/*! * ONNX Runtime Web v1.26.0-dev.20260416-b7804b056c * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var Eh=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,n1=Object.getOwnPropertyNames,s1=Object.prototype.hasOwnProperty,a1=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Te=(e,t)=>()=>(e&&(t=e(e=0)),t),bi=(e,t)=>{for(var r in t)Eh(e,r,{get:t[r],enumerable:!0})},o1=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of n1(t))!s1.call(e,s)&&s!==r&&Eh(e,s,{get:()=>t[s],enumerable:!(n=r1(t,s))||n.enumerable});return e},ol=e=>o1(Eh({},"__esModule",{value:!0}),e),ei,Qr,Jn,Om,Nw,Bw=Te(()=>{ei=new Map,Qr=[],Jn=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=ei.get(e);if(n===void 0)ei.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=Qr.indexOf(e);s!==-1&&Qr.splice(s,1);for(let a=0;a{let t=ei.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Nw=async e=>{let t=e.executionProviders||[],r=t.map(u=>typeof u=="string"?u:u.name),n=r.length===0?Qr:r,s,a=[],i=new Set;for(let u of n){let h=await Om(u);typeof h=="string"?a.push({name:u,err:h}):(s||(s=h),s===h&&i.add(u))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:h}of a)r.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${h}`);let c=t.filter(u=>i.has(typeof u=="string"?u:u.name));return[s,new Proxy(e,{get:(u,h)=>h==="executionProviders"?c:Reflect.get(u,h)})]}}),i1=Te(()=>{Bw()}),$w,l1=Te(()=>{$w="1.24.0-dev.20251116-b39e144322"}),Zd,gt,Dw=Te(()=>{l1(),Zd="warning",gt={wasm:{},webgl:{},webgpu:{},versions:{common:$w},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Zd=e}},get logLevel(){return Zd}},Object.defineProperty(gt,"logLevel",{enumerable:!0})}),He,c1=Te(()=>{Dw(),He=gt}),Rw,zw,u1=Te(()=>{Rw=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",c=t?.norm,u,h;c===void 0||c.mean===void 0?u=[255,255,255,255]:typeof c.mean=="number"?u=[c.mean,c.mean,c.mean,c.mean]:(u=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(u[3]=c.mean[3])),c===void 0||c.bias===void 0?h=[0,0,0,0]:typeof c.bias=="number"?h=[c.bias,c.bias,c.bias,c.bias]:(h=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(h[3]=c.bias[3]));let p=a*s,_=0,m=p,w=p*2,b=-1;i==="RGBA"?(_=0,m=p,w=p*2,b=p*3):i==="RGB"?(_=0,m=p,w=p*2):i==="RBG"&&(_=0,w=p,m=p*2);for(let M=0;M{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",u=t?.norm,h,p;u===void 0||u.mean===void 0?h=[255,255,255,255]:typeof u.mean=="number"?h=[u.mean,u.mean,u.mean,u.mean]:(h=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(h[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let _=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,w=0,b=1,M=2,E=3,T=0,C=_,P=_*2,A=-1;c==="RGBA"?(T=0,C=_,P=_*2,A=_*3):c==="RGB"?(T=0,C=_,P=_*2):c==="RBG"&&(T=0,P=_,C=_*2),n=r.createImageData(s,a);for(let F=0;F{kh(),Ni=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",u=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,p=u==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),_=4,m=0,w=1,b=2,M=3,E=0,T=h,C=h*2,P=-1;c==="RGB"&&(_=3,m=0,w=1,b=2,M=-1),u==="RGBA"?P=h*3:u==="RBG"?(E=0,C=h,T=h*2):u==="BGR"&&(C=0,T=h,E=h*2);for(let A=0;A{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,c=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=u();p.width=e.width,p.height=e.height;let _=h(p);if(_!=null){let m=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(m=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=m,c.width=w}else c.tensorFormat="RGBA",c.height=m,c.width=w;_.drawImage(e,0,0),i=_.getImageData(0,0,w,m).data}else throw new Error("Can not access image data")}else if(n){let p,_;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,_=t.resizedWidth):(p=e.height,_=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=p,c.width=_,t!==void 0){let m=u();m.width=_,m.height=p;let w=h(m);if(w!=null)w.putImageData(e,0,0),i=w.getImageData(0,0,_,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=u();p.width=e.width,p.height=e.height;let _=h(p);if(_!=null){let m=e.height,w=e.width;return _.drawImage(e,0,0,w,m),i=_.getImageData(0,0,w,m).data,c.height=m,c.width=w,Ni(i,c)}else throw new Error("Can not access image data")}else{if(a)return new Promise((p,_)=>{let m=u(),w=h(m);if(!e||!w)return _();let b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{m.width=b.width,m.height=b.height,w.drawImage(b,0,0,m.width,m.height);let M=w.getImageData(0,0,m.width,m.height);c.height=m.height,c.width=m.width,p(Ni(M.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ni(i,c);throw new Error("Input data provided is not supported - aborted tensor creation")},Uw=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new jt({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},Vw=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new jt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},Ww=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new jt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},jw=(e,t,r)=>new jt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),qn,fi,ef,qw,f1=Te(()=>{qn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),fi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ef=!1,qw=()=>{if(!ef){ef=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(qn.set("int64",BigInt64Array),fi.set(BigInt64Array,"int64")),t&&(qn.set("uint64",BigUint64Array),fi.set(BigUint64Array,"uint64")),n?(qn.set("float16",r),fi.set(r,"float16")):qn.set("float16",Uint16Array)}}}),Hw,Qw,h1=Te(()=>{kh(),Hw=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new jt(e.type,e.data,t);case"cpu-pinned":return new jt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new jt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new jt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new jt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),jt,kh=Te(()=>{u1(),d1(),f1(),h1(),jt=class{constructor(e,t,r){qw();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=qn.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,c;if(typeof e=="string")if(n=e,c=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let u=qn.get(e);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&u===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${u.name} as data.`);e==="uint64"||e==="int64"?i=u.from(t,BigInt):i=u.from(t)}else if(t instanceof u)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&u!==Uint16Array)i=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${u}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let u=typeof e[0];if(u==="string")n="string",i=e;else if(u==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let u=fi.get(e.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=u,i=e}if(c===void 0)c=[i.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");s=c,this.cpuData=i,this.dataLocation="cpu"}let a=Hw(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Gw(e,t)}static fromTexture(e,t){return Uw(e,t)}static fromGpuBuffer(e,t){return Vw(e,t)}static fromMLTensor(e,t){return Ww(e,t)}static fromPinnedBuffer(e,t,r){return jw(e,t,r)}toDataURL(e){return Rw(this,e)}toImageData(e){return zw(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Qw(this,e)}}}),ur,Yw=Te(()=>{kh(),ur=jt}),il,tf,ts,rs,an,on,Xw=Te(()=>{Dw(),il=(e,t)=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||console.timeStamp(`${e}::ORT::${t}`)},tf=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||tf("BEGIN",e)},rs=e=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||tf("END",e)},an=e=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||console.time(`ORT::${e}`)},on=e=>{(typeof gt.trace>"u"?!gt.wasm.trace:!gt.trace)||console.timeEnd(`ORT::${e}`)}}),Jw,p1=Te(()=>{Bw(),Yw(),Xw(),Jw=class Kw{constructor(t){this.handler=t}async run(t,r,n){ts(),an("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof ur||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ur)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);s[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,p=Object.getOwnPropertyNames(r);for(let _ of this.outputNames)if(p.indexOf(_)!==-1){let m=r[_];(m===null||m instanceof ur)&&(h=!0,i=!1,s[_]=m)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)s[h]=null;let c=await this.handler.run(t,s,a),u={};for(let h in c)if(Object.hasOwnProperty.call(c,h)){let p=c[h];p instanceof ur?u[h]=p:u[h]=new ur(p.type,p.data,p.dims)}return on("InferenceSession.run"),rs(),u}async release(){return this.handler.dispose()}static async create(t,r,n,s){ts(),an("InferenceSession.create");let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let p=t,_=0,m=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(_=r,!Number.isSafeInteger(_))throw new RangeError("'byteOffset' must be an integer.");if(_<0||_>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(m=t.byteLength-_,typeof n=="number"){if(m=n,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||_+m>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-_}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(p,_,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,u]=await Nw(i),h=await c.createInferenceSessionHandler(a,u);return on("InferenceSession.create"),rs(),new Kw(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ch,_1=Te(()=>{p1(),Ch=Jw}),m1=Te(()=>{}),g1=Te(()=>{}),w1=Te(()=>{}),y1=Te(()=>{}),Zw={};bi(Zw,{InferenceSession:()=>Ch,TRACE:()=>il,TRACE_EVENT_BEGIN:()=>an,TRACE_EVENT_END:()=>on,TRACE_FUNC_BEGIN:()=>ts,TRACE_FUNC_END:()=>rs,Tensor:()=>ur,env:()=>He,registerBackend:()=>Jn});var ns=Te(()=>{i1(),c1(),_1(),Yw(),m1(),g1(),Xw(),w1(),y1()}),Ah=Te(()=>{}),ey={};bi(ey,{default:()=>ty});var rf,nf,ty,v1=Te(()=>{my(),ss(),Sh(),rf="ort-wasm-proxy-worker",nf=globalThis.self?.name===rf,nf&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Ph(r.wasm).then(()=>{Nh(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;Bh(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=ul(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;$h(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":Dh(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:i,options:c}=r;Rh(n,s,a,i,new Array(i.length).fill(null),c).then(u=>{u.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},Gh([...a,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":zh(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),ty=nf?null:e=>new Worker(e??Gt,{type:"module",name:rf})}),ry={};bi(ry,{default:()=>ny});async function Nm(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(o,l)=>{o.startsWith("./")&&(o=o.substring(2)),(t.Uc||(t.Uc=new Map)).set(o,l)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let o=l=>(...d)=>{let f=tt;return d=l(...d),tt!=f?new Promise((g,y)=>{yn={resolve:g,reject:y}}):d};(()=>{for(let l of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[l]=o(t[l])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var i,c,u=(o,l)=>{throw l},h=import.meta.url,p="";if(r||n){try{p=new URL(".",h).href}catch{}n&&(c=o=>{var l=new XMLHttpRequest;return l.open("GET",o,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),i=async o=>{if(G(o))return new Promise((d,f)=>{var g=new XMLHttpRequest;g.open("GET",o,!0),g.responseType="arraybuffer",g.onload=()=>{g.status==200||g.status==0&&g.response?d(g.response):f(g.status)},g.onerror=f,g.send(null)});var l=await fetch(o,{credentials:"same-origin"});if(l.ok)return l.arrayBuffer();throw Error(l.status+" : "+l.url)}}var _,m,w,b,M,E,T=console.log.bind(console),C=console.error.bind(console),P=T,A=C,F=!1,G=o=>o.startsWith("file://");function v(){bt.buffer!=U.buffer&&Q()}if(s){let o=function(l){try{var d=l.data,f=d.Oc;if(f==="load"){let g=[];self.onmessage=y=>g.push(y),E=()=>{postMessage({Oc:"loaded"});for(let y of g)o(y);self.onmessage=o};for(let y of d.ce)t[y]&&!t[y].proxy||(t[y]=(...x)=>{postMessage({Oc:"callHandler",be:y,args:x})},y=="print"&&(P=t[y]),y=="printErr"&&(A=t[y]));bt=d.ie,Q(),m=d.je,nt(),Rr()}else if(f==="run"){(function(g){var y=(v(),S)[g+52>>>2>>>0];g=(v(),S)[g+56>>>2>>>0],uo(y,y-g),X(y)})(d.Nc),Fn(d.Nc,0,0,1,0,0),Js(),mn(d.Nc),j||(qa(),j=!0);try{rc(d.ge,d.Wc)}catch(g){if(g!="unwind")throw g}}else d.target!=="setimmediate"&&(f==="checkMailbox"?j&&Fr():f&&(A(`worker: received unknown command ${f}`),A(d)))}catch(g){throw ao(),g}};var j=!1;self.onunhandledrejection=l=>{throw l.reason||l},self.onmessage=o}var U,q,ne,H,I,S,D,Y,se,N,$,z=!1;function Q(){var o=bt.buffer;t.HEAP8=U=new Int8Array(o),ne=new Int16Array(o),t.HEAPU8=q=new Uint8Array(o),H=new Uint16Array(o),t.HEAP32=I=new Int32Array(o),t.HEAPU32=S=new Uint32Array(o),D=new Float32Array(o),Y=new Float64Array(o),se=new BigInt64Array(o),N=new BigUint64Array(o)}function _e(){z=!0,s?E():dt._b()}function me(o){throw A(o="Aborted("+o+")"),F=!0,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),M?.(o),o}function de(){return{a:{f:nc,J:sc,k:ac,p:oc,l:ic,sa:lc,b:cc,ca:uc,Ja:na,q:dc,da:ia,Za:la,Fa:ca,Ha:ua,_a:da,Xa:fa,Qa:ha,Wa:pa,oa:_a,Ga:ma,Xb:ga,Ya:wa,Yb:ya,db:fc,Da:hc,Sb:pc,Qb:mc,Ca:wc,M:yc,I:vc,Rb:bc,ja:Ac,Tb:Sc,Ta:Pc,Vb:Ic,Ka:Lc,Ob:Oc,ka:Nc,Sa:mn,ab:Bc,U:zc,n:jc,c:pn,rb:qc,w:Hc,L:Qc,z:Yc,j:Xc,o:Ca,sb:Jc,G:Kc,T:Zc,h:eu,u:tu,m:ru,i:nu,Na:su,Oa:au,Pa:ou,La:Fa,Ma:Ia,Pb:La,eb:lu,cb:uu,Y:du,qb:fu,la:hu,bb:cu,fb:pu,$a:_u,Wb:mu,N:iu,gb:gu,X:wu,Ub:yu,nb:Au,C:Su,ra:Pu,qa:Fu,pb:Iu,W:Lu,v:Ou,mb:Nu,lb:Bu,kb:$u,ob:Du,jb:Ru,ib:zu,hb:Gu,Ua:Ra,Va:za,Ia:wr,V:Ga,na:Ua,Ra:Va,ma:Wa,Cb:Jd,xa:jd,Db:Xd,ya:Wd,F:Ld,e:vd,s:wd,x:gd,B:Pd,Fb:Gd,ba:zd,D:xd,za:Ud,$:qd,ga:Rd,Gb:Dd,Hb:$d,Ba:Od,Aa:Bd,Ib:Nd,wa:Yd,aa:Vd,d:yd,A:Md,r:bd,Bb:Kd,t:Ed,y:Fd,H:Td,E:kd,K:Id,R:Hd,ia:Sd,_:Qd,Jb:Ad,Kb:Cd,g:Vu,a:bt,Nb:gr,Eb:Wu,ha:ju,O:qu,pa:Hu,Lb:Qu,ta:Yu,Q:Xu,yb:Ju,zb:Ku,ua:Zu,ea:ed,P:td,Ea:rd,va:nd,Z:sd,wb:ad,Zb:od,S:id,Ab:ld,tb:cd,ub:dd,vb:fd,fa:hd,xb:pd,Mb:_d}}}async function nt(){function o(f,g){var y=dt=f.exports;f={};for(let[x,k]of Object.entries(y))typeof k=="function"?(y=$c(k),f[x]=y):f[x]=k;return dt=f,dt=(function(){var x=dt,k=B=>re=>B(re)>>>0,L=B=>()=>B()>>>0;return(x=Object.assign({},x)).$b=k(x.$b),x.Cc=L(x.Cc),x.Ec=k(x.Ec),x.rd=(B=>(re,R)=>B(re,R)>>>0)(x.rd),x.wd=k(x.wd),x.xd=L(x.xd),x.Bd=k(x.Bd),x})(),Ys.push(dt.id),ja=(f=dt).$b,qa=f.ac,t._OrtInit=f.bc,t._OrtGetLastError=f.cc,t._OrtCreateSessionOptions=f.dc,t._OrtAppendExecutionProvider=f.ec,t._OrtAddFreeDimensionOverride=f.fc,t._OrtAddSessionConfigEntry=f.gc,t._OrtReleaseSessionOptions=f.hc,t._OrtCreateSession=f.ic,t._OrtReleaseSession=f.jc,t._OrtGetInputOutputCount=f.kc,t._OrtGetInputOutputMetadata=f.lc,t._OrtFree=f.mc,t._OrtCreateTensor=f.nc,t._OrtGetTensorData=f.oc,t._OrtReleaseTensor=f.pc,t._OrtCreateRunOptions=f.qc,t._OrtAddRunConfigEntry=f.rc,t._OrtReleaseRunOptions=f.sc,t._OrtCreateBinding=f.tc,t._OrtBindInput=f.uc,t._OrtBindOutput=f.vc,t._OrtClearBoundOutputs=f.wc,t._OrtReleaseBinding=f.xc,t._OrtRunWithBinding=f.yc,t._OrtRun=f.zc,t._OrtEndProfiling=f.Ac,En=t._OrtGetWebGpuDevice=f.Bc,$r=f.Cc,Je=t._free=f.Dc,Rt=t._malloc=f.Ec,Ha=t._wgpuBufferRelease=f.Fc,Qa=t._wgpuCreateInstance=f.Gc,Ya=f.Hc,Xa=f.Ic,Ja=f.Jc,Ka=f.Kc,Za=f.Lc,eo=f.Pc,to=f.Zc,ro=f._c,no=f.$c,kn=f.bd,Cn=f.cd,An=f.dd,Sn=f.ed,ir=f.fd,Pn=f.gd,so=f.hd,Fn=f.kd,ao=f.ld,oo=f.md,io=f.nd,In=f.od,lo=f.pd,co=f.qd,Ln=f.rd,te=f.sd,lr=f.td,uo=f.ud,X=f.vd,Dr=f.wd,J=f.xd,fo=f.yd,On=f.zd,ho=f.Ad,po=f.Bd,_o=f.Cd,Nn=f.Dd,mo=f.Ed,go=f.Fd,wo=f.Gd,yo=f.Hd,vo=f.Id,bo=f.Jd,Mo=f.Kd,xo=f.Ld,To=f.Md,Eo=f.Nd,ko=f.Od,Co=f.Pd,Ao=f.Qd,So=f.Rd,Po=f.Td,Fo=f.Ud,Io=f.Vd,Lo=f.Wd,Oo=f.Yd,No=f.Zd,Bo=f._d,$o=f.$d,Do=f.ae,Ro=f.oe,zo=f.pe,Go=f.qe,Uo=f.re,Vo=f.se,Wo=f.te,jo=f.ue,qo=f.ve,Ho=f.we,Qo=f.xe,Yo=f.ye,Xo=f.Ye,Jo=f.Ze,Ko=f._e,Zo=f.$e,m=g,dt}var l,d=de();return t.instantiateWasm?new Promise(f=>{t.instantiateWasm(d,(g,y)=>{f(o(g,y))})}):s?o(new WebAssembly.Instance(m,de()),m):($??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",import.meta.url).href,l=await(async function(f){var g=$;if(!_&&!G(g))try{var y=fetch(g,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(y,f)}catch(x){A(`wasm streaming compile failed: ${x}`),A("falling back to ArrayBuffer instantiation")}return(async function(x,k){try{var L=await(async function(B){if(!_)try{var re=await i(B);return new Uint8Array(re)}catch{}if(B==$&&_)B=new Uint8Array(_);else{if(!c)throw"both async and sync fetching of the wasm failed";B=c(B)}return B})(x);return await WebAssembly.instantiate(L,k)}catch(B){A(`failed to asynchronously prepare wasm: ${B}`),me(B)}})(g,f)})(d),o(l.instance,l.module))}class ye{name="ExitStatus";constructor(l){this.message=`Program terminated with exit(${l})`,this.status=l}}var $e=o=>{o.terminate(),o.onmessage=()=>{}},qe=[],ue=0,oe=null,Re=o=>{vt.length==0&&(Zs(),Ks(vt[0]));var l=vt.pop();if(!l)return 6;sr.push(l),It[o.Nc]=l,l.Nc=o.Nc;var d={Oc:"run",ge:o.fe,Wc:o.Wc,Nc:o.Nc};return l.postMessage(d,o.Yc),0},ie=0,le=(o,l,...d)=>{var f,g=16*d.length,y=J(),x=Dr(g),k=x>>>3;for(f of d)typeof f=="bigint"?((v(),se)[k++>>>0]=1n,(v(),se)[k++>>>0]=f):((v(),se)[k++>>>0]=0n,(v(),Y)[k++>>>0]=f);return o=oo(o,0,g,x,l),X(y),o};function gr(o){if(s)return le(0,1,o);if(w=o,!(0{if(w=o,s)throw Hr(o),"unwind";gr(o)},vt=[],sr=[],Ys=[],It={},Xs=o=>{var l=o.Nc;delete It[l],vt.push(o),sr.splice(sr.indexOf(o),1),o.Nc=0,io(l)};function Js(){Ys.forEach(o=>o())}var Ks=o=>new Promise(l=>{o.onmessage=g=>{var y=g.data;if(g=y.Oc,y.Vc&&y.Vc!=$r()){var x=It[y.Vc];x?x.postMessage(y,y.Yc):A(`Internal error! Worker sent a message "${g}" to target pthread ${y.Vc}, but that thread no longer exists!`)}else g==="checkMailbox"?Fr():g==="spawnThread"?Re(y):g==="cleanupThread"?Le(()=>{Xs(It[y.he])}):g==="loaded"?(o.loaded=!0,l(o)):y.target==="setimmediate"?o.postMessage(y):g==="uncaughtException"?o.onerror(y.error):g==="callHandler"?t[y.be](...y.args):g&&A(`worker sent an unknown command ${g}`)},o.onerror=g=>{throw A(`worker sent an error! ${g.filename}:${g.lineno}: ${g.message}`),g};var d,f=[];for(d of[])t.propertyIsEnumerable(d)&&f.push(d);o.postMessage({Oc:"load",ce:f,ie:bt,je:m})});function Zs(){var o=new Worker((()=>{let l=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new l("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});vt.push(o)}var bt,rc=(o,l)=>{ie=0,o=Nn(o,l),0-9007199254740992>o||9007199254740992>>=0);return(v(),U)[l.Qc+12>>>0]==0&&(ea(l,!0),Pr--),ta(l,!1),Sr.push(l),po(o)}var Nt=0,sc=()=>{te(0,0);var o=Sr.pop();fo(o.Xc),Nt=0};function ea(o,l){l=l?1:0,(v(),U)[o.Qc+12>>>0]=l}function ta(o,l){l=l?1:0,(v(),U)[o.Qc+13>>>0]=l}class un{constructor(l){this.Xc=l,this.Qc=l-24}}var dn=o=>{var l=Nt;if(!l)return lr(0),0;var d=new un(l);(v(),S)[d.Qc+16>>>2>>>0]=l;var f=(v(),S)[d.Qc+4>>>2>>>0];if(!f)return lr(0),l;for(var g of o){if(g===0||g===f)break;if(ho(g,f,d.Qc+16))return lr(g),l}return lr(f),l};function ac(){return dn([])}function oc(o){return dn([o>>>0])}function ic(o,l,d,f){return dn([o>>>0,l>>>0,d>>>0,f>>>0])}var lc=()=>{var o=Sr.pop();o||me("no exception to throw");var l=o.Xc;throw(v(),U)[o.Qc+13>>>0]==0&&(Sr.push(o),ta(o,!0),ea(o,!1),Pr++),On(l),Nt=l};function cc(o,l,d){var f=new un(o>>>=0);throw l>>>=0,d>>>=0,(v(),S)[f.Qc+16>>>2>>>0]=0,(v(),S)[f.Qc+4>>>2>>>0]=l,(v(),S)[f.Qc+8>>>2>>>0]=d,On(o),Pr++,Nt=o}var uc=()=>Pr;function ra(o,l,d,f){return s?le(2,1,o,l,d,f):na(o,l,d,f)}function na(o,l,d,f){if(o>>>=0,l>>>=0,d>>>=0,f>>>=0,!globalThis.SharedArrayBuffer)return 6;var g=[];return s&&g.length===0?ra(o,l,d,f):(o={fe:d,Nc:o,Wc:f,Yc:g},s?(o.Oc="spawnThread",postMessage(o,g),0):Re(o))}function dc(o){throw Nt||=o>>>0,Nt}var sa=globalThis.TextDecoder&&new TextDecoder,aa=(o,l,d,f)=>{if(d=l+d,f)return d;for(;o[l]&&!(l>=d);)++l;return l},oa=(o,l=0,d,f)=>{if(16<(d=aa(o,l>>>=0,d,f))-l&&o.buffer&&sa)return sa.decode(o.buffer instanceof ArrayBuffer?o.subarray(l,d):o.slice(l,d));for(f="";l(g=(240&g)==224?(15&g)<<12|y<<6|x:(7&g)<<18|y<<12|x<<6|63&o[l++])?f+=String.fromCharCode(g):(g-=65536,f+=String.fromCharCode(55296|g>>10,56320|1023&g))}}else f+=String.fromCharCode(g)}return f},Bt=(o,l,d)=>(o>>>=0)?oa((v(),q),o,l,d):"";function ia(o,l,d){return s?le(3,1,o,l,d):0}function la(o,l){if(s)return le(4,1,o,l)}function ca(o,l){if(s)return le(5,1,o,l)}function ua(o,l,d){if(s)return le(6,1,o,l,d)}function da(o,l,d){return s?le(7,1,o,l,d):0}function fa(o,l){if(s)return le(8,1,o,l)}function ha(o,l,d){if(s)return le(9,1,o,l,d)}function pa(o,l,d,f){if(s)return le(10,1,o,l,d,f)}function _a(o,l,d,f){if(s)return le(11,1,o,l,d,f)}function ma(o,l,d,f){if(s)return le(12,1,o,l,d,f)}function ga(o){if(s)return le(13,1,o)}function wa(o,l){if(s)return le(14,1,o,l)}function ya(o,l,d){if(s)return le(15,1,o,l,d)}var fc=()=>me(""),et=o=>{o>>>=0;for(var l="";;){var d=(v(),q)[o++>>>0];if(!d)return l;l+=String.fromCharCode(d)}},fn={},hn={},$t=class extends Error{constructor(o){super(o),this.name="BindingError"}};function ot(o,l,d={}){return(function(f,g,y={}){var x=g.name;if(!f)throw new $t(`type "${x}" must have a positive integer typeid pointer`);if(hn.hasOwnProperty(f)){if(y.de)return;throw new $t(`Cannot register type '${x}' twice`)}hn[f]=g,fn.hasOwnProperty(f)&&(g=fn[f],delete fn[f],g.forEach(k=>k()))})(o,l,d)}var va=(o,l,d)=>{switch(l){case 1:return d?f=>(v(),U)[f>>>0]:f=>(v(),q)[f>>>0];case 2:return d?f=>(v(),ne)[f>>>1>>>0]:f=>(v(),H)[f>>>1>>>0];case 4:return d?f=>(v(),I)[f>>>2>>>0]:f=>(v(),S)[f>>>2>>>0];case 8:return d?f=>(v(),se)[f>>>3>>>0]:f=>(v(),N)[f>>>3>>>0];default:throw new TypeError(`invalid integer width (${l}): ${o}`)}};function hc(o,l,d,f,g){o>>>=0,d>>>=0,l=et(l>>>0);let y=x=>x;if(f=f===0n){let x=8*d;y=k=>BigInt.asUintN(x,k),g=y(g)}ot(o,{name:l,Mc:y,Sc:(x,k)=>(typeof k=="number"&&(k=BigInt(k)),k),Rc:va(l,d,!f),Tc:null})}function pc(o,l,d,f){ot(o>>>=0,{name:l=et(l>>>0),Mc:function(g){return!!g},Sc:function(g,y){return y?d:f},Rc:function(g){return this.Mc((v(),q)[g>>>0])},Tc:null})}var ba=[],Lt=[0,1,,1,null,1,!0,1,!1,1];function pn(o){9<(o>>>=0)&&--Lt[o+1]==0&&(Lt[o]=void 0,ba.push(o))}var Ue=o=>{if(!o)throw new $t(`Cannot use deleted val. handle = ${o}`);return Lt[o]},Xe=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=ba.pop()||Lt.length;return Lt[l]=o,Lt[l+1]=1,l}};function _n(o){return this.Mc((v(),S)[o>>>2>>>0])}var _c={name:"emscripten::val",Mc:o=>{var l=Ue(o);return pn(o),l},Sc:(o,l)=>Xe(l),Rc:_n,Tc:null};function mc(o){return ot(o>>>0,_c)}var gc=(o,l)=>{switch(l){case 4:return function(d){return this.Mc((v(),D)[d>>>2>>>0])};case 8:return function(d){return this.Mc((v(),Y)[d>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${o}`)}};function wc(o,l,d){d>>>=0,ot(o>>>=0,{name:l=et(l>>>0),Mc:f=>f,Sc:(f,g)=>g,Rc:gc(l,d),Tc:null})}function yc(o,l,d,f,g){o>>>=0,d>>>=0,l=et(l>>>0);let y=k=>k;if(f===0){var x=32-8*d;y=k=>k<>>x,g=y(g)}ot(o,{name:l,Mc:y,Sc:(k,L)=>L,Rc:va(l,d,f!==0),Tc:null})}function vc(o,l,d){function f(y){var x=(v(),S)[y>>>2>>>0];return y=(v(),S)[y+4>>>2>>>0],new g((v(),U).buffer,y,x)}var g=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];ot(o>>>=0,{name:d=et(d>>>0),Mc:f,Rc:f},{de:!0})}var it=(o,l,d)=>{var f=(v(),q);if(l>>>=0,0=x){if(l>=d)break;f[l++>>>0]=x}else if(2047>=x){if(l+1>=d)break;f[l++>>>0]=192|x>>6,f[l++>>>0]=128|63&x}else if(65535>=x){if(l+2>=d)break;f[l++>>>0]=224|x>>12,f[l++>>>0]=128|x>>6&63,f[l++>>>0]=128|63&x}else{if(l+3>=d)break;f[l++>>>0]=240|x>>18,f[l++>>>0]=128|x>>12&63,f[l++>>>0]=128|x>>6&63,f[l++>>>0]=128|63&x,y++}}f[l>>>0]=0,o=l-g}else o=0;return o},lt=o=>{for(var l=0,d=0;d=f?l++:2047>=f?l+=2:55296<=f&&57343>=f?(l+=4,++d):l+=3}return l};function bc(o,l){ot(o>>>=0,{name:l=et(l>>>0),Mc(d){var f=(v(),S)[d>>>2>>>0];return f=Bt(d+4,f,!0),Je(d),f},Sc(d,f){f instanceof ArrayBuffer&&(f=new Uint8Array(f));var g=typeof f=="string";if(!(g||ArrayBuffer.isView(f)&&f.BYTES_PER_ELEMENT==1))throw new $t("Cannot pass non-string to std::string");var y=g?lt(f):f.length,x=Rt(4+y+1),k=x+4;return(v(),S)[x>>>2>>>0]=y,g?it(f,k,y+1):(v(),q).set(f,k>>>0),d!==null&&d.push(Je,x),x},Rc:_n,Tc(d){Je(d)}})}var Ma=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Mc=(o,l,d)=>{if(o>>>=1,16<(l=aa((v(),H),o,l/2,d))-o&&Ma)return Ma.decode((v(),H).slice(o,l));for(d="";o>>0];d+=String.fromCharCode(f)}return d},xc=(o,l,d)=>{if(d??=2147483647,2>d)return 0;var f=l;d=(d-=2)<2*o.length?d/2:o.length;for(var g=0;g>>1>>>0]=y,l+=2}return(v(),ne)[l>>>1>>>0]=0,l-f},Tc=o=>2*o.length,Ec=(o,l,d)=>{var f="";o>>>=2;for(var g=0;!(g>=l/4);g++){var y=(v(),S)[o+g>>>0];if(!y&&!d)break;f+=String.fromCodePoint(y)}return f},kc=(o,l,d)=>{if(l>>>=0,d??=2147483647,4>d)return 0;var f=l;d=f+d-4;for(var g=0;g>>2>>>0]=y,(l+=4)+4>d)break}return(v(),I)[l>>>2>>>0]=0,l-f},Cc=o=>{for(var l=0,d=0;d>>=0,l>>>=0,d=et(d>>>=0),l===2)var f=Mc,g=xc,y=Tc;else f=Ec,g=kc,y=Cc;ot(o,{name:d,Mc:x=>{var k=(v(),S)[x>>>2>>>0];return k=f(x+4,k*l,!0),Je(x),k},Sc:(x,k)=>{if(typeof k!="string")throw new $t(`Cannot pass non-string to C++ string type ${d}`);var L=y(k),B=Rt(4+L+l);return(v(),S)[B>>>2>>>0]=L/l,g(k,B+4,L+l),x!==null&&x.push(Je,B),B},Rc:_n,Tc(x){Je(x)}})}function Sc(o,l){ot(o>>>=0,{ee:!0,name:l=et(l>>>0),Mc:()=>{},Sc:()=>{}})}function Pc(o){Fn(o>>>0,!n,1,!r,131072,!1),Js()}var Le=o=>{if(!F)try{if(o(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function mn(o){o>>>=0,Fc||(Atomics.waitAsync((v(),I),o>>>2,o).value.then(Fr),o+=128,Atomics.store((v(),I),o>>>2,1))}var Fr=()=>Le(()=>{var o=$r();o&&(mn(o),co())});function Ic(o,l){(o>>>=0)==l>>>0?setTimeout(Fr):s?postMessage({Vc:o,Oc:"checkMailbox"}):(o=It[o])&&o.postMessage({Oc:"checkMailbox"})}var gn=[];function Lc(o,l,d,f,g){for(l>>>=0,g>>>=0,gn.length=0,d=g>>>3,f=g+f>>>3;d>>0]?(v(),se)[d++>>>0]:(v(),Y)[d++>>>0],gn.push(y)}return(l?Bn[l]:md[o])(...gn)}var Oc=()=>{ie=0};function Nc(o){o>>>=0,s?postMessage({Oc:"cleanupThread",he:o}):Xs(It[o])}function Bc(o){}var Ir=o=>{try{o()}catch(l){me(l)}};function $c(o){var l=(...d)=>{Lr.push(o);try{return o(...d)}finally{F||(Lr.pop(),tt&&Mt===1&&Lr.length===0&&(Mt=0,ie+=1,Ir(Jo),typeof Fibers<"u"&&Fibers.Be()))}};return Ea.set(o,l),l}var Mt=0,tt=null,xa=0,Lr=[],wn=new Map,Ta=new Map,Ea=new Map,Dc=0,yn=null,Rc=[],ka=o=>(function(l){if(!F){if(Mt===0){var d=!1,f=!1;l((g=0)=>{if(!F&&(xa=g,d=!0,f)){Mt=2,Ir(()=>Ko(tt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),g=!1;try{var y=(function(){var L=(v(),I)[tt+8>>>2>>>0];return L=Ta.get(L),L=Ea.get(L),--ie,L()})()}catch(L){y=L,g=!0}var x=!1;if(!tt){var k=yn;k&&(yn=null,(g?k.reject:k.resolve)(y),x=!0)}if(g&&!x)throw y}}),f=!0,d||(Mt=1,tt=(function(){var g=Rt(65548),y=g+12;if((v(),S)[g>>>2>>>0]=y,(v(),S)[g+4>>>2>>>0]=y+65536,y=Lr[0],!wn.has(y)){var x=Dc++;wn.set(y,x),Ta.set(x,y)}return y=wn.get(y),(v(),I)[g+8>>>2>>>0]=y,g})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ir(()=>Xo(tt)))}else Mt===2?(Mt=0,Ir(Zo),Je(tt),tt=null,Rc.forEach(Le)):me(`invalid state: ${Mt}`);return xa}})(l=>{o().then(l)});function zc(o){return o>>>=0,ka(async()=>{var l=await Ue(o);return Xe(l)})}var vn=[],Gc=o=>{var l=vn.length;return vn.push(o),l},Uc=(o,l)=>{for(var d=Array(o),f=0;f>>2>>>0],x=hn[y];if(x===void 0)throw o=`parameter ${f}`,y=ja(y),l=et(y),Je(y),new $t(`${o} has unknown type ${l}`);d[g]=x}return d},Vc=(o,l,d)=>{var f=[];return o=o(f,d),f.length&&((v(),S)[l>>>2>>>0]=Xe(f)),o},Wc={},Or=o=>{var l=Wc[o];return l===void 0?et(o):l};function jc(o,l,d){var[f,...g]=Uc(o,l>>>0);l=f.Sc.bind(f);var y=g.map(L=>L.Rc.bind(L));o--;var x={toValue:Ue};switch(o=y.map((L,B)=>{var re=`argFromPtr${B}`;return x[re]=L,`${re}(args${B?"+"+8*B:""})`}),d){case 0:var k="toValue(handle)";break;case 2:k="new (toValue(handle))";break;case 3:k="";break;case 1:x.getStringOrSymbol=Or,k="toValue(handle)[getStringOrSymbol(methodName)]"}return k+=`(${o})`,f.ee||(x.toReturnWire=l,x.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`),k=`return function (handle, methodName, destructorsRef, args) { ${k} }`,d=new Function(Object.keys(x),k)(...Object.values(x)),k=`methodCaller<(${g.map(L=>L.name)}) => ${f.name}>`,Gc(Object.defineProperty(d,"name",{value:k}))}function qc(o,l){return l>>>=0,(o=Ue(o>>>0))==Ue(l)}function Hc(o){return(o>>>=0)?(o=Or(o),Xe(globalThis[o])):Xe(globalThis)}function Qc(o){return o=Or(o>>>0),Xe(t[o])}function Yc(o,l){return l>>>=0,o=Ue(o>>>0),l=Ue(l),Xe(o[l])}function Xc(o){9<(o>>>=0)&&(Lt[o+1]+=1)}function Ca(o,l,d,f,g){return vn[o>>>0](l>>>0,d>>>0,f>>>0,g>>>0)}function Jc(o,l,d,f,g){return Ca(o>>>0,l>>>0,d>>>0,f>>>0,g>>>0)}function Kc(){return Xe([])}function Zc(o){o=Ue(o>>>0);for(var l=Array(o.length),d=0;d>>0))}function tu(){return Xe({})}function ru(o){for(var l=Ue(o>>>=0);l.length;){var d=l.pop();l.pop()(d)}pn(o)}function nu(o,l,d){l>>>=0,d>>>=0,o=Ue(o>>>0),l=Ue(l),d=Ue(d),o[l]=d}function su(o,l){o=Ce(o),l>>>=0,o=new Date(1e3*o),(v(),I)[l>>>2>>>0]=o.getUTCSeconds(),(v(),I)[l+4>>>2>>>0]=o.getUTCMinutes(),(v(),I)[l+8>>>2>>>0]=o.getUTCHours(),(v(),I)[l+12>>>2>>>0]=o.getUTCDate(),(v(),I)[l+16>>>2>>>0]=o.getUTCMonth(),(v(),I)[l+20>>>2>>>0]=o.getUTCFullYear()-1900,(v(),I)[l+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),I)[l+28>>>2>>>0]=o}var Aa=o=>o%4==0&&(o%100!=0||o%400==0),Sa=[0,31,60,91,121,152,182,213,244,274,305,335],Pa=[0,31,59,90,120,151,181,212,243,273,304,334];function au(o,l){o=Ce(o),l>>>=0,o=new Date(1e3*o),(v(),I)[l>>>2>>>0]=o.getSeconds(),(v(),I)[l+4>>>2>>>0]=o.getMinutes(),(v(),I)[l+8>>>2>>>0]=o.getHours(),(v(),I)[l+12>>>2>>>0]=o.getDate(),(v(),I)[l+16>>>2>>>0]=o.getMonth(),(v(),I)[l+20>>>2>>>0]=o.getFullYear()-1900,(v(),I)[l+24>>>2>>>0]=o.getDay();var d=(Aa(o.getFullYear())?Sa:Pa)[o.getMonth()]+o.getDate()-1|0;(v(),I)[l+28>>>2>>>0]=d,(v(),I)[l+36>>>2>>>0]=-60*o.getTimezoneOffset(),d=new Date(o.getFullYear(),6,1).getTimezoneOffset();var f=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(d!=f&&o.getTimezoneOffset()==Math.min(f,d)),(v(),I)[l+32>>>2>>>0]=o}function ou(o){o>>>=0;var l=new Date((v(),I)[o+20>>>2>>>0]+1900,(v(),I)[o+16>>>2>>>0],(v(),I)[o+12>>>2>>>0],(v(),I)[o+8>>>2>>>0],(v(),I)[o+4>>>2>>>0],(v(),I)[o>>>2>>>0],0),d=(v(),I)[o+32>>>2>>>0],f=l.getTimezoneOffset(),g=new Date(l.getFullYear(),6,1).getTimezoneOffset(),y=new Date(l.getFullYear(),0,1).getTimezoneOffset(),x=Math.min(y,g);return 0>d?(v(),I)[o+32>>>2>>>0]=+(g!=y&&x==f):0>>2>>>0]=l.getDay(),d=(Aa(l.getFullYear())?Sa:Pa)[l.getMonth()]+l.getDate()-1|0,(v(),I)[o+28>>>2>>>0]=d,(v(),I)[o>>>2>>>0]=l.getSeconds(),(v(),I)[o+4>>>2>>>0]=l.getMinutes(),(v(),I)[o+8>>>2>>>0]=l.getHours(),(v(),I)[o+12>>>2>>>0]=l.getDate(),(v(),I)[o+16>>>2>>>0]=l.getMonth(),(v(),I)[o+20>>>2>>>0]=l.getYear(),o=l.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Fa(o,l,d,f,g,y,x){return s?le(16,1,o,l,d,f,g,y,x):-52}function Ia(o,l,d,f,g,y){if(s)return le(17,1,o,l,d,f,g,y)}var ar={},iu=()=>performance.timeOrigin+performance.now();function La(o,l){if(s)return le(18,1,o,l);if(ar[o]&&(clearTimeout(ar[o].id),delete ar[o]),!l)return 0;var d=setTimeout(()=>{delete ar[o],Le(()=>lo(o,performance.timeOrigin+performance.now()))},l);return ar[o]={id:d,Ae:l},0}function lu(o,l,d,f){o>>>=0,l>>>=0,d>>>=0,f>>>=0;var g=new Date().getFullYear(),y=new Date(g,0,1).getTimezoneOffset();g=new Date(g,6,1).getTimezoneOffset();var x=Math.max(y,g);(v(),S)[o>>>2>>>0]=60*x,(v(),I)[l>>>2>>>0]=+(y!=g),o=(l=k=>{var L=Math.abs(k);return`UTC${0<=k?"-":"+"}${String(Math.floor(L/60)).padStart(2,"0")}${String(L%60).padStart(2,"0")}`})(y),l=l(g),gDate.now();function uu(o,l,d){return d>>>=0,0<=o&&3>=o?(o===0?o=Date.now():o=performance.timeOrigin+performance.now(),o=Math.round(1e6*o),(v(),se)[d>>>3>>>0]=BigInt(o),0):28}var bn=[],Oa=(o,l)=>{bn.length=0;for(var d;d=(v(),q)[o++>>>0];){var f=d!=105;l+=(f&=d!=112)&&l%8?4:0,bn.push(d==112?(v(),S)[l>>>2>>>0]:d==106?(v(),se)[l>>>3>>>0]:d==105?(v(),I)[l>>>2>>>0]:(v(),Y)[l>>>3>>>0]),l+=f?8:4}return bn};function du(o,l,d){return o>>>=0,l=Oa(l>>>0,d>>>0),Bn[o](...l)}function fu(o,l,d){return o>>>=0,l=Oa(l>>>0,d>>>0),Bn[o](...l)}var hu=()=>{};function pu(o,l){return A(Bt(o>>>0,l>>>0))}var _u=()=>{throw ie+=1,"unwind"};function mu(){return 4294901760}var gu=()=>1,wu=()=>navigator.hardwareConcurrency;function yu(o){o>>>=0;var l=(v(),q).length;if(o<=l||4294901760=d;d*=2){var f=l*(1+.2/d);f=Math.min(f,o+100663296);e:{f=(Math.min(4294901760,65536*Math.ceil(Math.max(o,f)/65536))-bt.buffer.byteLength+65535)/65536|0;try{bt.grow(f),Q();var g=1;break e}catch{}g=void 0}if(g)return!0}return!1}var rt=o=>{var l=lt(o)+1,d=Dr(l);return it(o,d,l),d},Mn=(o,l)=>{(v(),S)[o>>>2>>>0]=l;var d=(v(),S)[o>>>2>>>0];(v(),S)[o+4>>>2>>>0]=(l-d)/4294967296},or=o=>(v(),S)[o>>>2>>>0]+4294967296*(v(),I)[o+4>>>2>>>0],Ae=[],vu=(o,l)=>{Ae[o>>>0]=l},ct=[],Nr=[],Dt=(o,l)=>{Nr[o]=new Promise(d=>l.finally(()=>d(o)))},W=o=>{if(o)return Ae[o>>>0]},bu=(o,l)=>{for(o=(v(),S)[o>>>2>>>0];o;o=(v(),S)[o>>>2>>>0])l[(v(),I)[o+4>>>2>>>0]](o)},Br=(o,l,d)=>{(v(),S)[o>>>2>>>0]=l,(v(),S)[o+4>>>2>>>0]=d},Na=o=>{var l=(v(),S)[o>>>2>>>0];return o=(v(),S)[o+4>>>2>>>0],Bt(l,o)},ut=o=>{var l=(v(),S)[o>>>2>>>0];return o=(v(),S)[o+4>>>2>>>0],l?Bt(l,o):o===0?"":void 0},Mu=o=>{var l=ut(o+4),d=(d=(v(),S)[o+12>>>2>>>0])?W(d):"auto";if(o+=16){var f=W((v(),S)[o+4>>>2>>>0]),g=(v(),S)[o+16>>>2>>>0],y=(v(),S)[o+20>>>2>>>0];if(g){for(var x={},k=0;k>>3>>>0]}g=x}else g=void 0;o={module:f,constants:g,entryPoint:ut(o+8)}}else o=void 0;return{label:l,layout:d,compute:o}},Ba=(o,l)=>{function d(f,g){f=o[f],(v(),S)[l+g>>>2>>>0]=f}d("maxTextureDimension1D",4),d("maxTextureDimension2D",8),d("maxTextureDimension3D",12),d("maxTextureArrayLayers",16),d("maxBindGroups",20),d("maxBindGroupsPlusVertexBuffers",24),d("maxBindingsPerBindGroup",28),d("maxDynamicUniformBuffersPerPipelineLayout",32),d("maxDynamicStorageBuffersPerPipelineLayout",36),d("maxSampledTexturesPerShaderStage",40),d("maxSamplersPerShaderStage",44),d("maxStorageBuffersPerShaderStage",48),d("maxStorageTexturesPerShaderStage",52),d("maxUniformBuffersPerShaderStage",56),d("minUniformBufferOffsetAlignment",80),d("minStorageBufferOffsetAlignment",84),Mn(l+64,o.maxUniformBufferBindingSize),Mn(l+72,o.maxStorageBufferBindingSize),d("maxVertexBuffers",88),Mn(l+96,o.maxBufferSize),d("maxVertexAttributes",104),d("maxVertexBufferArrayStride",108),d("maxInterStageShaderVariables",112),d("maxColorAttachments",116),d("maxColorAttachmentBytesPerSample",120),d("maxComputeWorkgroupStorageSize",124),d("maxComputeInvocationsPerWorkgroup",128),d("maxComputeWorkgroupSizeX",132),d("maxComputeWorkgroupSizeY",136),d("maxComputeWorkgroupSizeZ",140),d("maxComputeWorkgroupsPerDimension",144),o.ze!==void 0&&d("maxImmediateSize",148)},xu=[,"validation","out-of-memory","internal"],Tu=[,"compatibility","core"],$a={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},Eu=[,"low-power","high-performance"],ku=[,"occlusion","timestamp"],Cu={undefined:1,unknown:1,destroyed:2};function Au(o,l,d,f,g,y){l=Ce(l),d=Ce(d),f>>>=0,g>>>=0,y>>>=0;var x=W(o>>>0);if(o={},y){var k=(v(),S)[y+12>>>2>>>0];if(k){var L=(v(),S)[y+16>>>2>>>0];o.requiredFeatures=Array.from((v(),S).subarray(L>>>2>>>0,L+4*k>>>2>>>0),R=>$a[R])}var B=(v(),S)[y+20>>>2>>>0];if(B){let R=function(ce,Me,cr=!1){Me=B+Me,(Me=(v(),S)[Me>>>2>>>0])==4294967295||cr&&Me==0||(re[ce]=Me)},ee=function(ce,Me){Me=B+Me;var cr=(v(),S)[Me>>>2>>>0],$n=(v(),S)[Me+4>>>2>>>0];cr==4294967295&&$n==4294967295||(re[ce]=or(Me))};var re={};R("maxTextureDimension1D",4),R("maxTextureDimension2D",8),R("maxTextureDimension3D",12),R("maxTextureArrayLayers",16),R("maxBindGroups",20),R("maxBindGroupsPlusVertexBuffers",24),R("maxDynamicUniformBuffersPerPipelineLayout",32),R("maxDynamicStorageBuffersPerPipelineLayout",36),R("maxSampledTexturesPerShaderStage",40),R("maxSamplersPerShaderStage",44),R("maxStorageBuffersPerShaderStage",48),R("maxStorageTexturesPerShaderStage",52),R("maxUniformBuffersPerShaderStage",56),R("minUniformBufferOffsetAlignment",80),R("minStorageBufferOffsetAlignment",84),ee("maxUniformBufferBindingSize",64),ee("maxStorageBufferBindingSize",72),R("maxVertexBuffers",88),ee("maxBufferSize",96),R("maxVertexAttributes",104),R("maxVertexBufferArrayStride",108),R("maxInterStageShaderVariables",112),R("maxColorAttachments",116),R("maxColorAttachmentBytesPerSample",120),R("maxComputeWorkgroupStorageSize",124),R("maxComputeInvocationsPerWorkgroup",128),R("maxComputeWorkgroupSizeX",132),R("maxComputeWorkgroupSizeY",136),R("maxComputeWorkgroupSizeZ",140),R("maxComputeWorkgroupsPerDimension",144),R("maxImmediateSize",148,!0),o.requiredLimits=re}(k=(v(),S)[y+24>>>2>>>0])&&(k={label:ut(k+4)},o.defaultQueue=k),o.label=ut(y+4)}ie+=1,Dt(l,x.requestDevice(o).then(R=>{--ie,Le(()=>{Ae[g>>>0]=R.queue,Ae[f>>>0]=R,ie+=1,Dt(d,R.lost.then(ee=>{Le(()=>{R.onuncapturederror=()=>{};var ce=J(),Me=rt(ee.message);Cn(d,Cu[ee.reason],Me),X(ce)}),--ie})),R.onuncapturederror=ee=>{var ce=5;ee.error instanceof GPUValidationError?ce=2:ee.error instanceof GPUOutOfMemoryError?ce=3:ee.error instanceof GPUInternalError&&(ce=4);var Me=J();ee=rt(ee.error.message),so(f,ce,ee),X(Me)},"adapterInfo"in R||(R.adapterInfo=x.info),Pn(l,1,f,0)})},R=>{--ie,Le(()=>{var ee=J(),ce=rt(R.message);Pn(l,3,f,ce),d&&Cn(d,4,ce),X(ee)})}))}function Su(o){var l=W(o>>>=0),d=ct[o];if(d){for(var f=0;f>>=0;var f=W(o>>>=0);d==4294967295&&(d=void 0);try{var g=f.getMappedRange(l>>>0,d)}catch{return 0}var y=Ln(16,g.byteLength);return(v(),q).set(new Uint8Array(g),y>>>0),ct[o].push(()=>Je(y)),y}function Fu(o,l,d){d>>>=0;var f=W(o>>>=0);d==4294967295&&(d=void 0);try{var g=f.getMappedRange(l>>>0,d)}catch{return 0}var y=Ln(16,g.byteLength);return(v(),q).fill(0,y,g.byteLength),ct[o].push(()=>{new Uint8Array(g).set((v(),q).subarray(y>>>0,y+g.byteLength>>>0)),Je(y)}),y}function Iu(o,l,d,f,g){o>>>=0,l=Ce(l),d=Ce(d),g>>>=0;var y=W(o);ct[o]=[],g==4294967295&&(g=void 0),ie+=1,Dt(l,y.mapAsync(d,f>>>0,g).then(()=>{--ie,Le(()=>{An(l,1,0)})},x=>{--ie,Le(()=>{J();var k=rt(x.message);An(l,x.name==="AbortError"?4:x.name==="OperationError"?3:0,k),delete ct[o]})}))}function Lu(o){var l=W(o>>>=0),d=ct[o];if(d){for(var f=0;f>>0]}function Nu(o,l,d){o>>>=0,l>>>=0,d>>>=0;var f=!!(v(),S)[l+32>>>2>>>0];l={label:ut(l+4),usage:(v(),S)[l+16>>>2>>>0],size:or(l+24),mappedAtCreation:f},o=W(o);try{var g=o.createBuffer(l)}catch{return!1}return Ae[d>>>0]=g,f&&(ct[d]=[]),!0}function Bu(o,l,d,f){o>>>=0,l=Ce(l),f>>>=0,d=Mu(d>>>0),o=W(o),ie+=1,Dt(l,o.createComputePipelineAsync(d).then(g=>{--ie,Le(()=>{Ae[f>>>0]=g,kn(l,1,f,0)})},g=>{--ie,Le(()=>{var y=J(),x=rt(g.message);kn(l,g.reason==="validation"?3:g.reason==="internal"?4:0,f,x),X(y)})}))}function $u(o,l,d){o>>>=0,l>>>=0,d>>>=0;var f=(v(),S)[l>>>2>>>0],g=(v(),I)[f+4>>>2>>>0];l={label:ut(l+4),code:""},g===2&&(l.code=Na(f+8)),o=W(o).createShaderModule(l),Ae[d>>>0]=o}var Du=o=>{(o=W(o)).onuncapturederror=null,o.destroy()};function Ru(o,l){l=Ce(l),o=W(o>>>0),ie+=1,Dt(l,o.popErrorScope().then(d=>{--ie,Le(()=>{var f=5;d?d instanceof GPUValidationError?f=2:d instanceof GPUOutOfMemoryError?f=3:d instanceof GPUInternalError&&(f=4):f=1;var g=J(),y=d?rt(d.message):0;Sn(l,1,f,y),X(g)})},d=>{--ie,Le(()=>{var f=J(),g=rt(d.message);Sn(l,1,5,g),X(f)})}))}function zu(o,l,d,f){if(l=Ce(l),f>>>=0,d>>>=0){var g={featureLevel:Tu[(v(),I)[d+4>>>2>>>0]],powerPreference:Eu[(v(),I)[d+8>>>2>>>0]],forceFallbackAdapter:!!(v(),S)[d+12>>>2>>>0]};(o=(v(),S)[d>>>2>>>0])!==0&&(v(),g.De=!!(v(),S)[o+8>>>2>>>0])}"gpu"in navigator?(ie+=1,Dt(l,navigator.gpu.requestAdapter(g).then(y=>{--ie,Le(()=>{if(y)Ae[f>>>0]=y,ir(l,1,f,0);else{var x=J(),k=rt("WebGPU not available on this browser (requestAdapter returned null)");ir(l,3,f,k),X(x)}})},y=>{--ie,Le(()=>{var x=J(),k=rt(y.message);ir(l,4,f,k),X(x)})}))):(g=J(),o=rt("WebGPU not available on this browser (navigator.gpu is not available)"),ir(l,3,f,o),X(g))}function Gu(o,l,d){return o>>>=0,l>>>=0,d>>>=0,ka(async()=>{var f=[];if(d){var g=(v(),I)[d>>>2>>>0];f.length=l+1,f[l]=new Promise(k=>setTimeout(k,g,0))}else f.length=l;for(var y=0;y{if(!xn){var o,l={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(o in Tn)Tn[o]===void 0?delete l[o]:l[o]=Tn[o];var d=[];for(o in l)d.push(`${o}=${l[o]}`);xn=d}return xn};function Ra(o,l){if(s)return le(19,1,o,l);o>>>=0,l>>>=0;var d,f=0,g=0;for(d of Da()){var y=l+f;(v(),S)[o+g>>>2>>>0]=y,f+=it(d,y,1/0)+1,g+=4}return 0}function za(o,l){if(s)return le(20,1,o,l);o>>>=0,l>>>=0;var d=Da();for(var f of((v(),S)[o>>>2>>>0]=d.length,o=0,d))o+=lt(f)+1;return(v(),S)[l>>>2>>>0]=o,0}function Ga(o){return s?le(21,1,o):52}function Ua(o,l,d,f){return s?le(22,1,o,l,d,f):52}function Va(o,l,d,f){return s?le(23,1,o,l,d,f):70}var Uu=[null,[],[]];function Wa(o,l,d,f){if(s)return le(24,1,o,l,d,f);l>>>=0,d>>>=0,f>>>=0;for(var g=0,y=0;y>>2>>>0],k=(v(),S)[l+4>>>2>>>0];l+=8;for(var L=0;L>>0],R=Uu[B];re===0||re===10?((B===1?P:A)(oa(R)),R.length=0):R.push(re)}g+=k}return(v(),S)[f>>>2>>>0]=g,0}function Vu(o){return o>>>0}function Wu(o,l){return Ba(W(o>>>0).limits,l>>>0),1}function ju(o,l){return W(o>>>0).features.has($a[l])}function qu(o){return BigInt(W(o>>>0).size)}function Hu(o){return BigInt(W(o>>>0).usage)}function Qu(o,l){if(o>>>=0,l>>>=0){var d=ut(l+4);d={label:d,timestampWrites:l=(l=(v(),S)[l+12>>>2>>>0])!==0?{querySet:W((v(),S)[l+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),S)[l+8>>>2>>>0],endOfPassWriteIndex:(v(),S)[l+12>>>2>>>0]}:void 0}}return l=W(o),o=Za(0),d=l.beginComputePass(d),Ae[o>>>0]=d,o}function Yu(o,l,d,f){d=Ce(d),(f=Ce(f))==-1&&(f=void 0),(o=W(o>>>0)).clearBuffer(W(l>>>0),d,f)}function Xu(o,l,d,f,g,y){d=Ce(d),g=Ce(g),y=Ce(y),W(o>>>0).copyBufferToBuffer(W(l>>>0),d,W(f>>>0),g,y)}function Ju(o){var l=W(o>>>0);return o=Ja(0),l=l.finish(),Ae[o>>>0]=l,o}function Ku(o,l,d,f,g,y){y=Ce(y),W(o>>>0).resolveQuerySet(W(l>>>0),d,f,W(g>>>0),y)}function Zu(o,l,d,f){W(o>>>0).dispatchWorkgroups(l,d,f)}function ed(o,l,d){d=Ce(d),W(o>>>0).dispatchWorkgroupsIndirect(W(l>>>0),d)}function td(o){W(o>>>0).end()}function rd(o,l,d,f,g){f>>>=0,g>>>=0,o=W(o>>>0),d=W(d>>>0),f==0?o.setBindGroup(l,d):o.setBindGroup(l,d,(v(),S),g>>>2,f)}function nd(o,l){W(o>>>0).setPipeline(W(l>>>0))}function sd(o,l,d){W(o>>>0).Ce(W(l>>>0),d)}function ad(o,l){var d=W(o>>>0);return o=Xa(0),l=d.getBindGroupLayout(l),Ae[o>>>0]=l,o}function od(o,l){function d(g){var y=(v(),S)[g+8>>>2>>>0],x=(v(),S)[g+32>>>2>>>0],k=(v(),S)[g+36>>>2>>>0],L=0;return bu(g,{327681:B=>{L=(v(),S)[B+8>>>2>>>0]}}),y?((x=or(g+24))==-1&&(x=void 0),y={buffer:W(y),offset:or(g+16),size:x}):y=W(x||k||L),{binding:(v(),S)[g+4>>>2>>>0],resource:y}}o>>>=0,l={label:ut(4+(l>>>=0)),layout:W((v(),S)[l+12>>>2>>>0]),entries:(function(g,y){for(var x=[],k=0;k>>2>>>0],(v(),S)[l+20>>>2>>>0])},o=W(o);var f=Ya(0);return vu(f,o.createBindGroup(l)),f}function id(o,l){var d;return o>>>=0,(l>>>=0)&&(d={label:ut(l+4)}),l=W(o),o=Ka(0),d=l.createCommandEncoder(d),Ae[o>>>0]=d,o}function ld(o,l){o>>>=0,l>>>=0,l={type:ku[(v(),I)[l+12>>>2>>>0]],count:(v(),S)[l+16>>>2>>>0]};var d=W(o);return o=eo(0),l=d.createQuerySet(l),Ae[o>>>0]=l,o}function cd(o,l){o=W(o>>>0).adapterInfo,l>>>=0,(v(),S)[l+52>>>2>>>0]=o.subgroupMinSize,(v(),S)[l+56>>>2>>>0]=o.subgroupMaxSize;var d=o.vendor+o.architecture+o.device+o.description,f=lt(d)+1,g=Rt(f);return g&&it(d,g,f),d=g,f=lt(o.vendor),Br(l+4,d,f),d+=f,f=lt(o.architecture),Br(l+12,d,f),d+=f,f=lt(o.device),Br(l+20,d,f),Br(l+28,d+f,lt(o.description)),(v(),I)[l+36>>>2>>>0]=2,o=o.isFallbackAdapter?3:4,(v(),I)[l+40>>>2>>>0]=o,(v(),S)[l+44>>>2>>>0]=0,(v(),S)[l+48>>>2>>>0]=0,1}var ud={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function dd(o,l){l>>>=0;var d=W(o>>>0);o=Rt(4*d.features.size);var f=0,g=0;for(let y of d.features)0<=(d=ud[y])&&((v(),I)[o+f>>>2>>>0]=d,f+=4,g++);(v(),S)[l+4>>>2>>>0]=o,(v(),S)[l>>>2>>>0]=g}function fd(o,l){return Ba(W(o>>>0).limits,l>>>0),1}function hd(o,l){W(o>>>0).pushErrorScope(xu[l])}function pd(o,l,d){l>>>=0,d>>>=0,o=W(o>>>0),l=Array.from((v(),I).subarray(d>>>2>>>0,d+4*l>>>2>>>0),f=>W(f)),o.submit(l)}function _d(o,l,d,f,g){d=Ce(d),f>>>=0,g>>>=0,o=W(o>>>0),l=W(l>>>0),f=(v(),q).subarray(f>>>0,f+g>>>0),o.writeBuffer(l,d,f,0,g)}s||(function(){for(var o=t.numThreads-1;o--;)Zs();qe.push(async()=>{var l=(async function(){if(!s)return Promise.all(vt.map(Ks))})();ue++,await l,--ue==0&&oe&&(l=oe,oe=null,l())})})(),s||(bt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Q()),t.wasmBinary&&(_=t.wasmBinary),t.stackSave=()=>J(),t.stackRestore=o=>X(o),t.stackAlloc=o=>Dr(o),t.setValue=function(o,l,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":(v(),U)[o>>>0]=l;break;case"i16":(v(),ne)[o>>>1>>>0]=l;break;case"i32":(v(),I)[o>>>2>>>0]=l;break;case"i64":(v(),se)[o>>>3>>>0]=BigInt(l);break;case"float":(v(),D)[o>>>2>>>0]=l;break;case"double":(v(),Y)[o>>>3>>>0]=l;break;case"*":(v(),S)[o>>>2>>>0]=l;break;default:me(`invalid type for setValue: ${d}`)}},t.getValue=function(o,l="i8"){switch(l.endsWith("*")&&(l="*"),l){case"i1":case"i8":return(v(),U)[o>>>0];case"i16":return(v(),ne)[o>>>1>>>0];case"i32":return(v(),I)[o>>>2>>>0];case"i64":return(v(),se)[o>>>3>>>0];case"float":return(v(),D)[o>>>2>>>0];case"double":return(v(),Y)[o>>>3>>>0];case"*":return(v(),S)[o>>>2>>>0];default:me(`invalid type for getValue: ${l}`)}},t.UTF8ToString=Bt,t.stringToUTF8=it,t.lengthBytesUTF8=lt;var ja,qa,En,$r,Je,Rt,Ha,Qa,Ya,Xa,Ja,Ka,Za,eo,to,ro,no,kn,Cn,An,Sn,ir,Pn,so,Fn,ao,oo,io,In,lo,co,Ln,te,lr,uo,X,Dr,J,fo,On,ho,po,_o,Nn,mo,go,wo,yo,vo,bo,Mo,xo,To,Eo,ko,Co,Ao,So,Po,Fo,Io,Lo,Oo,No,Bo,$o,Do,Ro,zo,Go,Uo,Vo,Wo,jo,qo,Ho,Qo,Yo,Xo,Jo,Ko,Zo,dt,md=[gr,Hr,ra,ia,la,ca,ua,da,fa,ha,pa,_a,ma,ga,wa,ya,Fa,Ia,La,Ra,za,Ga,Ua,Va,Wa],Bn={970348:(o,l,d,f,g)=>{if(t===void 0||!t.Uc)return 1;if((o=Bt(Number(o>>>0))).startsWith("./")&&(o=o.substring(2)),!(o=t.Uc.get(o)))return 2;if(l=Number(l>>>0),d=Number(d>>>0),f=Number(f>>>0),l+d>o.byteLength)return 3;try{let y=o.subarray(l,l+d);switch(g){case 0:(v(),q).set(y,f>>>0);break;case 1:t.ad?t.ad(f,y):t.ne(f,y);break;default:return 4}return 0}catch{return 4}},971172:(o,l,d)=>{t.Sd(o,(v(),q).subarray(l>>>0,l+d>>>0))},971236:()=>t.le(),971278:o=>{t.jd(o)},971315:()=>typeof wasmOffsetConverter<"u"};function gd(o,l,d,f){var g=J();try{return xo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function wd(o,l,d){var f=J();try{return vo(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function yd(o){var l=J();try{mo(o)}catch(d){if(X(l),d!==d+0)throw d;te(1,0)}}function vd(o,l){var d=J();try{return Nn(o,l)}catch(f){if(X(d),f!==f+0)throw f;te(1,0)}}function bd(o,l,d){var f=J();try{_o(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Md(o,l){var d=J();try{To(o,l)}catch(f){if(X(d),f!==f+0)throw f;te(1,0)}}function xd(o,l,d,f,g,y,x){var k=J();try{return yo(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Td(o,l,d,f,g,y){var x=J();try{go(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Ed(o,l,d,f){var g=J();try{Mo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function kd(o,l,d,f,g,y,x){var k=J();try{ko(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Cd(o,l,d,f,g,y,x){var k=J();try{Co(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Ad(o,l,d,f,g,y,x,k){var L=J();try{Bo(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Sd(o,l,d,f,g,y,x,k,L,B,re,R){var ee=J();try{Ao(o,l,d,f,g,y,x,k,L,B,re,R)}catch(ce){if(X(ee),ce!==ce+0)throw ce;te(1,0)}}function Pd(o,l,d,f,g){var y=J();try{return Eo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Fd(o,l,d,f,g){var y=J();try{wo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Id(o,l,d,f,g,y,x,k){var L=J();try{bo(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Ld(o){var l=J();try{return $o(o)}catch(d){if(X(l),d!==d+0)throw d;te(1,0)}}function Od(o,l,d){var f=J();try{return Do(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Nd(o,l){var d=J();try{return Yo(o,l)}catch(f){if(X(d),f!==f+0)throw f;return te(1,0),0n}}function Bd(o){var l=J();try{return So(o)}catch(d){if(X(l),d!==d+0)throw d;return te(1,0),0n}}function $d(o,l,d,f){var g=J();try{return Ro(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function Dd(o,l,d,f,g){var y=J();try{return zo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Rd(o,l,d,f,g,y){var x=J();try{return Go(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function zd(o,l,d,f,g,y){var x=J();try{return Oo(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Gd(o,l,d,f,g,y){var x=J();try{return Uo(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Ud(o,l,d,f,g,y,x,k){var L=J();try{return No(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Vd(o,l,d,f,g){var y=J();try{return Vo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;return te(1,0),0n}}function Wd(o,l,d,f){var g=J();try{return Wo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function jd(o,l,d,f){var g=J();try{return jo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function qd(o,l,d,f,g,y,x,k,L,B,re,R){var ee=J();try{return qo(o,l,d,f,g,y,x,k,L,B,re,R)}catch(ce){if(X(ee),ce!==ce+0)throw ce;te(1,0)}}function Hd(o,l,d,f,g,y,x,k,L,B,re){var R=J();try{Ho(o,l,d,f,g,y,x,k,L,B,re)}catch(ee){if(X(R),ee!==ee+0)throw ee;te(1,0)}}function Qd(o,l,d,f,g,y,x,k,L,B,re,R,ee,ce,Me,cr){var $n=J();try{Qo(o,l,d,f,g,y,x,k,L,B,re,R,ee,ce,Me,cr)}catch(Dn){if(X($n),Dn!==Dn+0)throw Dn;te(1,0)}}function Yd(o,l,d){var f=J();try{return Fo(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;return te(1,0),0n}}function Xd(o,l,d){var f=J();try{return Po(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Jd(o,l,d){var f=J();try{return Io(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Kd(o,l,d,f){var g=J();try{Lo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function Rr(){if(0{let l=new WeakMap,d,f,g=1;t.webgpuRegisterDevice=k=>{if(f!==void 0)throw Error("another WebGPU EP inference session is being created.");if(k){var L=l.get(k);if(!L){let B=((re,R=0)=>{var ee=no(R);return R=ro(R,ee),Ae[ee>>>0]=re.queue,Ae[R>>>0]=re,R})(k,L=Qa(0));L=[g++,L,B],l.set(k,L)}return d=k,f=L[0],L}d=void 0,f=0};let y=new Map;t.webgpuOnCreateSession=k=>{if(f!==void 0){var L=f;if(f=void 0,k){let B=En(L);y.set(k,B),L===0&&o(d??W(B))}d=void 0}},t.webgpuOnReleaseSession=k=>{y.delete(k)};let x=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(k,L,B)=>{if(B)return k[x]=[B,NaN],B;if(B=k[x])return B[1]++,B[0];if((L=y.get(L))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return L=((re,R=0)=>(re.mapState==="unmapped"||me(),R=to(R),Ae[R>>>0]=re,R))(k,L),k[x]=[L,1],L},t.webgpuUnregisterBuffer=k=>{let L=k[x];if(!L)throw Error("Buffer is not registered");L[1]--,L[1]===0&&(Ha(L[0]),delete k[x])},t.webgpuGetBuffer=k=>W(k),t.webgpuCreateDownloader=(k,L,B)=>{if((B=y.get(B))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let re=W(B),R=16*Math.ceil(Number(L)/16);return async()=>{let ee=re.createBuffer({size:R,usage:9});try{let ce=re.createCommandEncoder();return ce.copyBufferToBuffer(k,0,ee,0,R),re.queue.submit([ce.finish()]),await ee.mapAsync(GPUMapMode.READ),ee.getMappedRange().slice(0,L)}finally{ee.destroy()}}},t.ad=(k,L)=>{var B=L.buffer;let re=L.byteOffset,R=L.byteLength;if(L=16*Math.ceil(Number(R)/16),k=W(k),!d){var ee=En(f);d=W(ee)}let ce=(ee=d.createBuffer({mappedAtCreation:!0,size:L,usage:6})).getMappedRange();new Uint8Array(ce).set(new Uint8Array(B,re,R)),ee.unmap(),(B=d.createCommandEncoder()).copyBufferToBuffer(ee,0,k,0,L),d.queue.submit([B.finish()]),ee.destroy()}},t.webnnInit=o=>{let l=o[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=o.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=d=>l.onRunStart(d),t.webnnOnRunEnd=l.onRunEnd.bind(l),t.webnnOnReleaseSession=d=>{l.onReleaseSession(d)},t.webnnCreateMLTensorDownloader=(d,f)=>l.createMLTensorDownloader(d,f),t.webnnRegisterMLTensor=(d,f,g,y)=>l.registerMLTensor(d,f,g,y),t.webnnCreateMLContext=d=>l.createMLContext(d),t.webnnRegisterMLConstant=(d,f,g,y,x,k)=>l.registerMLConstant(d,f,g,y,x,t.Uc,k),t.webnnRegisterGraphInput=l.registerGraphInput.bind(l),t.webnnIsGraphInput=l.isGraphInput.bind(l),t.webnnRegisterGraphOutput=l.registerGraphOutput.bind(l),t.webnnIsGraphOutput=l.isGraphOutput.bind(l),t.webnnCreateTemporaryTensor=l.createTemporaryTensor.bind(l),t.webnnIsGraphInputOutputTypeSupported=l.isGraphInputOutputTypeSupported.bind(l)},z?t:new Promise((o,l)=>{b=o,M=l})}var ny,Bm,b1=Te(()=>{ny=Nm,Bm=globalThis.self?.name?.startsWith("em-pthread"),Bm&&Nm()}),sf,rh,$m,Gt,sy,Bi,Dm,Rm,af,zm,of,ay,lf,oy,Sh=Te(()=>{Ah(),sf=typeof location>"u"?void 0:location.origin,rh=import.meta.url>"file:"&&import.meta.url<"file;",$m=()=>{{if(rh){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,sf).href}return import.meta.url}},Gt=$m(),sy=()=>{if(Gt&&!Gt.startsWith("blob:"))return Gt.substring(0,Gt.lastIndexOf("/")+1)},Bi=(e,t)=>{try{let r=t??Gt;return(r?new URL(e,r):new URL(e)).origin===sf}catch{return!1}},Dm=(e,t)=>{let r=t??Gt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Rm=(e,t)=>`${t??"./"}${e}`,af=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},zm=async e=>(await import(e)).default,of=(v1(),ol(ey)).default,ay=async()=>{if(!Gt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Bi(Gt))return[void 0,of()];let e=await af(Gt);return[e,of(e)]},lf=(b1(),ol(ry)).default,oy=async(e,t,r,n)=>{let s=lf&&!(e||t);if(s)if(Gt)s=Bi(Gt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,lf];{let a="ort-wasm-simd-threaded.asyncify.mjs",i=e??Dm(a,t),c=r&&i&&!Bi(i,t),u=c?await af(i):i??Rm(a,t);return[c?u:void 0,await zm(u)]}}}),cf,$i,ti,uf,Gm,Um,Vm,Ph,ze,ss=Te(()=>{Sh(),$i=!1,ti=!1,uf=!1,Gm=()=>{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}},Um=()=>{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}},Vm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ph=async e=>{if($i)return Promise.resolve();if(ti)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(uf)throw new Error("previous call to 'initializeWebAssembly()' failed.");ti=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Vm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Um())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Gm();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", 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=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s?.mjs,c=i?.href??i,u=s?.wasm,h=u?.href??u,p=e.wasmBinary,[_,m]=await oy(c,a,r>1,!!p||!!h),w=!1,b=[];if(t>0&&b.push(new Promise(M=>{setTimeout(()=>{w=!0,M()},t)})),b.push(new Promise((M,E)=>{let T={numThreads:r};if(p)T.wasmBinary=p,T.locateFile=C=>C;else if(h||a)T.locateFile=C=>h??a+C;else if(c&&c.indexOf("blob:")!==0)T.locateFile=C=>new URL(C,c).href;else if(_){let C=sy();C&&(T.locateFile=P=>C+P)}m(T).then(C=>{ti=!1,$i=!0,cf=C,M(),_&&URL.revokeObjectURL(_)},C=>{ti=!1,uf=!0,E(C)})})),await Promise.race(b),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if($i&&cf)return cf;throw new Error("WebAssembly is not initialized yet.")}}),Vt,ll,Fe,Fh=Te(()=>{ss(),Vt=(e,t)=>{let r=ze(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},ll=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")ll(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Fe=e=>{let t=ze(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),i=t.getValue(s+n,"*"),c=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(r)}}}),iy,M1=Te(()=>{ss(),Fh(),iy=e=>{let t=ze(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Vt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Fe("Can't create run options."),e?.extra!==void 0&&ll(e.extra,"",new WeakSet,(i,c)=>{let u=Vt(i,n),h=Vt(c,n);t._OrtAddRunConfigEntry(r,u,h)!==0&&Fe(`Can't set a run config entry: ${i} - ${c}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),Wm,jm,qm,Di,Yr,Hm,ly,x1=Te(()=>{ss(),Fh(),Wm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},jm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},qm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Di=(e,t,r,n)=>{let s=Vt(t,n),a=Vt(r,n);ze()._OrtAddSessionConfigEntry(e,s,a)!==0&&Fe(`Can't set a session config entry: ${t} - ${r}.`)},Yr=(e,t,r,n)=>{let s=Vt(t,n),a=Vt(r,n);e.push([s,a])},Hm=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,i=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let _=s?.deviceType;_&&Di(e,"deviceType",_,r)}break;case"webgpu":{a="WebGPU";let _;if(typeof s!="string"){let w=s;if(w.device)if(typeof GPUDevice<"u"&&w.device instanceof GPUDevice)_=w.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:b}=t;if(typeof b=="boolean"&&b&&Yr(i,"enableGraphCapture","1",r),typeof w.preferredLayout=="string"&&Yr(i,"preferredLayout",w.preferredLayout,r),w.forceCpuNodeNames){let M=Array.isArray(w.forceCpuNodeNames)?w.forceCpuNodeNames:[w.forceCpuNodeNames];Yr(i,"forceCpuNodeNames",M.join(` `),r)}w.validationMode&&Yr(i,"validationMode",w.validationMode,r)}let m=ze().webgpuRegisterDevice(_);if(m){let[w,b,M]=m;Yr(i,"deviceId",w.toString(),r),Yr(i,"webgpuInstance",b.toString(),r),Yr(i,"webgpuDevice",M.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let c=Vt(a,r),u=i.length,h=0,p=0;if(u>0){h=ze()._malloc(u*ze().PTR_SIZE),r.push(h),p=ze()._malloc(u*ze().PTR_SIZE),r.push(p);for(let _=0;_{let t=ze(),r=0,n=[],s=e||{};qm(s);try{let a=Wm(s.graphOptimizationLevel??"all"),i=jm(s.executionMode??"sequential"),c=typeof s.logId=="string"?Vt(s.logId,n):0,u=s.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let h=s.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let p=typeof s.optimizedModelFilePath=="string"?Vt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,c,u,h,p),r===0&&Fe("Can't create session options."),s.executionProviders&&await Hm(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Di(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[_,m]of Object.entries(s.freeDimensionOverrides)){if(typeof _!="string")throw new Error(`free dimension override name must be a string: ${_}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let w=Vt(_,n);t._OrtAddFreeDimensionOverride(r,w,m)!==0&&Fe(`Can't set a free dimension override: ${_} - ${m}.`)}return s.extra!==void 0&&ll(s.extra,"",new WeakSet,(_,m)=>{Di(r,_,m,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Fe("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Hn,tl,_s,gi,cl,Ih,Lh,nh,As=Te(()=>{Hn=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}`)}},tl=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}`)}},_s=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},gi=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}`)}},cl=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}`)}},Ih=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Lh=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",nh=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}`)}}}),Oh,cy=Te(()=>{Ah(),Oh=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(c){if(c instanceof RangeError){let u=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw c}let i=0;for(;;){let{done:c,value:u}=await s.read();if(c)break;let h=u.byteLength;new Uint8Array(a,i,h).set(u),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),uy,T1=Te(()=>{As(),uy=(e,t)=>new(gi(t))(e)}),Qm,Ym,Xm,Jm,dy,Km,kt,fy=Te(()=>{As(),Qm=["V","I","W","E","F"],Ym=(e,t)=>{console.log(`[${Qm[e]},${new Date().toISOString()}]${t}`)},dy=(e,t)=>{Xm=e,Jm=t},Km=(e,t)=>{let r=cl(e),n=cl(Xm);r>=n&&Ym(r,typeof t=="function"?t():t)},kt=(...e)=>{Jm&&Km(...e)}}),df,sh,ff,Zm,hf,eg,pf,_f,mf,tg,hy,E1=Te(()=>{As(),fy(),df=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),sh=(e,t)=>{if(t==="int32")return e;let r=df.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let n=r/8;if(e.byteLength%n!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(gi(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let i=new Int32Array(s);for(let c=0;c2147483647n||u<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");i[c]=Number(u)}return new Uint8Array(i.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let i=Int32Array.from(a,Number);return new Uint8Array(i.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},ff=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Zm=1,hf=()=>Zm++,eg=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),pf=(e,t)=>{let r=df.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},_f=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:i}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return pf(this.dataType,this.tensorShape)}destroy(){kt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=ff(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},mf=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),i;if(!a?.input.dataTypes.includes(t)){if(i=eg.get(t),!i||a?.input.dataTypes.includes(i))throw new Error(`WebNN backend does not support data type: ${t}`);kt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${i}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==pf(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,c,!0,!0,i),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=sh(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else kt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?ff(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},tg=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=hf();return this.tensorTrackersById.set(e,new mf(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n,s){kt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){kt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let s=this.getMLContext(e),a=hf(),i=new _f({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new mf(this,i)),this.externalTensors.add(i),a}async getCachedTensor(e,t,r,n,s,a,i){let c=this.getMLContext(e);for(let[h,p]of this.freeTensors.entries())if(p.canReuseTensor(c,t,r)){kt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}`);let _=this.freeTensors.splice(h,1)[0];return _.sessionId=e,_}kt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}}`);let u=await c.createTensor({dataType:i??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new _f({sessionId:e,context:c,tensor:u,dataType:t,shape:r,fallbackDataType:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},hy=(...e)=>new tg(...e)}),py={};bi(py,{WebNNBackend:()=>_y});var ri,rg,_y,k1=Te(()=>{As(),ss(),T1(),E1(),fy(),ri=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),rg=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},_y=class{constructor(e){this.tensorManager=hy(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,dy(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){kt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){kt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)kt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>rg(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){kt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=ri.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){kt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=ri.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");kt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return uy(r,t)}}registerMLTensor(e,t,r,n){let s=ri.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return kt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,i=!1){if(!a)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let u=a.get(c);if(!u)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let h=u.slice(t,t+r).buffer,p;switch(s.dataType){case"float32":p=new Float32Array(h);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(h):new Uint16Array(h);break;case"int32":p=new Int32Array(h);break;case"uint32":p=new Uint32Array(h);break;case"int64":if(i){let _=sh(new Uint8Array(h),"int64");p=new Int32Array(_.buffer),s.dataType="int32"}else p=new BigInt64Array(h);break;case"uint64":p=new BigUint64Array(h);break;case"int8":p=new Int8Array(h);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(h);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return kt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=ri.get(Hn(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),ng,Nh,Bh,Xr,sg,gf,ul,$h,Dh,wf,Rh,zh,Gh,my=Te(()=>{ns(),M1(),x1(),As(),ss(),Fh(),cy(),ng=(e,t)=>{ze()._OrtInit(e,t)!==0&&Fe("Can't initialize onnxruntime.")},Nh=async e=>{ng(e.wasm.numThreads,cl(e.logLevel))},Bh=async(e,t)=>{ze().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&ze().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(k1(),ol(py)).WebNNBackend(e);ze().webnnInit([n,()=>n.reserveTensorId(),s=>n.releaseTensorId(s),async(s,a,i,c,u)=>n.ensureTensor(s,a,i,c,u),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},Xr=new Map,sg=e=>{let t=ze(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&Fe("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},gf=(e,t)=>{let r=ze(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,i=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,i,i+a)!==0&&Fe("Can't get session input/output metadata.");let c=Number(r.getValue(i,"*"));s=Number(r.getValue(i+a,"*"));let u=r.HEAP32[s/4];if(u===0)return[c,0];let h=r.HEAPU32[s/4+1],p=[];for(let _=0;_{let t=ze(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},$h=async(e,t)=>{let r,n,s=ze();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=ul(e);let a=0,i=0,c=0,u=[],h=[],p=[];try{if([i,u]=await ly(t),t?.externalData&&s.mountExternalData){let A=[];for(let F of t.externalData){let G=typeof F=="string"?F:F.path;A.push(Oh(typeof F=="string"?F:F.data).then(v=>{s.mountExternalData(G,v)}))}await Promise.all(A)}for(let A of t?.executionProviders??[])if((typeof A=="string"?A:A.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof A!="string"){let F=A,G=F?.context,v=F?.gpuDevice,j=F?.deviceType,U=F?.powerPreference;G?s.currentContext=G:v?s.currentContext=await s.webnnCreateMLContext(v):s.currentContext=await s.webnnCreateMLContext({deviceType:j,powerPreference:U})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,i),s.webgpuOnCreateSession?.(a),a===0&&Fe("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[_,m]=sg(a),w=!!t?.enableGraphCapture,b=[],M=[],E=[],T=[],C=[];for(let A=0;A<_;A++){let[F,G,v]=gf(a,A);F===0&&Fe("Can't get an input name."),h.push(F);let j=s.UTF8ToString(F);b.push(j),E.push(G===0?{name:j,isTensor:!1}:{name:j,isTensor:!0,type:tl(G),shape:v})}for(let A=0;AA==="gpu-buffer"||A==="ml-tensor"||A==="ml-tensor-cpu-output")&&(c=s._OrtCreateBinding(a),c===0&&Fe("Can't create IO binding."),P={handle:c,outputPreferredLocations:C,outputPreferredLocationsEncoded:C.map(A=>A==="ml-tensor-cpu-output"?"ml-tensor":A).map(A=>nh(A))}),Xr.set(a,[a,h,p,P,w,!1]),[a,b,M,E,T]}catch(_){throw h.forEach(m=>s._OrtFree(m)),p.forEach(m=>s._OrtFree(m)),c!==0&&s._OrtReleaseBinding(c)!==0&&Fe("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&Fe("Can't release session."),_}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i)!==0&&Fe("Can't release session options."),u.forEach(_=>s._free(_)),s.unmountExternalData?.()}},Dh=e=>{let t=ze(),r=Xr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,c]=r;i&&(c&&t._OrtClearBoundOutputs(i.handle)!==0&&Fe("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&Fe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach(u=>t._OrtFree(u)),a.forEach(u=>t._OrtFree(u)),t._OrtReleaseSession(n)!==0&&Fe("Can't release session."),Xr.delete(e)},wf=async(e,t,r,n,s,a,i=!1)=>{if(!e){t.push(0);return}let c=ze(),u=c.PTR_SIZE,h=e[0],p=e[1],_=e[3],m=_,w,b;if(h==="string"&&(_==="gpu-buffer"||_==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&_!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(_==="gpu-buffer"){let T=e[2].gpuBuffer;b=_s(Hn(h),p);{let C=c.webgpuRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=C(T,n)}}else if(_==="ml-tensor"){let T=e[2].mlTensor;b=_s(Hn(h),p);let C=c.webnnRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');w=C(n,T,Hn(h),p)}else{let T=e[2];if(Array.isArray(T)){b=u*T.length,w=c._malloc(b),r.push(w);for(let C=0;Cc.setValue(E+P*u,C,u===4?"i32":"i64"));let T=c._OrtCreateTensor(Hn(h),w,b,E,p.length,nh(m));T===0&&Fe(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(T)}finally{c.stackRestore(M)}},Rh=async(e,t,r,n,s,a)=>{let i=ze(),c=i.PTR_SIZE,u=Xr.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=u[0],p=u[1],_=u[2],m=u[3],w=u[4],b=u[5],M=t.length,E=n.length,T=0,C=[],P=[],A=[],F=[],G=[],v=i.stackSave(),j=i.stackAlloc(M*c),U=i.stackAlloc(M*c),q=i.stackAlloc(E*c),ne=i.stackAlloc(E*c);try{[T,C]=iy(a),an("wasm prepareInputOutputTensor");for(let D=0;Due*oe,1);z=tl(me);let qe=m?.outputPreferredLocations[n[D]];if(z==="string"){if(qe==="gpu-buffer"||qe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ue=[];for(let oe=0;oe<$e;oe++){let Re=i.getValue(Q+oe*c,"*"),ie=i.getValue(Q+(oe+1)*c,"*"),le=oe===$e-1?void 0:ie-Re;ue.push(i.UTF8ToString(Re,le))}I.push([z,ye,ue,"cpu"])}else if(qe==="gpu-buffer"&&$e>0){let ue=i.webgpuGetBuffer;if(!ue)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let oe=ue(Q),Re=_s(me,$e);if(Re===void 0||!Ih(z))throw new Error(`Unsupported data type: ${z}`);$=!0;{i.webgpuRegisterBuffer(oe,e,Q);let ie=i.webgpuCreateDownloader(oe,Re,e);I.push([z,ye,{gpuBuffer:oe,download:async()=>{let le=await ie();return new(gi(z))(le)},dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Fe("Can't release tensor.")}},"gpu-buffer"])}}else if(qe==="ml-tensor"&&$e>0){let ue=i.webnnEnsureTensor,oe=i.webnnIsGraphInputOutputTypeSupported;if(!ue||!oe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(_s(me,$e)===void 0||!Lh(z))throw new Error(`Unsupported data type: ${z}`);if(!oe(e,z,!1))throw new Error(`preferredLocation "ml-tensor" for ${z} output is not supported by current WebNN Context.`);let Re=await ue(e,Q,me,ye,!1);$=!0,I.push([z,ye,{mlTensor:Re,download:i.webnnCreateMLTensorDownloader(Q,z),dispose:()=>{i.webnnReleaseTensorId(Q),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else if(qe==="ml-tensor-cpu-output"&&$e>0){let ue=i.webnnCreateMLTensorDownloader(Q,z)(),oe=I.length;$=!0,S.push((async()=>{let Re=[oe,await ue];return i.webnnReleaseTensorId(Q),i._OrtReleaseTensor(Y),Re})()),I.push([z,ye,[],"cpu"])}else{let ue=gi(z),oe=new ue($e);new Uint8Array(oe.buffer,oe.byteOffset,oe.byteLength).set(i.HEAPU8.subarray(Q,Q+oe.byteLength)),I.push([z,ye,oe,"cpu"])}}finally{i.stackRestore(se),z==="string"&&Q&&i._free(Q),$||i._OrtReleaseTensor(Y)}}m&&!w&&(i._OrtClearBoundOutputs(m.handle)!==0&&Fe("Can't clear bound outputs."),Xr.set(e,[h,p,_,m,w,!1]));for(let[D,Y]of await Promise.all(S))I[D][2]=Y;return on("wasm ProcessOutputTensor"),I}finally{i.webnnOnRunEnd?.(h),i.stackRestore(v),r.forEach(H=>{H&&H[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(H[2].gpuBuffer)}),s.forEach(H=>{H&&H[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(H[2].gpuBuffer)}),P.forEach(H=>i._OrtReleaseTensor(H)),A.forEach(H=>i._OrtReleaseTensor(H)),F.forEach(H=>i._free(H)),T!==0&&i._OrtReleaseRunOptions(T),C.forEach(H=>i._free(H))}},zh=e=>{let t=ze(),r=Xr.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Fe("Can't get an profile file name."),t._OrtFree(s)},Gh=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Jr,Jt,cs,ni,si,Ri,yf,zi,Rn,zn,ag,gy,wy,yy,vy,by,My,xy,Ty=Te(()=>{ns(),my(),ss(),Sh(),Jr=()=>!!He.wasm.proxy&&typeof document<"u",cs=!1,ni=!1,si=!1,zi=new Map,Rn=(e,t)=>{let r=zi.get(e);r?r.push(t):zi.set(e,[t])},zn=()=>{if(cs||!ni||si||!Jt)throw new Error("worker not ready")},ag=e=>{switch(e.data.type){case"init-wasm":cs=!1,e.data.err?(si=!0,yf[1](e.data.err)):(ni=!0,yf[0]()),Ri&&(URL.revokeObjectURL(Ri),Ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=zi.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},gy=async()=>{if(!ni){if(cs)throw new Error("multiple calls to 'initWasm()' detected.");if(si)throw new Error("previous call to 'initWasm()' failed.");if(cs=!0,Jr())return new Promise((e,t)=>{Jt?.terminate(),ay().then(([r,n])=>{try{Jt=n,Jt.onerror=a=>t(a),Jt.onmessage=ag,yf=[e,t];let s={type:"init-wasm",in:He};!s.in.wasm.wasmPaths&&(r||rh)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",import.meta.url).href}),Jt.postMessage(s),Ri=r}catch(s){t(s)}},t)});try{await Ph(He.wasm),await Nh(He),ni=!0}catch(e){throw si=!0,e}finally{cs=!1}}},wy=async e=>{if(Jr())return zn(),new Promise((t,r)=>{Rn("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:He}};Jt.postMessage(n)});await Bh(He,e)},yy=async e=>Jr()?(zn(),new Promise((t,r)=>{Rn("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Jt.postMessage(n,[e.buffer])})):ul(e),vy=async(e,t)=>{if(Jr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zn(),new Promise((r,n)=>{Rn("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Jt.postMessage(s,a)})}else return $h(e,t)},by=async e=>{if(Jr())return zn(),new Promise((t,r)=>{Rn("release",[t,r]);let n={type:"release",in:e};Jt.postMessage(n)});Dh(e)},My=async(e,t,r,n,s,a)=>{if(Jr()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return zn(),new Promise((i,c)=>{Rn("run",[i,c]);let u=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:u,outputIndices:n,options:a}};Jt.postMessage(h,Gh(u))})}else return Rh(e,t,r,n,s,a)},xy=async e=>{if(Jr())return zn(),new Promise((t,r)=>{Rn("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Jt.postMessage(n)});zh(e)}}),vf,og,Ey,C1=Te(()=>{ns(),Ty(),As(),Ah(),cy(),vf=(e,t)=>{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 ${t()}`)}},og=e=>{switch(e[3]){case"cpu":return new ur(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ih(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return ur.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!Lh(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return ur.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},Ey=class{async fetchModelAndCopyToWasmMemory(e){return yy(await Oh(e))}async loadModel(e,t){ts();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await vy(r,t),rs()}async dispose(){return by(this.sessionId)}async run(e,t,r){ts();let n=[],s=[];Object.entries(e).forEach(_=>{let m=_[0],w=_[1],b=this.inputNames.indexOf(m);if(b===-1)throw new Error(`invalid input '${m}'`);n.push(w),s.push(b)});let a=[],i=[];Object.entries(t).forEach(_=>{let m=_[0],w=_[1],b=this.outputNames.indexOf(m);if(b===-1)throw new Error(`invalid output '${m}'`);a.push(w),i.push(b)});let c=n.map((_,m)=>vf(_,()=>`input "${this.inputNames[s[m]]}"`)),u=a.map((_,m)=>_?vf(_,()=>`output "${this.outputNames[i[m]]}"`):null),h=await My(this.sessionId,s,c,i,u,r),p={};for(let _=0;_oh,initializeFlags:()=>ah,wasmBackend:()=>Cy});var ah,oh,Cy,A1=Te(()=>{ns(),Ty(),C1(),ah=()=>{(typeof He.wasm.initTimeout!="number"||He.wasm.initTimeout<0)&&(He.wasm.initTimeout=0);let e=He.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),He.wasm.simd=!1),typeof He.wasm.proxy!="boolean"&&(He.wasm.proxy=!1),typeof He.wasm.trace!="boolean"&&(He.wasm.trace=!1),typeof He.wasm.numThreads!="number"||!Number.isInteger(He.wasm.numThreads)||He.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)He.wasm.numThreads=1;else{let t=typeof navigator>"u"?a1("node:os").cpus().length:navigator.hardwareConcurrency;He.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},oh=class{async init(e){ah(),await gy(),await wy(e)}async createInferenceSessionHandler(e,t){let r=new Ey;return await r.loadModel(e,t),r}},Cy=new oh});ns();ns();ns();var S1="1.26.0-dev.20260416-b7804b056c",P1=Zw;{let e=(A1(),ol(ky)).wasmBackend;Jn("webgpu",e,5),Jn("webnn",e,5),Jn("cpu",e,10),Jn("wasm",e,10)}Object.defineProperty(He.versions,"web",{value:S1,enumerable:!0});var F1=Object.freeze({__proto__:null,get InferenceSession(){return Ch},get TRACE(){return il},get TRACE_EVENT_BEGIN(){return an},get TRACE_EVENT_END(){return on},get TRACE_FUNC_BEGIN(){return ts},get TRACE_FUNC_END(){return rs},get Tensor(){return ur},default:P1,get env(){return He},get registerBackend(){return Jn}});const I1=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];const n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);const i=t?.format!==void 0?t.format:"RGB",c=t?.norm;let u,h;c===void 0||c.mean===void 0?u=[255,255,255,255]:typeof c.mean=="number"?u=[c.mean,c.mean,c.mean,c.mean]:(u=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(u[3]=c.mean[3])),c===void 0||c.bias===void 0?h=[0,0,0,0]:typeof c.bias=="number"?h=[c.bias,c.bias,c.bias,c.bias]:(h=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(h[3]=c.bias[3]));const p=a*s;let _=0,m=p,w=p*2,b=-1;i==="RGBA"?(_=0,m=p,w=p*2,b=p*3):i==="RGB"?(_=0,m=p,w=p*2):i==="RBG"&&(_=0,w=p,m=p*2);for(let M=0;M{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let s,a,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);const c=t!==void 0&&t.format!==void 0?t.format:"RGB",u=t?.norm;let h,p;u===void 0||u.mean===void 0?h=[255,255,255,255]:typeof u.mean=="number"?h=[u.mean,u.mean,u.mean,u.mean]:(h=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(h[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));const _=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const m=4;let w=0,b=1,M=2,E=3,T=0,C=_,P=_*2,A=-1;c==="RGBA"?(T=0,C=_,P=_*2,A=_*3):c==="RGB"?(T=0,C=_,P=_*2):c==="RBG"&&(T=0,P=_,C=_*2),n=r.createImageData(s,a);for(let F=0;F{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:n}=t,s=t.norm??{mean:255,bias:0};let a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const c=t.format!==void 0?t.format:"RGBA",u=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,p=u==="RGBA"?new Float32Array(h*4):new Float32Array(h*3);let _=4,m=0,w=1,b=2,M=3,E=0,T=h,C=h*2,P=-1;c==="RGB"&&(_=3,m=0,w=1,b=2,M=-1),u==="RGBA"?P=h*3:u==="RBG"?(E=0,C=h,T=h*2):u==="BGR"&&(C=0,T=h,E=h*2);for(let F=0;F{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let i,c=t??{};const u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){const p=u();p.width=e.width,p.height=e.height;const _=h(p);if(_!=null){let m=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(m=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=m,c.width=w}else c.tensorFormat="RGBA",c.height=m,c.width=w;_.drawImage(e,0,0),i=_.getImageData(0,0,w,m).data}else throw new Error("Can not access image data")}else if(n){let p,_;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,_=t.resizedWidth):(p=e.height,_=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=p,c.width=_,t!==void 0){const m=u();m.width=_,m.height=p;const w=h(m);if(w!=null)w.putImageData(e,0,0),i=w.getImageData(0,0,_,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=u();p.width=e.width,p.height=e.height;const _=h(p);if(_!=null){const m=e.height,w=e.width;return _.drawImage(e,0,0,w,m),i=_.getImageData(0,0,w,m).data,c.height=m,c.width=w,bf(i,c)}else throw new Error("Can not access image data")}else{if(a)return new Promise((p,_)=>{const m=u(),w=h(m);if(!e||!w)return _();const b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{m.width=b.width,m.height=b.height,w.drawImage(b,0,0,m.width,m.height);const M=w.getImageData(0,0,m.width,m.height);c.height=m.height,c.width=m.width,p(bf(M.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return bf(i,c);throw new Error("Input data provided is not supported - aborted tensor creation")},N1=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new tr({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},B1=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new tr({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},$1=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new tr({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},D1=(e,t,r)=>new tr({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),ws=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),rl=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ig=!1;const R1=()=>{if(!ig){ig=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(ws.set("int64",BigInt64Array),rl.set(BigInt64Array,"int64")),t&&(ws.set("uint64",BigUint64Array),rl.set(BigUint64Array,"uint64")),n?(ws.set("float16",r),rl.set(r,"float16")):ws.set("float16",Uint16Array)}},z1=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new tr(e.type,e.data,t);case"cpu-pinned":return new tr({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new tr({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new tr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new tr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let tr=class{constructor(t,r,n){R1();let s,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,a=t.dims,t.location){case"cpu-pinned":{const c=ws.get(s);if(!c)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof c))throw new TypeError(`buffer should be of type ${c.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let c,u;if(typeof t=="string")if(s=t,u=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");c=r}else{const h=ws.get(t);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&h===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${h.name} as data.`);t==="uint64"||t==="int64"?c=h.from(r,BigInt):c=h.from(r)}else if(r instanceof h)c=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")c=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&h!==Uint16Array)c=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${h}`)}else if(u=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const h=typeof t[0];if(h==="string")s="string",c=t;else if(h==="boolean")s="bool",c=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",c=Uint8Array.from(t);else{const h=rl.get(t.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=h,c=t}if(u===void 0)u=[c.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");a=u,this.cpuData=c,this.dataLocation="cpu"}const i=z1(a);if(this.cpuData&&i!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=a,this.size=i}static async fromImage(t,r){return O1(t,r)}static fromTexture(t,r){return N1(t,r)}static fromGpuBuffer(t,r){return B1(t,r)}static fromMLTensor(t,r){return $1(t,r)}static fromPinnedBuffer(t,r,n){return D1(t,r,n)}toDataURL(t){return I1(this,t)}toImageData(t){return L1(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return G1(this,t)}};const U1=tr;var Mf={},V1=Object.defineProperty,Ss=(e,t)=>{for(var r in t)V1(e,r,{get:t[r],enumerable:!0})},qt={},xr={},W1={},j1="4.2.0",Uh=typeof self<"u",Ms=!Fy(qt),Ay=!Fy(xr),dl=Uh&&"caches"in self,q1=typeof globalThis.Deno<"u",kl=q1&&dl&&!Ms,Sy=typeof process<"u",Py=Sy&&process?.release?.name==="node"&&!kl,Vh=typeof window<"u"&&typeof window.document<"u",Wh=Uh&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),H1=Vh||Wh||kl,Q1=Py||typeof navigator<"u"&&"gpu"in navigator,Y1=typeof navigator<"u"&&"ml"in navigator,X1=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",J1=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",K1=typeof ServiceWorkerGlobalScope<"u"&&Uh&&self instanceof ServiceWorkerGlobalScope,Z1=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&n},ex=Z1(),ve=Object.freeze({IS_BROWSER_ENV:Vh,IS_WEBWORKER_ENV:Wh,IS_WEB_ENV:H1,IS_SERVICE_WORKER_ENV:K1,IS_DENO_WEB_RUNTIME:kl,IS_WEB_CACHE_AVAILABLE:dl,IS_WEBGPU_AVAILABLE:Q1,IS_WEBNN_AVAILABLE:Y1,IS_SAFARI:ex,IS_PROCESS_AVAILABLE:Sy,IS_NODE_ENV:Py,IS_FS_AVAILABLE:Ms,IS_PATH_AVAILABLE:Ay,IS_CRYPTO_AVAILABLE:X1,IS_CHROME_AVAILABLE:J1}),jh=Ms&&Ay,fl="./";if(jh){const e=Object(import.meta).url;e?fl=xr.dirname(xr.dirname(W1.fileURLToPath(e))):typeof __dirname<"u"&&(fl=xr.dirname(__dirname))}var tx=jh?xr.join(fl,"/.cache/"):null,lg="/models/",rx=jh?xr.join(fl,lg):lg,nx=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,dr=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),cg=dr.WARNING,Se={version:j1,backends:{onnx:{}},get logLevel(){return cg},set logLevel(e){cg=e,Se.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Vh||Wh||kl),localModelPath:rx,useFS:Ms,useBrowserCache:dl,useFSCache:Ms,cacheDir:tx,useCustomCache:!1,customCache:null,useWasmCache:dl||Ms,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:nx};function Fy(e){return Object.keys(e).length===0}var Yt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Qn(e,t){e&&e(t)}var ug=class extends Yt{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};const t=Object.values(this.files_loading).reduce((s,a)=>s+a.loaded,0),r=Object.values(this.files_loading).reduce((s,a)=>s+a.total,0),n=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function sx(e){return Number.isInteger(e)||typeof e=="bigint"}function dg(e){return e==null||e===-1}function fg(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Tr(...e){return Array.prototype.concat.apply([],e)}function hl(e,t){return Math.abs((e+t)%(2*t)-t)}function xt(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function ax(e,t){let r=0;for(const n of e)n===t&&++r;return r}var be={error(...e){Se.logLevel<=dr.ERROR&&console.error(...e)},warn(...e){Se.logLevel<=dr.WARNING&&console.warn(...e)},info(...e){Se.logLevel<=dr.INFO&&console.log(...e)},debug(...e){Se.logLevel<=dr.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},ox=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let n=t;for(let s=0;sn&&t.push(e.slice(n,s)),t.push(i),s+=i.length,n=s):++s}return n{const e=[...Array.from({length:94},(s,a)=>a+33),...Array.from({length:12},(s,a)=>a+161),...Array.from({length:82},(s,a)=>a+174)],t=e.slice();let r=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+r),r+=1);const n=t.map(s=>String.fromCharCode(s));return Object.fromEntries(e.map((s,a)=>[s,n[a]]))})(),cx=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),ux=cx(Iy),pg=".,!?…。,、।۔،",dx=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${pg}])]+`,` ?[^\\s${pg}]+`]]),pl="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",qh=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Cl=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[n,s]of dx)r=r.replaceAll(n,s);try{return new RegExp(r,"gu")}catch(n){if(!(n instanceof SyntaxError)||!n.message.toLowerCase().includes("invalid property name"))throw n;let s=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(i,c,u)=>{try{return new RegExp(`\\p{${u}}`,"u"),`${c}{${u}}`}catch{return s=!0,`${c}{Script=${u}}`}});if(!s)throw n;try{return new RegExp(a,"gu")}catch{throw n}}}else if(e.String!==void 0){const r=fx(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},fx=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),hx=(e,t,r)=>{const n=[];let s=0;for(;se>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,_x=e=>Number.isInteger(e)||typeof e=="bigint",mx=e=>{let t=0;for(const r of e)++t;return t},gx=e=>Ly(e.toLowerCase()),fr=(...e)=>Array.prototype.concat.apply([],e),Hh=e=>new Map(Object.entries(e)),wx=(e,t)=>{const r=[];let n=0;for(const s of e.matchAll(t)){const a=s[0];n0&&r.push(a),n=s.index+a.length}return ne.replace(/\p{M}/gu,""),_g=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},yx=e=>e.match(/\S+/g)||[],vx=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Mi=vx,bx=class extends Mi{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},Wr=bx,Mx=class extends Wr{tokenize_chinese_chars(e){const t=[];for(let r=0;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},Ex=Tx,kx=class extends Wr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Oy(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},Cx=kx,Ax=class extends Wr{normalize(e){const t=Cl(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},Sx=Ax,Px=class extends Wr{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Al=Px,Fx=class extends Al{constructor(){super(...arguments),this.form="NFC"}},Ix=Fx,Lx=class extends Al{constructor(){super(...arguments),this.form="NFD"}},Ox=Lx,Nx=class extends Al{constructor(){super(...arguments),this.form="NFKC"}},Bx=Nx,$x=class extends Al{constructor(){super(...arguments),this.form="NFKD"}},Dx=$x,Rx=class extends Wr{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},zx=Rx,Gx=class extends Wr{normalize(e){return Ly(e)}},Ux=Gx,Vx=class extends Wr{normalize(e){return e.toLowerCase()}},Wx=Vx,jx=class extends Wr{normalize(e){return e=this.config.prepend+e,e}},qx=jx;function Hx(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new xx(e);case"Precompiled":return new Ex(e);case"Sequence":return new Cx(e);case"Replace":return new Sx(e);case"NFC":return new Ix(e);case"NFD":return new Ox(e);case"NFKC":return new Bx(e);case"NFKD":return new Dx(e);case"Strip":return new zx(e);case"StripAccents":return new Ux(e);case"Lowercase":return new Wx(e);case"Prepend":return new qx(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Oy=Hx,Qx=class extends Mi{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},pr=Qx,Yx=class extends pr{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Iy,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(n=>Array.from(this.text_encoder.encode(n),s=>this.byte_encoder[s]).join(""))}},Xx=Yx,Jx=class extends pr{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Kx=Jx,Zx=class extends pr{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:r=void 0}=t??{};let n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},eT=Zx,tT=class extends pr{constructor(e){super(),this.config=e,this.pattern=Cl(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):wx(e,this.pattern)}},rT=tT,nT=class extends pr{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${pl}]+|[${pl}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},sT=nT,aT=class extends pr{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},oT=aT,iT=class extends pr{constructor(){super(),this.pattern=new RegExp(`[^\\s${pl}]+|[${pl}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},lT=iT,cT=class extends pr{constructor(e){super(),this.config=e,this.pattern=Cl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},uT=cT,dT=class extends pr{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Ny(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},fT=dT,hT=class extends pr{pre_tokenize_text(e){return yx(e)}},pT=hT,_T=class extends pr{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;rthis.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0;const i=[];for(;a0&&(h=this.config.continuing_subword_prefix+h),this.tokens_to_ids.has(h)){u=h;break}--c}if(u===null){s=!0;break}i.push(u),a=c}s?t.push(this.unk_token):t.push(...i)}return t}},mg=yT,gg=class By{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new By(!1,new Map)}},vT=class{constructor(){this.root=gg.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let n=t.children.get(r);n===void 0&&(n=gg.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},bT=vT,xf=class $y{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new $y(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},MT=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);const n=new xf(this.bos_token_id??0,0,0,0,0),s=new xf(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(e,t,r,n){const s=this.nodes.length,a=new xf(n,s,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let i of this.begin_nodes[t]){i.prev=null;let c=0,u=null;for(let h of this.end_nodes[t]){const p=h.backtrace_score+i.score;(u===null||p>c)&&(u=h.clone(),c=p)}if(u!==null)i.prev=u,i.backtrace_score=c;else return[]}++t}const r=[],s=this.begin_nodes[e][0].prev;if(s===null)return[];let a=s.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},xT=MT;function TT(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=TT(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new bT,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let n=0;for(;nr>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},ST=AT,PT=class extends Sl{constructor(e){super(e),this.tokens_to_ids=Hh(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new ST(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){const s=new CT((c,u)=>c.score`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(i=>this.tokens_to_ids.has(i))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},yg=PT,FT=class extends Sl{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=Hh(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(e){return e}},IT=FT;function LT(e,t){switch(e.type){case"WordPiece":return new mg(e);case"Unigram":return new wg(e,t.eos_token);case"BPE":return new yg(e);default:if(e.vocab)return Array.isArray(e.vocab)?new wg(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new yg(e):new mg(e):new IT(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var OT=LT,NT=class extends Mi{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},xi=NT,BT=class extends xi{post_process(e,t=null,r=!0){const n=t===null?this.config.single:this.config.pair;let s=[],a=[];for(const i of n)"SpecialToken"in i?r&&(s.push(i.SpecialToken.id),a.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(s=fr(s,e),a=fr(a,new Array(e.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(s=fr(s,t),a=fr(a,new Array(t.length).fill(i.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},$T=BT,DT=class extends xi{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},RT=DT,zT=class extends xi{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=fr([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=[],a=r?[this.sep[0]]:[];e=fr(e,s,t,a),n=fr(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},GT=zT,UT=class extends xi{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=fr([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=fr(e,s,t,a),n=fr(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},VT=UT,WT=class extends xi{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>Dy(t))}post_process(e,t=null,r=!0){let n={tokens:e,tokens_pair:t};for(const s of this.processors)n=s.post_process(n.tokens,n.tokens_pair,r);return n}},jT=WT;function qT(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new $T(e);case"ByteLevel":return new RT(e);case"BertProcessing":return new GT(e);case"RobertaProcessing":return new VT(e);case"Sequence":return new jT(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var Dy=qT,HT=class extends Mi{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},_r=HT,QT=class extends _r{constructor(e){super(e),this.byte_decoder=ux,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const n of e)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},YT=QT,XT=class extends _r{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=qh(t)),t})}},JT=XT,KT=class extends _r{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;rt.replaceAll(this.suffix,r===e.length-1?"":" "))}},t2=e2,r2=class extends _r{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let s=1;ss!==this.pad_token).join("");return this.cleanup&&(n=qh(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},n2=r2,s2=class extends _r{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Ry(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},a2=s2,o2=class extends _r{decode_chain(e){const t=Cl(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},i2=o2,l2=class extends _r{decode_chain(e){return[e.join("")]}},c2=l2,u2=class extends _r{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let s=0;s")){const a=parseInt(n.slice(3,5),16);isNaN(a)||(s=a)}if(s!==null)r.push(s);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(n)}}if(r.length>0){const n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},h2=f2;function p2(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new YT(e);case"WordPiece":return new JT(e);case"Metaspace":return new ZT(e);case"BPEDecoder":return new t2(e);case"CTC":return new n2(e);case"Sequence":return new a2(e);case"Replace":return new i2(e);case"Fuse":return new c2(e);case"Strip":return new d2(e);case"ByteFallback":return new h2(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Ry=p2,_2=class{constructor(e,t){const r=_g(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=_g(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=Oy(this.tokenizer.normalizer),this.pre_tokenizer=Ny(this.tokenizer.pre_tokenizer),this.model=OT(this.tokenizer.model,this.config),this.post_processor=Dy(this.tokenizer.post_processor),this.decoder=Ry(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const s=[],a=[];this.added_tokens_map=new Map;for(const i of this.tokenizer.added_tokens){const c=new lx(i);if(this.added_tokens.push(c),this.model.tokens_to_ids.set(c.content,c.id),this.model.vocab[c.id]=c.content,c.special&&(this.special_tokens.push(c.content),this.all_special_ids.push(c.id)),this.added_tokens_map.set(c.content,c),c.normalized&&this.normalizer!==null){const u=this.normalizer(c.content);a.push(u),this.added_tokens_map.set(u,c)}else s.push(c.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new hg(s),this.splitter_normalized=new hg(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),i=s.map(u=>this.added_tokens_map.get(u)?.id??this.model.tokens_to_ids.get(u)??this.model.unk_token_id),c={ids:i,tokens:s,attention_mask:new Array(i.length).fill(1)};return n&&a&&(c.token_type_ids=a),c}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!_x(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(s=>this.model.vocab[Number(s)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=qh(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,n)=>{const s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),s.rstrip&&n{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=gx(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const s=this.splitter_normalized.split(r);return s.forEach((a,i)=>{const c=this.added_tokens_map.get(a);c&&(c.lstrip&&i>0&&(s[i-1]=s[i-1].trimEnd()),c.rstrip&&i{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const i=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:n}):[a];return this.model(i)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const n=this.encode_text(e),s=this.encode_text(t||null);return this.post_processor?this.post_processor(n,s,r):{tokens:fr(n??[],s??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let r=0;r=",V.ComparisonBinaryOperator],["==",V.ComparisonBinaryOperator],["!=",V.ComparisonBinaryOperator],["<",V.ComparisonBinaryOperator],[">",V.ComparisonBinaryOperator],["+",V.AdditiveBinaryOperator],["-",V.AdditiveBinaryOperator],["~",V.AdditiveBinaryOperator],["*",V.MultiplicativeBinaryOperator],["/",V.MultiplicativeBinaryOperator],["%",V.MultiplicativeBinaryOperator],["=",V.Equals]],w2=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y2(e,t={}){return e.endsWith(` `)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function v2(e,t={}){const r=[],n=y2(e,t);let s=0,a=0;const i=h=>{let p="";for(;h(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const _=n[s++],m=w2.get(_);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${_}`);p+=m;continue}if(p+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return p},c=()=>{const h=r.at(-1);h&&h.type===V.Text&&(h.value=h.value.trimEnd(),h.value===""&&r.pop())},u=()=>{for(;s0){r.push(new Zt(_,V.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const _=n[s]==="-";_&&++s;let m="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");m+=n[s++]}const w=m.endsWith("-");w&&(m=m.slice(0,-1)),_&&c(),r.push(new Zt(m,V.Comment)),s+=2,w&&u();continue}if(n.slice(s,s+3)==="{%-"){c(),r.push(new Zt("{%",V.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){c(),r.push(new Zt("{{",V.OpenExpression)),a=0,s+=3;continue}if(i(bg),n.slice(s,s+3)==="-%}"){r.push(new Zt("%}",V.CloseStatement)),s+=3,u();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Zt("}}",V.CloseExpression)),s+=3,u();continue}const p=n[s];if(p==="-"||p==="+"){const _=r.at(-1)?.type;if(_===V.Text||_===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(_){case V.Identifier:case V.NumericLiteral:case V.StringLiteral:case V.CloseParen:case V.CloseSquareBracket:break;default:{++s;const m=i(ai);r.push(new Zt(`${p}${m}`,m.length>0?V.NumericLiteral:V.UnaryOperator));continue}}}for(const[_,m]of g2){if(_==="}}"&&a>0)continue;if(n.slice(s,s+_.length)===_){r.push(new Zt(_,m)),m===V.OpenExpression?a=0:m===V.OpenCurlyBracket?++a:m===V.CloseCurlyBracket&&--a,s+=_.length;continue e}}if(p==="'"||p==='"'){++s;const _=i(m=>m!==p);r.push(new Zt(_,V.StringLiteral)),++s;continue}if(ai(p)){let _=i(ai);if(n[s]==="."&&ai(n[s+1])){++s;const m=i(ai);_=`${_}.${m}`}r.push(new Zt(_,V.NumericLiteral));continue}if(vg(p)){const _=i(vg);r.push(new Zt(_,V.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var mr=class{type="Statement"},b2=class extends mr{constructor(e){super(),this.body=e}type="Program"},M2=class extends mr{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},x2=class extends mr{constructor(e,t,r,n){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},T2=class extends mr{type="Break"},E2=class extends mr{type="Continue"},k2=class extends mr{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},C2=class extends mr{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},A2=class extends mr{constructor(e){super(),this.value=e}type="Comment"},Xt=class extends mr{type="Expression"},S2=class extends Xt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},Mg=class extends Xt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},us=class extends Xt{constructor(e){super(),this.value=e}type="Identifier"},Ps=class extends Xt{constructor(e){super(),this.value=e}type="Literal"},P2=class extends Ps{type="IntegerLiteral"},F2=class extends Ps{type="FloatLiteral"},xg=class extends Ps{type="StringLiteral"},I2=class extends Ps{type="ArrayLiteral"},Tg=class extends Ps{type="TupleLiteral"},L2=class extends Ps{type="ObjectLiteral"},oi=class extends Xt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},O2=class extends Xt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},N2=class extends mr{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},B2=class extends Xt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},$2=class extends Xt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},D2=class extends Xt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},R2=class extends Xt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},z2=class extends Xt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},G2=class extends Xt{constructor(e){super(),this.argument=e}type="SpreadExpression"},U2=class extends mr{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},V2=class extends Xt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function W2(e){const t=new b2([]);let r=0;function n(N,$){const z=e[r++];if(!z||z.type!==N)throw new Error(`Parser Error: ${$}. ${z.type} !== ${N}.`);return z}function s(N){if(!u(N))throw new SyntaxError(`Expected ${N}`);++r}function a(){switch(e[r].type){case V.Comment:return new A2(e[r++].value);case V.Text:return h();case V.OpenStatement:return p();case V.OpenExpression:return _();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function i(...N){return r+N.length<=e.length&&N.every(($,z)=>$===e[r+z].type)}function c(...N){return e[r]?.type===V.OpenStatement&&e[r+1]?.type===V.Identifier&&N.includes(e[r+1]?.value)}function u(...N){return r+N.length<=e.length&&N.every(($,z)=>e[r+z].type==="Identifier"&&$===e[r+z].value)}function h(){return new xg(n(V.Text,"Expected text token").value)}function p(){if(n(V.OpenStatement,"Expected opening statement token"),e[r].type!==V.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const N=e[r].value;let $;switch(N){case"set":++r,$=m();break;case"if":++r,$=w(),n(V.OpenStatement,"Expected {% token"),s("endif"),n(V.CloseStatement,"Expected %} token");break;case"macro":++r,$=b(),n(V.OpenStatement,"Expected {% token"),s("endmacro"),n(V.CloseStatement,"Expected %} token");break;case"for":++r,$=E(),n(V.OpenStatement,"Expected {% token"),s("endfor"),n(V.CloseStatement,"Expected %} token");break;case"call":{++r;let z=null;i(V.OpenParen)&&(z=q());const Q=se();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const _e=q();n(V.CloseStatement,"Expected closing statement token");const me=[];for(;!c("endcall");)me.push(a());n(V.OpenStatement,"Expected '{%'"),s("endcall"),n(V.CloseStatement,"Expected closing statement token");const de=new Mg(Q,_e);$=new U2(de,z,me);break}case"break":++r,n(V.CloseStatement,"Expected closing statement token"),$=new T2;break;case"continue":++r,n(V.CloseStatement,"Expected closing statement token"),$=new E2;break;case"filter":{++r;let z=se();z instanceof us&&i(V.OpenParen)&&(z=U(z)),n(V.CloseStatement,"Expected closing statement token");const Q=[];for(;!c("endfilter");)Q.push(a());n(V.OpenStatement,"Expected '{%'"),s("endfilter"),n(V.CloseStatement,"Expected '%}'"),$=new N2(z,Q);break}default:throw new SyntaxError(`Unknown statement type: ${N}`)}return $}function _(){n(V.OpenExpression,"Expected opening expression token");const N=T();return n(V.CloseExpression,"Expected closing expression token"),N}function m(){const N=M();let $=null;const z=[];if(i(V.Equals))++r,$=M();else{for(n(V.CloseStatement,"Expected %} token");!c("endset");)z.push(a());n(V.OpenStatement,"Expected {% token"),s("endset")}return n(V.CloseStatement,"Expected closing statement token"),new k2(N,$,z)}function w(){const N=T();n(V.CloseStatement,"Expected closing statement token");const $=[],z=[];for(;!c("elif","else","endif");)$.push(a());if(c("elif")){++r,++r;const Q=w();z.push(Q)}else if(c("else"))for(++r,++r,n(V.CloseStatement,"Expected closing statement token");!c("endif");)z.push(a());return new M2(N,$,z)}function b(){const N=se();if(N.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const $=q();n(V.CloseStatement,"Expected closing statement token");const z=[];for(;!c("endmacro");)z.push(a());return new C2(N,$,z)}function M(N=!1){const $=N?se:T,z=[$()],Q=i(V.Comma);for(;Q&&(++r,z.push($()),!!i(V.Comma)););return Q?new Tg(z):z[0]}function E(){const N=M(!0);if(!(N instanceof us||N instanceof Tg))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${N.type} instead`);if(!u("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const $=T();n(V.CloseStatement,"Expected closing statement token");const z=[];for(;!c("endfor","else");)z.push(a());const Q=[];if(c("else"))for(++r,++r,n(V.CloseStatement,"Expected closing statement token");!c("endfor");)Q.push(a());return new x2(N,$,z,Q)}function T(){return C()}function C(){const N=P();if(u("if")){++r;const $=P();if(u("else")){++r;const z=C();return new V2($,N,z)}else return new B2(N,$)}return N}function P(){let N=A();for(;u("or");){const $=e[r];++r;const z=A();N=new oi($,N,z)}return N}function A(){let N=F();for(;u("and");){const $=e[r];++r;const z=F();N=new oi($,N,z)}return N}function F(){let N;for(;u("not");){const $=e[r];++r;const z=F();N=new D2($,z)}return N??G()}function G(){let N=v();for(;;){let $;if(u("not","in"))$=new Zt("not in",V.Identifier),r+=2;else if(u("in"))$=e[r++];else if(i(V.ComparisonBinaryOperator))$=e[r++];else break;const z=v();N=new oi($,N,z)}return N}function v(){let N=S();for(;i(V.AdditiveBinaryOperator);){const $=e[r];++r;const z=S();N=new oi($,N,z)}return N}function j(){const N=I(se());return i(V.OpenParen)?U(N):N}function U(N){let $=new Mg(N,q());return $=I($),i(V.OpenParen)&&($=U($)),$}function q(){n(V.OpenParen,"Expected opening parenthesis for arguments list");const N=ne();return n(V.CloseParen,"Expected closing parenthesis for arguments list"),N}function ne(){const N=[];for(;!i(V.CloseParen);){let $;if(e[r].type===V.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const z=T();$=new G2(z)}else if($=T(),i(V.Equals)){if(++r,!($ instanceof us))throw new SyntaxError("Expected identifier for keyword argument");const z=T();$=new z2($,z)}N.push($),i(V.Comma)&&++r}return N}function H(){const N=[];let $=!1;for(;!i(V.CloseSquareBracket);)i(V.Colon)?(N.push(void 0),++r,$=!0):(N.push(T()),i(V.Colon)&&(++r,$=!0));if(N.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(N.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new R2(...N)}return N[0]}function I(N){for(;i(V.Dot)||i(V.OpenSquareBracket);){const $=e[r];++r;let z;const Q=$.type===V.OpenSquareBracket;if(Q)z=H(),n(V.CloseSquareBracket,"Expected closing square bracket");else if(z=se(),z.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");N=new S2(N,z,Q)}return N}function S(){let N=D();for(;i(V.MultiplicativeBinaryOperator);){const $=e[r++],z=D();N=new oi($,N,z)}return N}function D(){let N=Y();for(;u("is");){++r;const $=u("not");$&&++r;const z=se();if(!(z instanceof us))throw new SyntaxError("Expected identifier for the test");N=new $2(N,$,z)}return N}function Y(){let N=j();for(;i(V.Pipe);){++r;let $=se();if(!($ instanceof us))throw new SyntaxError("Expected identifier for the filter");i(V.OpenParen)&&($=U($)),N=new O2(N,$)}return N}function se(){const N=e[r++];switch(N.type){case V.NumericLiteral:{const $=N.value;return $.includes(".")?new F2(Number($)):new P2(Number($))}case V.StringLiteral:{let $=N.value;for(;i(V.StringLiteral);)$+=e[r++].value;return new xg($)}case V.Identifier:return new us(N.value);case V.OpenParen:{const $=M();return n(V.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case V.OpenSquareBracket:{const $=[];for(;!i(V.CloseSquareBracket);)$.push(T()),i(V.Comma)&&++r;return++r,new I2($)}case V.OpenCurlyBracket:{const $=new Map;for(;!i(V.CloseCurlyBracket);){const z=T();n(V.Colon,"Expected colon between key and value in object literal");const Q=T();$.set(z,Q),i(V.Comma)&&++r}return++r,new L2($)}default:throw new SyntaxError(`Unexpected token: ${N.type}`)}}for(;r0)for(let s=e;st;s+=r)n.push(s);return n}function Eg(e,t,r,n=1){const s=Math.sign(n);s>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let i=t;s*it.toUpperCase())}function H2(e){return Q2(new Date,e)}function Q2(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),s=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return s(e.getMonth()+1);case"%d":return s(e.getDate());case"%b":return n.format(e);case"%B":return r.format(e);case"%H":return s(e.getHours());case"%M":return s(e.getMinutes());case"%%":return"%";default:return a}})}function Y2(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X2(e,t,r,n){if(n===0)return e;let s=n==null||n<0?1/0:n;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(Y2(t),"gu");return e.replaceAll(a,i=>s>0?(--s,r):i)}var kg=class extends Error{},Cg=class extends Error{},Cr=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new he(!!this.value)}toString(){return String(this.value)}},we=class extends Cr{type="IntegerValue"},Ze=class extends Cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ae=class extends Cr{type="StringValue";builtins=new Map([["upper",new We(()=>new ae(this.value.toUpperCase()))],["lower",new We(()=>new ae(this.value.toLowerCase()))],["strip",new We(()=>new ae(this.value.trim()))],["title",new We(()=>new ae(q2(this.value)))],["capitalize",new We(()=>new ae(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new we(this.value.length)],["rstrip",new We(()=>new ae(this.value.trimEnd()))],["lstrip",new We(()=>new ae(this.value.trimStart()))],["startswith",new We(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof ae)return new he(this.value.startsWith(t.value));if(t instanceof xe){for(const r of t.value){if(!(r instanceof ae))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new he(!0)}return new he(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new We(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof ae)return new he(this.value.endsWith(t.value));if(t instanceof xe){for(const r of t.value){if(!(r instanceof ae))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new he(!0)}return new he(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new We(e=>{const t=e[0]??new Ye;if(!(t instanceof ae||t instanceof Ye))throw new Error("sep argument must be a string or null");const r=e[1]??new we(-1);if(!(r instanceof we))throw new Error("maxsplit argument must be a number");let n=[];if(t instanceof Ye){const s=this.value.trimStart();for(const{0:a,index:i}of s.matchAll(/\S+/g)){if(r.value!==-1&&n.length>=r.value&&i!==void 0){n.push(a+s.slice(i+a.length));break}n.push(a)}}else{if(t.value==="")throw new Error("empty separator");n=this.value.split(t.value),r.value!==-1&&n.length>r.value&&n.push(n.splice(r.value).join(t.value))}return new xe(n.map(s=>new ae(s)))})],["replace",new We(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],r=e[1];if(!(t instanceof ae&&r instanceof ae))throw new Error("replace() arguments must be strings");let n;if(e.length>2?e[2].type==="KeywordArgumentsValue"?n=e[2].value.get("count")??new Ye:n=e[2]:n=new Ye,!(n instanceof we||n instanceof Ye))throw new Error("replace() count argument must be a number or null");return new ae(X2(this.value,t.value,r.value,n.value))})]])},he=class extends Cr{type="BooleanValue"},J2=/[\x7f-\uffff]/g;function Ag(e){return e.replace(J2,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Kn(e,t={},r=0,n=!0){const{indent:s=null,ensureAscii:a=!1,separators:i=null,sortKeys:c=!1}=t;let u,h;switch(i?[u,h]=i:s?(u=",",h=": "):(u=", ",h=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let p=JSON.stringify(e.value);return a&&(p=Ag(p)),p}case"ArrayValue":case"ObjectValue":{const p=s?" ".repeat(s):"",_=` `+p.repeat(r),m=_+p;if(e.type==="ArrayValue"){const w=e.value.map(b=>Kn(b,t,r+1,n));return s?`[${m}${w.join(`${u}${m}`)}${_}]`:`[${w.join(u)}]`}else{let w=Array.from(e.value.entries());c&&(w=w.sort(([M],[E])=>M.localeCompare(E)));const b=w.map(([M,E])=>{let T=JSON.stringify(M);a&&(T=Ag(T));const C=`${T}${h}${Kn(E,t,r+1,n)}`;return s?`${m}${C}`:C});return s?`{${b.join(u)}${_}}`:`{${b.join(u)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var yt=class extends Cr{type="ObjectValue";__bool__(){return new he(this.value.size>0)}builtins=new Map([["get",new We(([e,t])=>{if(!(e instanceof ae))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Ye})],["items",new We(()=>this.items())],["keys",new We(()=>this.keys())],["values",new We(()=>this.values())],["dictsort",new We(e=>{let t=new Map;const r=e.filter(c=>c instanceof hi?(t=c.value,!1):!0),n=r.at(0)??t.get("case_sensitive")??new he(!1);if(!(n instanceof he))throw new Error("case_sensitive must be a boolean");const s=r.at(1)??t.get("by")??new ae("key");if(!(s instanceof ae))throw new Error("by must be a string");if(!["key","value"].includes(s.value))throw new Error("by must be either 'key' or 'value'");const a=r.at(2)??t.get("reverse")??new he(!1);if(!(a instanceof he))throw new Error("reverse must be a boolean");const i=Array.from(this.value.entries()).map(([c,u])=>new xe([new ae(c),u])).sort((c,u)=>{const h=s.value==="key"?0:1,p=c.value[h],_=u.value[h],m=ih(p,_,n.value);return a.value?-m:m});return new xe(i)})]]);items(){return new xe(Array.from(this.value.entries()).map(([e,t])=>new xe([new ae(e),t])))}keys(){return new xe(Array.from(this.value.keys()).map(e=>new ae(e)))}values(){return new xe(Array.from(this.value.values()))}toString(){return Kn(this,{},0,!1)}},hi=class extends yt{type="KeywordArgumentsValue"},xe=class extends Cr{type="ArrayValue";builtins=new Map([["length",new we(this.value.length)]]);__bool__(){return new he(this.value.length>0)}toString(){return Kn(this,{},0,!1)}},Sg=class extends xe{type="TupleValue"},We=class extends Cr{type="FunctionValue"},Ye=class extends Cr{type="NullValue"},Ve=class extends Cr{type="UndefinedValue"},Wn=class{constructor(e){this.parent=e}variables=new Map([["namespace",new We(e=>{if(e.length===0)return new yt(new Map);if(e.length!==1||!(e[0]instanceof yt))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof We],["odd",e=>{if(!(e instanceof we))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof we))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof we||e instanceof Ze],["integer",e=>e instanceof we],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof yt],["sequence",e=>e instanceof xe||e instanceof yt||e instanceof ae],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,nl(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Ve}catch{return new Ve}}};function K2(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",j2),e.set("strftime_now",H2),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Pg(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof yt)n=n.value.get(s)??new Ve;else if(n instanceof xe){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&aa instanceof we||a instanceof Ze||a instanceof he,s=a=>a instanceof he?a.value?1:0:a.value;if(n(e)&&n(t)){const a=s(e),i=s(t);return ai?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let a=e.value,i=t.value;return r||(a=a.toLowerCase(),i=i.toLowerCase()),ai?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var Z2=class{global;constructor(e){this.global=e??new Wn}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}const n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new he(r.value==n.value);case"!=":return new he(r.value!=n.value)}if(r instanceof Ve||n instanceof Ve){if(n instanceof Ve&&["in","not in"].includes(e.operator.value))return new he(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Ye||n instanceof Ye)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new ae(r.value.toString()+n.value.toString());if((r instanceof we||r instanceof Ze)&&(n instanceof we||n instanceof Ze)){const s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{const i=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof Ze||n instanceof Ze?new Ze(i):new we(i)}case"/":return new Ze(s/a);case"%":{const i=s%a;return r instanceof Ze||n instanceof Ze?new Ze(i):new we(i)}case"<":return new he(s":return new he(s>a);case">=":return new he(s>=a);case"<=":return new he(s<=a)}}else if(r instanceof xe&&n instanceof xe)switch(e.operator.value){case"+":return new xe(r.value.concat(n.value))}else if(n instanceof xe){const s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new he(s);case"not in":return new he(!s)}}}if(r instanceof ae||n instanceof ae)switch(e.operator.value){case"+":return new ae(r.value.toString()+n.value.toString())}if(r instanceof ae&&n instanceof ae)switch(e.operator.value){case"in":return new he(n.value.includes(r.value));case"not in":return new he(!n.value.includes(r.value))}if(r instanceof ae&&n instanceof yt)switch(e.operator.value){case"in":return new he(n.value.has(r.value));case"not in":return new he(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(e,t){const r=[],n=new Map;for(const s of e)if(s.type==="SpreadExpression"){const a=s,i=this.evaluate(a.argument,t);if(!(i instanceof xe))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(const c of i.value)r.push(c)}else if(s.type==="KeywordArgumentExpression"){const a=s;n.set(a.key.value,this.evaluate(a.value,t))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,t))}return[r,n]}applyFilter(e,t,r){if(t.type==="Identifier"){const n=t;if(n.value==="safe")return e;if(n.value==="tojson")return new ae(Kn(e,{}));if(e instanceof xe)switch(n.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new we(e.value.length);case"reverse":return new xe(e.value.slice().reverse());case"sort":return new xe(e.value.slice().sort((s,a)=>ih(s,a,!1)));case"join":return new ae(e.value.map(s=>s.value).join(""));case"string":return new ae(Kn(e,{},0,!1));case"unique":{const s=new Set,a=[];for(const i of e.value)s.has(i.value)||(s.add(i.value),a.push(i));return new xe(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof ae)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const s=e.builtins.get(n.value);if(s instanceof We)return s.value([],r);if(s instanceof we)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new ae(e.value.trim());case"indent":return new ae(e.value.split(` `).map((s,a)=>a===0||s.length===0?s:" "+s).join(` `));case"join":case"string":return e;case"int":{const s=parseInt(e.value,10);return new we(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new Ze(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof we||e instanceof Ze)switch(n.value){case"abs":return e instanceof we?new we(Math.abs(e.value)):new Ze(Math.abs(e.value));case"int":return new we(Math.floor(e.value));case"float":return new Ze(e.value);case"string":return new ae(e.toString());default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof yt)switch(n.value){case"items":return new xe(Array.from(e.value.entries()).map(([s,a])=>new xe([new ae(s),a])));case"length":return new we(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof We?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof he)switch(n.value){case"bool":return new he(e.value);case"int":return new we(e.value?1:0);case"float":return new Ze(e.value?1:0);case"string":return new ae(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const n=t;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value;if(s==="tojson"){const[,a]=this.evaluateArguments(n.args,r),i=a.get("indent")??new Ye;if(!(i instanceof we||i instanceof Ye))throw new Error("If set, indent must be a number");const c=a.get("ensure_ascii")??new he(!1);if(!(c instanceof he))throw new Error("If set, ensure_ascii must be a boolean");const u=a.get("sort_keys")??new he(!1);if(!(u instanceof he))throw new Error("If set, sort_keys must be a boolean");const h=a.get("separators")??new Ye;let p=null;if(h instanceof xe||h instanceof Sg){if(h.value.length!==2)throw new Error("separators must be a tuple of two strings");const[_,m]=h.value;if(!(_ instanceof ae)||!(m instanceof ae))throw new Error("separators must be a tuple of two strings");p=[_.value,m.value]}else if(!(h instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new ae(Kn(e,{indent:i.value,ensureAscii:c.value,sortKeys:u.value,separators:p}))}else if(s==="join"){let a;if(e instanceof ae)a=Array.from(e.value);else if(e instanceof xe)a=e.value.map(h=>h.value);else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`);const[i,c]=this.evaluateArguments(n.args,r),u=i.at(0)??c.get("separator")??new ae("");if(!(u instanceof ae))throw new Error("separator must be a string");return new ae(a.join(u.value))}else if(s==="int"||s==="float"){const[a,i]=this.evaluateArguments(n.args,r),c=a.at(0)??i.get("default")??(s==="int"?new we(0):new Ze(0));if(e instanceof ae){const u=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(u)?c:s==="int"?new we(u):new Ze(u)}else{if(e instanceof we||e instanceof Ze)return e;if(e instanceof he)return s==="int"?new we(e.value?1:0):new Ze(e.value?1:0);throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}}else if(s==="default"){const[a,i]=this.evaluateArguments(n.args,r),c=a[0]??new ae(""),u=a[1]??i.get("boolean")??new he(!1);if(!(u instanceof he))throw new Error("`default` filter flag must be a boolean");return e instanceof Ve||u.value&&!e.__bool__().value?c:e}if(e instanceof xe){switch(s){case"sort":{const[a,i]=this.evaluateArguments(n.args,r),c=a.at(0)??i.get("reverse")??new he(!1);if(!(c instanceof he))throw new Error("reverse must be a boolean");const u=a.at(1)??i.get("case_sensitive")??new he(!1);if(!(u instanceof he))throw new Error("case_sensitive must be a boolean");const h=a.at(2)??i.get("attribute")??new Ye;if(!(h instanceof ae||h instanceof we||h instanceof Ye))throw new Error("attribute must be a string, integer, or null");const p=_=>{if(h instanceof Ye)return _;const m=h instanceof we?String(h.value):h.value;return Pg(_,m)};return new xe(e.value.slice().sort((_,m)=>{const w=p(_),b=p(m),M=ih(w,b,u.value);return c.value?-M:M}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(_=>!(_ instanceof yt)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(_=>_.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[i,c,u]=n.args.map(_=>this.evaluate(_,r));let h;if(c){const _=r.tests.get(c.value);if(!_)throw new Error(`Unknown test: ${c.value}`);h=_}else h=(..._)=>_[0].__bool__().value;const p=e.value.filter(_=>{const m=_.value.get(i.value),w=m?h(m,u):!1;return a?w:!w});return new xe(p)}case"map":{const[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){const i=a.get("attribute");if(!(i instanceof ae))throw new Error("attribute must be a string");const c=a.get("default"),u=e.value.map(h=>{if(!(h instanceof yt))throw new Error("items in map must be an object");const p=Pg(h,i.value);return p instanceof Ve?c??new Ve:p});return new xe(u)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof ae){switch(s){case"indent":{const[a,i]=this.evaluateArguments(n.args,r),c=a.at(0)??i.get("width")??new we(4);if(!(c instanceof we))throw new Error("width must be a number");const u=a.at(1)??i.get("first")??new he(!1),h=a.at(2)??i.get("blank")??new he(!1),p=e.value.split(` `),_=" ".repeat(c.value),m=p.map((w,b)=>!u.value&&b===0||!h.value&&w.length===0?w:_+w);return new ae(m.join(` `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof We))throw new Error("replace filter not available");const[i,c]=this.evaluateArguments(n.args,r);return a.value([...i,new hi(c)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof yt){const a=e.builtins.get(s);if(a&&a instanceof We){const[i,c]=this.evaluateArguments(n.args,r);return c.size>0&&i.push(new hi(c)),a.value(i,r)}throw new Error(`Unknown ObjectValue filter: ${s}`)}else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw new Error(`Unknown test: ${e.test.value}`);const s=n(r);return new he(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ve}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new he(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const n of e){const s=this.evaluate(n,t);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(r+=s.toString())}return new ae(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,n]=this.evaluateArguments(e.args,t);n.size>0&&r.push(new hi(n));const s=this.evaluate(e.callee,t);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof xe||e instanceof ae))throw new Error("Slice object must be an array or string");const n=this.evaluate(t.start,r),s=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(n instanceof we||n instanceof Ve))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof we||s instanceof Ve))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof we||a instanceof Ve))throw new Error("Slice step must be numeric or undefined");return e instanceof xe?new xe(Eg(e.value,n.value,s.value,a.value)):new ae(Eg(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let n;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);n=this.evaluate(e.property,t)}else n=new ae(e.property.value);let s;if(r instanceof yt){if(!(n instanceof ae))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof xe||r instanceof ae)if(n instanceof we)s=r.value.at(n.value),r instanceof ae&&(s=new ae(r.value.at(n.value)));else if(n instanceof ae)s=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof ae))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Cr?s:new Ve}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const n=e.assignee.value;t.setVariable(n,r)}else if(e.assignee.type==="TupleLiteral"){const n=e.assignee;if(!(r instanceof xe))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const s=r.value;if(s.length!==n.value.length)throw new Error(`Too ${n.value.length>s.length?"few":"many"} items to unpack in set`);for(let a=0;aw.setVariable(e.loopvar.value,_);else if(e.loopvar.type==="TupleLiteral"){const w=e.loopvar;if(_.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${_.type}`);const b=_;if(w.value.length!==b.value.length)throw new Error(`Too ${w.value.length>b.value.length?"few":"many"} items to unpack`);m=M=>{for(let E=0;E0?a[h-1]:new Ve],["nextitem",h{const s=new Wn(n);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let i=0;i{const h=new Wn(u);if(e.callerArgs)for(let p=0;pthis.evaluate(r,t)));case"TupleLiteral":return new Sg(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[n,s]of e.value){const a=this.evaluate(n,t);if(!(a instanceof ae))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new yt(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function nl(e){switch(typeof e){case"number":return Number.isInteger(e)?new we(e):new Ze(e);case"string":return new ae(e);case"boolean":return new he(e);case"undefined":return new Ve;case"object":return e===null?new Ye:Array.isArray(e)?new xe(e.map(nl)):new yt(new Map(Object.entries(e).map(([t,r])=>[t,nl(r)])));case"function":return new We((t,r)=>{const n=e(...t.map(s=>s.value))??null;return nl(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var ht=` `,eE="{%- ",tE=" -%}";function rE(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function nE(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return hr(e.body,0,r).replace(/\n$/,"")}function Tt(...e){return eE+e.join(" ")+tE}function hr(e,t,r){return e.map(n=>sE(n,t,r)).join(ht)}function sE(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return hr(e.body,t,r);case"If":return aE(e,t,r);case"For":return oE(e,t,r);case"Set":return iE(e,t,r);case"Macro":return lE(e,t,r);case"Break":return n+Tt("break");case"Continue":return n+Tt("continue");case"CallStatement":return cE(e,t,r);case"FilterStatement":return uE(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+ke(e)+" -}}"}}function aE(e,t,r){const n=r.repeat(t),s=[];let a=e;for(;a&&(s.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let i=n+Tt("if",ke(s[0].test))+ht+hr(s[0].body,t+1,r);for(let c=1;c0&&(i+=ht+n+Tt("else")+ht+hr(a.alternate,t+1,r)),i+=ht+n+Tt("endif"),i}function oE(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const i=e.iterable;s=`${ke(i.lhs)} if ${ke(i.test)}`}else s=ke(e.iterable);let a=n+Tt("for",ke(e.loopvar),"in",s)+ht+hr(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=ht+n+Tt("else")+ht+hr(e.defaultBlock,t+1,r)),a+=ht+n+Tt("endfor"),a}function iE(e,t,r){const n=r.repeat(t),s=ke(e.assignee),a=e.value?ke(e.value):"",i=n+Tt("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?i:i+ht+hr(e.body,t+1,r)+ht+n+Tt("endset")}function lE(e,t,r){const n=r.repeat(t),s=e.args.map(ke).join(", ");return n+Tt("macro",`${e.name.value}(${s})`)+ht+hr(e.body,t+1,r)+ht+n+Tt("endmacro")}function cE(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ke).join(", ")})`:"",a=ke(e.call);let i=n+Tt(`call${s}`,a)+ht;return i+=hr(e.body,t+1,r)+ht,i+=n+Tt("endcall"),i}function uE(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:ke(e.filter);let a=n+Tt("filter",s)+ht;return a+=hr(e.body,t+1,r)+ht,a+=n+Tt("endfilter"),a}function ke(e,t=-1){switch(e.type){case"SpreadExpression":return`*${ke(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const r=e,n=rE(r),s=ke(r.left,n),a=ke(r.right,n+1),i=`${s} ${r.operator.value} ${a}`;return n`${ke(n)}: ${ke(s)}`).join(", ")}}`;case"SliceExpression":{const r=e,n=r.start?ke(r.start):"",s=r.stop?ke(r.stop):"",a=r.step?`:${ke(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{const r=e,n=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}var dE=class{parsed;constructor(e){const t=v2(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=W2(t)}render(e){const t=new Wn;if(K2(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new Z2(t).run(this.parsed).value}format(e){return nE(this.parsed,e?.indent||" ")}},fE={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},_l=class zy{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=qt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=qt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=qt.createReadStream(t);this.body=new ReadableStream({start(s){n.on("data",a=>s.enqueue(a)),n.on("end",()=>s.close()),n.on("error",a=>s.error(a))},cancel(){n.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",fE[t]??"application/octet-stream")}clone(){let t=new zy(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await qt.promises.readFile(this.filePath)).buffer}async blob(){const t=await qt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await qt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Pl=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ve.IS_CRYPTO_AVAILABLE){const i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;const t=this._mt,r=(i,c)=>Math.imul(i,c)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),t[0]=19650218;for(let i=1;i<624;++i)t[i]=r(1812433253,t[i-1]^t[i-1]>>>30)+i>>>0;let s=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++s,++a)s>=624&&(t[0]=t[623],s=1),a>=n.length&&(a=0),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++s)s>=624&&(t[0]=t[623],s=1),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1566083941))-s>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const n=this.random()*2*Math.PI,s=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*s,this._gauss_next=Math.sin(n)*s}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let n=this._int32()>>>32-r;for(;n>t;)n=this._int32()>>>32-r;const s=e[t];e[t]=e[n],e[n]=s}}choices(e,t){return e[Gy(this._random_fn,t)]}};function Gy(e,t){let r=0;for(let s=0;sGy(Qh.random,e),pE=new Pl,Uy=class{constructor(e){this.path=e}async match(e){let t=xr.join(this.path,e),r=new _l(t);if(r.exists)return r}async put(e,t,r=void 0){const n=xr.join(this.path,e),s=ve.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=pE._int32().toString(36),i=n+`.tmp.${s}.${a}`;try{const c=t.headers.get("Content-Length"),u=parseInt(c??"0");let h=0;await qt.promises.mkdir(xr.dirname(n),{recursive:!0});const p=qt.createWriteStream(i),_=t.body.getReader();for(;;){const{done:m,value:w}=await _.read();if(m)break;await new Promise((M,E)=>{p.write(w,T=>{if(T){E(T);return}M()})}),h+=w.length;const b=u?h/u*100:0;r?.({progress:b,loaded:h,total:u})}await new Promise((m,w)=>{p.close(b=>b?w(b):m())}),await qt.promises.rename(i,n)}catch(c){try{await qt.promises.unlink(i)}catch{}throw c}}async delete(e){let t=xr.join(this.path,e);try{return await qt.promises.unlink(t),!0}catch{return!1}}},_E={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"},Fg=100,mE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Gi(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function Fs(e,t=null,r=null){let n;try{n=new URL(e)}catch{return!1}return!(t&&!t.includes(n.protocol)||r&&!r.includes(n.hostname))}function gE(e){return!(!mE.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function wE(e,t,r){if(!r)return null;const n=_E[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function yE(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&be.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),i=0;const c=e.body.getReader();async function u(){const{done:h,value:p}=await c.read();if(h)return;const _=i+p.length;if(_>s){s=_;const w=new Uint8Array(s);w.set(a),a=w}a.set(p,i),i=_;const m=i/s*100;return t({progress:m,loaded:i,total:s}),u()}return await u(),a}function Ig(e){return Fs(e,["blob:"])}function Lg(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var Vy="SHA-256",vE="experimental_transformers-hash-cache",Og=e=>({algorithm:Vy,value:e}),Ng=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(vE),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{const t=await this._getFileHash(e);if(t)try{const[r]=await navigator.crossOriginStorage.requestFileHandles([Og(t)]),n=await r.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,t)=>{const r=await this._getFileHash(e);if(r){const n=await t.blob();await this._storeBlobInCOS(n,r)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{const[r]=await navigator.crossOriginStorage.requestFileHandles([Og(t)],{create:!0}),n=await r.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{const r=[];for await(const a of t)r.push(a);const n=new Blob(r),s=await this._getBlobHash(n);await this._storeBlobInCOS(n,s);try{await(await this._getHashCache()).put(e,new Response(s))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{const t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();const n=await this._getLfsFileHash(e);return n?(await t.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const n=(await fetch(t).then(s=>s.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(Vy,t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}};async function Yh(e=null){let t=null;if(Se.useCustomCache){if(!Se.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!Se.customCache.match||!Se.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=Se.customCache}if(!t&&Se.experimental_useCrossOriginStorage&&Ng.isAvailable()&&(t=new Ng),!t&&Se.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(Se.cacheKey)}catch(r){be.warn("An error occurred while opening the browser cache:",r)}}if(!t&&Se.useFSCache){if(!ve.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new Uy(e??Se.cacheDir)}return t}async function bE(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}var ME=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;const t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,t),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}},xE=100,Tf=new ME(xE);function Wy(e,t){const r=Tf.get(e);if(r!==void 0)return r;const n=t().then(s=>s,s=>(Tf.delete(e),Promise.reject(s)));return Tf.put(e,n),n}async function TE(e){if(!Fs(e,["http:","https:"]))return null;const t=jy(e);return t.set("Range","bytes=0-0"),Se.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function Xh(e,t,r={}){const n=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return Wy(n,()=>EE(e,t,r))}async function EE(e,t,r){const n=await Yh(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:i,validModelId:c}=qy(e,t,r,n),u=await Hy(n,s,i);if(u!==void 0&&typeof u!="string"){const h=u.headers.get("content-length"),p=u.headers.get("content-type");return{exists:!0,size:h?parseInt(h,10):void 0,contentType:p||void 0,fromCache:!0}}if(Se.allowLocalModels&&!Fs(s,["http:","https:"]))try{const p=await ml(s);if(typeof p!="string"&&p.status!==404){const _=p.headers.get("content-length"),m=p.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(Se.allowRemoteModels&&!r.local_files_only&&c)try{const h=await TE(a);if(h&&h.status>=200&&h.status<300){let p;const _=h.headers.get("content-type");if(h.status===206){const m=h.headers.get("content-range");if(m){const w=m.match(/bytes \d+-\d+\/(\d+)/);w&&(p=parseInt(w[1],10))}}else if(h.status===200)try{await h.body?.cancel()}catch{}if(p===void 0){const m=h.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:_||void 0,fromCache:!1}}}catch(h){be.warn(`Unable to fetch file metadata for "${a}": ${h}`)}return{exists:!1,fromCache:!1}}async function ml(e){return Se.useFS&&!Fs(e,["http:","https:","blob:"])?new _l(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):Se.fetch(e,{headers:jy(e)})}function jy(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const n=!!Mf?.TESTING_REMOTELY,s=Se.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),Fs(e,["http:","https:"],["huggingface.co","hf.co"])){const i=Mf?.HF_TOKEN??Mf?.HF_ACCESS_TOKEN;i&&r.set("Authorization",`Bearer ${i}`)}}return r}function qy(e,t,r={},n=null){const s=r.revision??"main",a=Gi(e,t),i=gE(e),c=i?Gi(Se.localModelPath,a):a,u=Gi(Se.remoteHost,Se.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),h=n instanceof Uy?s==="main"?a:Gi(e,s,t):u;return{requestURL:a,localPath:c,remoteURL:u,proposedCacheKey:h,validModelId:i}}async function Hy(e,t,r){if(e)return await bE(e,t,r)}async function kE(e,t,r,n,s,a,i={}){if(await r.match(n)===void 0)if(a){if(typeof s!="string"){const c=new Headers(s.headers);c.set("content-length",a.byteLength.toString()),await r.put(n,new Response(a,{headers:c})).catch(u=>{be.warn(`Unable to add response to browser cache: ${u}.`)})}}else{const c=i.progress_callback?u=>Qn(i.progress_callback,{status:"progress",name:e,file:t,...u}):void 0;await r.put(n,s,c)}}async function CE(e,t,r=!0,n={},s=!1,a=null){const{requestURL:i,localPath:c,remoteURL:u,proposedCacheKey:h,validModelId:p}=qy(e,t,n,a);let _,m=!1,w;w=await Hy(a,c,h);const b=w!==void 0;if(b)_=h;else{if(Se.allowLocalModels)if(Fs(i,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`);if(!Se.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${i}.`)}else try{w=await ml(c),_=c}catch(C){be.warn(`Unable to load from local path "${c}": "${C}"`)}if(w===void 0||typeof w!="string"&&w.status===404){if(n.local_files_only||!Se.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${c}".`);return null}if(!p)throw Error(`Local file missing at "${c}" and download aborted due to invalid model ID "${e}".`);if(w=await ml(u),w.status!==200)return wE(w.status,u,r);_=h}m=a&&typeof Response<"u"&&w instanceof Response&&w.status===200}Qn(n.progress_callback,{status:"download",name:e,file:t});let M;if(!(ve.IS_NODE_ENV&&s)){let T;if(typeof w!="string")if(!n.progress_callback)T=new Uint8Array(await w.arrayBuffer());else if(b&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))T=new Uint8Array(await w.arrayBuffer()),Qn(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:T.length,total:T.length});else{let C;const P=w.headers.get("content-length");if(P)C=parseInt(P,10);else try{const A=await Xh(e,t,n);A.size&&(C=A.size)}catch{}T=await yE(w,A=>{Qn(n.progress_callback,{status:"progress",name:e,file:t,...A})},C)}M=T}if(m&&_&&typeof w!="string"&&await kE(e,t,a,_,w,M,n),ve.IS_NODE_ENV&&s&&n.progress_callback&&typeof w!="string"){const T=parseInt(w.headers.get("content-length"),10)||0;Qn(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:T,total:T})}if(Qn(n.progress_callback,{status:"done",name:e,file:t}),M){if(!ve.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return M}if(w instanceof _l)return w.filePath;const E=await a?.match(_);if(E instanceof _l)return E.filePath;if(E instanceof Response)return new Uint8Array(await E.arrayBuffer());if(typeof E=="string")return E;throw new Error("Unable to get model file path or buffer.")}var Ui=new Map;async function gl(e,t,r=!0,n={},s=!1){if(!Se.allowLocalModels){if(n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!Se.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Qn(n.progress_callback,{status:"initiate",name:e,file:t});const a=`${e}::${t}`;let i=Ui.get(a);if(!i){const c=await Yh(n?.cache_dir);i=CE(e,t,r,n,s,c).then(u=>(Ui.delete(a),u),u=>{throw Ui.delete(a),u}),Ui.set(a,i)}return await i}async function Jh(e,t,r=!0,n={}){const s=await gl(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function jr(e,t,r=!0,n={}){const s=await Jh(e,t,r,n);return s===null?{}:JSON.parse(s)}function AE(e,[t,r,n],[s,a],i="bilinear",c=!1){const u=a/n,h=s/r,p=new e.constructor(s*a*t),_=r*n,m=s*a;for(let w=0;w=0;--c)s[c]=u,n[c]=t[r[c]],u*=n[c];const a=r.map((c,u)=>s[r.indexOf(u)]),i=new e.constructor(e.length);for(let c=0;c=0;--h)u+=p%t[h]*a[h],p=Math.floor(p/t[h]);i[u]=e[c]}return[i,n]}function Is(e){const t=pt(e)[0],r=e.map(a=>Math.exp(a-t)),n=r.reduce((a,i)=>a+i,0);return r.map(a=>a/n)}function PE(e){const t=pt(e)[0];let r=0;for(let a=0;aa-t-n)}function lh(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;nt&&(t=e[n],r=n);return[t,r]}function Qy(e){return e>0&&(e&e-1)===0}var Yy=class{constructor(e){if(this.size=e|0,this.size<=1||!Qy(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;rr;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let n=0;n>>1],r[n+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r>=2;a>=2;a>>=2){i=n/a<<1;const _=i>>>2;for(c=0;c>>1,a>>>1)}else for(c=0,u=0;c>>1,a>>>1,r)}const p=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;const m=i>>>1,w=m>>>1,b=w>>>1;for(c=0;c>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,t,r,n,s){const a=e[n],i=e[n+s];t[r]=a+i,t[r+1]=0,t[r+2]=a-i,t[r+3]=0}_singleRealTransform4(e,t,r,n,s,a){const i=s*2,c=s*3,u=e[n],h=e[n+s],p=e[n+i],_=e[n+c],m=u+p,w=u-p,b=h+_,M=a*(h-_);t[r]=m+b,t[r+1]=0,t[r+2]=w,t[r+3]=-M,t[r+4]=m-b,t[r+5]=0,t[r+6]=w,t[r+7]=M}},FE=class{constructor(e){const t=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=t;const s=new Float64Array(r),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);const i=-2*Math.PI/e,c=Math.cos(i),u=Math.sin(i);for(let h=0;h>1;++h){const p=(h+1-e)**2/2,_=Math.sqrt(c**2+u**2)**p,m=p*Math.atan2(u,c),w=2*h;s[w]=_*Math.cos(m),s[w+1]=_*Math.sin(m),a[w]=s[w],a[w+1]=-s[w+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new Yy(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const n=this._buffer1,s=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,c=this._chirpBuffer,u=this._slicedChirpBuffer,h=this._a;if(r)for(let p=0;p>1,w=t[m];n[p]=w*u[p],n[_]=w*u[_]}else for(let p=0;p=e.length&&(u=2*(e.length-1)-u),n[i++]=e[u]}n.sort(),r[a]=n[s]}return r}function Vi(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function OE(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function NE(e){const t=e.length,r=e[0].length,n=[t+1,r+1],s=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));s[0][0]=0;const a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let p=1;p0||c>0;)switch(u.push(i-1),h.push(c-1),a[i][c]){case 0:--i,--c;break;case 1:--i;break;case 2:--c;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${c}]. Please file a bug report.`)}return u.reverse(),h.reverse(),[u,h]}var BE=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),i=new Uint32Array(a),c=new Float32Array(a);for(let u=0;u>10;let m=u&1023;if(_===31)h=p|2139095040|m<<13;else if(_===0)if(m===0)h=p;else{let w=113;for(;(m&1024)===0;)m<<=1,--w;m&=-1025,h=p|w<<23|m<<13}else h=p|_+112<<23|m<<13;i[0]=h,e[u]=c[0]}}const r=t.length,n=e,s=new Float32Array(r);for(let a=0;a$E});var $E={};async function Jy(e){const t=e.split("/").pop();let r;try{if(r=await Yh(),r){const s=await r.match(e);if(s)return s}}catch(s){be.warn(`Failed to load ${t} from cache:`,s)}const n=await Se.fetch(e);if(!n.ok)throw new Error(`Failed to fetch ${t}: ${n.status} ${n.statusText}`);if(r)try{await r.put(e,n.clone())}catch(s){be.warn(`Failed to cache ${t}:`,s)}return n}async function DE(e){const t=await Jy(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return be.warn("Failed to read WASM binary:",r),null}}async function RE(e){if(ve.IS_SERVICE_WORKER_ENV||ve.IS_CHROME_AVAILABLE)return e;const t=await Jy(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return be.warn("Failed to read WASM factory:",r),null}}var zE=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function Ky(e){return e<=dr.DEBUG?0:e<=dr.INFO?2:e<=dr.WARNING||e<=dr.ERROR?3:4}var GE={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},er=[],ch,xs,Bg=Symbol.for("onnxruntime");if(Bg in globalThis)xs=globalThis[Bg];else if(ve.IS_NODE_ENV){switch(xs=Xy,process.platform){case"win32":er.push("dml");break;case"linux":process.arch==="x64"&&er.push("cuda");break;case"darwin":er.push("coreml");break}er.push("webgpu"),er.push("cpu"),ch=["cpu"]}else xs=F1,ve.IS_WEBNN_AVAILABLE&&er.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ve.IS_WEBGPU_AVAILABLE&&er.push("webgpu"),er.push("wasm"),ch=["wasm"];var UE=xs.InferenceSession;function VE(e=null){if(!e)return ch;switch(e){case"auto":return er;case"gpu":return er.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(er.includes(e))return[zE[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${er.join(", ")}.`)}var $g=Promise.resolve(),ds=null;async function WE(){if(ds)return ds;if(!(Se.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs)){if(ve.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return ds=Promise.resolve(),ds}return ds=(async()=>{const t=ft.wasm.wasmPaths;let r=!1;await Promise.all([t.wasm&&!Ig(t.wasm)?(async()=>{try{const n=await DE(Lg(t.wasm));n&&(ft.wasm.wasmBinary=n,r=!0)}catch(n){be.warn("Failed to pre-load WASM binary:",n)}})():Promise.resolve(),t.mjs&&!Ig(t.mjs)?(async()=>{try{const n=await RE(Lg(t.mjs));n&&(ft.wasm.wasmPaths.mjs=n)}catch(n){be.warn("Failed to pre-load WASM factory:",n)}})():Promise.resolve()]),r||(ft.wasm.wasmPaths.mjs=t.mjs)})(),ds}async function Zy(e,t,r){await WE();const n=Ky(Se.logLevel??dr.WARNING),s=()=>UE.create(e,{logSeverityLevel:n,...t}),a=await(ve.IS_WEB_ENV?$g=$g.then(s):s());return a.config=r,a}var Dg=Promise.resolve();async function ev(e,t){const r=()=>e.run(t);return ve.IS_WEB_ENV?Dg=Dg.then(r):r()}function tv(e){return e instanceof xs.Tensor}var ft=xs?.env;function Kh(){return ft?.wasm?.proxy}if(ft){let e=function(t){const r=Ky(t);ft.logLevel=GE[r]};if(ft.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`;ft.wasm.wasmPaths=ve.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}ft.wasm.proxy=!1}ft.webgpu&&(ft.webgpu.powerPreference="high-performance"),e(Se.logLevel??dr.WARNING),Se.backends.onnx={...ft,setLogLevel:e}}var Kr=async(e,t,r)=>{const n=await Zy(new Uint8Array(e),t);return(async s=>{const a=Kh(),i=Object.fromEntries(Object.entries(s).map(([u,h])=>[u,(a?h.clone():h).ort_tensor])),c=await ev(n,i);return Array.isArray(r)?r.map(u=>new K(c[u])):new K(c[r])})},Ts=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Kr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Kr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Kr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Kr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Kr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Kr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Kr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Kr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}},jE=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),Ef=ve.IS_NODE_ENV?"cpu":"wasm";function rv(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Ef}).`),Ef):Ef}var qE=(function(){let e;return async function(){if(e===void 0)if(!ve.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),Rg=st.fp32,zg=Object.freeze({[jE.wasm]:st.q8}),uh=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function nv(e,t,r,{configDtype:n=null,warn:s}={}){let a,i=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,i=!0):a=e;let c;if(a===st.auto){if(n){const u=typeof n=="string"?n:n?.[t];if(u&&u!==st.auto&&st.hasOwnProperty(u))return u}c=zg[r]??Rg}else a&&st.hasOwnProperty(a)?c=a:c=zg[r]??Rg;return i&&s&&s(`dtype not specified for "${t}". Using the default dtype (${c}) for this device (${r}).`),c}var wi=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),K=class Ke{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...t){return tv(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new U1(t[0],t[1],t[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let s=Number(n);if(Number.isInteger(s))return r._getitem(s)}return r[n]},set:(r,n,s)=>r[n]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const n=r.reduce((s,a)=>s*a);for(let s=0;s0){const s=n.reduce((a,i)=>a*i);return this._subarray(t,s,n)}else return new Ke(this.type,[this.data[t]],n)}indexOf(t){const r=this.data;for(let n=0;nw)throw new Error(`Invalid slice: ${_}`);const b=[Math.max(m,0),Math.min(w,this.dims[p])];n.push(b),r.push(b[1]-b[0])}else throw new Error(`Invalid slice: ${_}`)}const s=n.map(([p,_])=>_-p),a=s.reduce((p,_)=>p*_),i=this.data,c=new i.constructor(a),u=this.stride();let h=!0;for(let p=1;p=0;--m){const b=s[m];_+=(w%b+n[m][0])*u[m],w=Math.floor(w/b)}c[p]=i[_]}return new Ke(this.type,c,r)}permute(...t){return QE(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,n=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const s=this.data,a=s instanceof BigInt64Array||s instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let i,c;if(a?(i=(_,m)=>_+m,c=0n):(i=(_,m)=>_+m**t,c=0),r===null){let _=s.reduce(i,c);return t!==1&&(_=_**(1/t)),new Ke(this.type,[_],[])}const[u,h,p]=_i(i,this,r,n);if(t!==1)for(let _=0;_=0;--u){const _=this.dims[u];if(u!==r){const m=h%_;c+=m*p,p*=this.dims[u]}h=Math.floor(h/_)}s[i]/=a[c]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return kf(this.dims)}squeeze(t=null){return new Ke(this.type,this.data,Gg(this.dims,t))}squeeze_(t=null){return this.dims=Gg(this.dims,t),this}unsqueeze(t){return new Ke(this.type,this.data,Ug(this.dims,t))}unsqueeze_(t){return this.dims=Ug(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((i,c)=>i*c,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;sc!==r?a*i:a,1);t[r]=n.length/s}return new Ke(this.type,n,t)}neg_(){const t=this.data;for(let r=0;rt?1:0;return new Ke("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;sMath.min(i,c),this,t,r,1/0);return new Ke(n,s,a)}max(t=null,r=!1){if(t===null){const i=pt(this.data)[0];return new Ke(this.type,[i],[])}const[n,s,a]=_i((i,c)=>Math.max(i,c),this,t,r,-1/0);return new Ke(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=lh(this.data)[1];return new Ke("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=pt(this.data)[1];return new Ke("int64",[BigInt(n)],[])}repeat(...t){if(t.lengthp===1)){if(t.length===this.dims.length)return this.clone();const p=t.length-this.dims.length,_=Array(p).fill(1).concat(this.dims);return new Ke(this.type,this.data.slice(),_)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((p,_)=>p*t[_]),a=s.reduce((p,_)=>p*_,1),i=this.data,c=new i.constructor(a),u=kf(n),h=kf(s);for(let p=0;pBigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Ke(t,BE(this.data),this.dims);return new Ke(t,wi[t].from(this.data,r),this.dims)}};function HE(e,t){const r=e.length,n=t.reduce((a,i)=>a*i);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let a=t.length-1;a>=0;a--)s=s.reduce((i,c)=>{let u=i[i.length-1];return u.lengthnew K("int64",e,[e.length]);async function ov(e,t,r,n,s){return await(await Ts.slice)({x:e,s:Wi(t),e:Wi(r),a:Wi(n),t:Wi(new Array(n.length).fill(1))})}function Gg(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,n)=>r!==1||!t.includes(n))),e}function Ug(e,t){return t=Mr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Mr(e,t,r=null,n=!0){if(e<-t||e>=t){if(n)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function je(e,t=0){t=Mr(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((i,c)=>i+c.dims[t],0);const n=r.reduce((i,c)=>i*c,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let i=0;for(const c of e){const u=c.data;s.set(u,i),i+=u.length}}else{let i=0;for(let c=0;c=0;--m){const M=h[m];let E=w%M;m===t&&(E+=i),_+=E*b,b*=r[m],w=Math.floor(w/M)}s[_]=u[p]}i+=h[t]}}return new K(a,s,r)}function Gr(e,t=0){return je(e.map(r=>r.unsqueeze(t)),t)}function _i(e,t,r,n=!1,s=null){const a=t.data,i=t.dims;r=Mr(r,i.length);const c=i.slice();c[r]=1;const u=new a.constructor(a.length/i[r]);s!==null&&u.fill(s);for(let h=0;h=0;--_){const b=i[_];if(_!==r){const M=m%b;p+=M*w,w*=c[_]}m=Math.floor(m/b)}u[p]=e(u[p],a[h],h,p)}return n||c.splice(r,1),[t.type,u,c]}function XE(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const w=s.reduce((T,C)=>T+C,0)/s.length,b=Math.sqrt(s.reduce((T,C)=>T+(C-w)**2,0)/(s.length-r)),M=new K(e.type,[w],[]);return[new K(e.type,[b],[]),M]}t=Mr(t,a.length);const i=Zh(e,t,n),c=i.data,[u,h,p]=_i((m,w,b,M)=>m+(w-c[M])**2,e,t,n);for(let m=0;mh+p,0);return new K(e.type,[u/s.length],[])}t=Mr(t,n.length);const[a,i,c]=_i((u,h)=>u+h,e,t,r);if(n[t]!==1)for(let u=0;u=0;--r)t[r]=n,n*=e[r];return t}function ep(e,t,r,n){const s=e.reduce((a,i)=>a*i,1);return new K(r,new n(s).fill(t),e)}function At(e,t){let r,n;if(typeof t=="number")r="float32",n=Float32Array;else if(typeof t=="bigint")r="int64",n=BigInt64Array;else if(typeof t=="boolean")r="bool",n=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return ep(e,t,r,n)}function dh(e,t){return At(e.dims,t)}function Ot(e){return ep(e,1n,"int64",BigInt64Array)}function iv(e){return Ot(e.dims)}function lv(e){return ep(e,0n,"int64",BigInt64Array)}function cv(e){return lv(e.dims)}function JE(e){const t=e.reduce((r,n)=>r*n,1);return new K("float32",Float32Array.from({length:t},()=>Qh.gauss()),e)}async function KE(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await Xh(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function uv(e,t){const r=await KE(e);return await Promise.all(r.map(n=>jr(e,n,!0,t)))}function tp(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var ZE=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ek(e,t,r,n){for(const s of Object.keys(e)){const a=t-e[s].length,i=r(s),c=new Array(a).fill(i);e[s]=n==="right"?Tr(e[s],c):Tr(c,e[s])}}function tk(e,t){for(const r of Object.keys(e))e[r].length=t}function Gn(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const n=e[r];if(n)if(typeof n=="object"){if(n.__type==="AddedToken")return n.content;throw Error(`Unknown token: ${n}`)}else return n}return null}function rk(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var pe=class extends Yt{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new m2(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Gn(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Gn(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Gn(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Gn(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Gn(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Gn(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const n=Object.create(null);for(const{name:s,template:a}of this.chat_template){if(typeof s!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[s]=a}this.chat_template=n}this._compiled_template_cache=new Map;const r=rk(this._tokenizer);this.all_special_ids=r.map(n=>n.id),this.all_special_tokens=r.map(n=>n.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){const i=await uv(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(t=>this._tokenizer.token_to_id(t))}_call(e,t={}){const{text_pair:r=null,add_special_tokens:n=!0,padding:s=!1,return_token_type_ids:a=null}=t;let{truncation:i=null,max_length:c=null}=t;const u=t.return_tensor??!0,h=Array.isArray(e);let p;if(h){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");p=e.map((m,w)=>this._encode_plus(m,{text_pair:r[w],add_special_tokens:n,return_token_type_ids:a}))}else p=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");p=[this._encode_plus(e,{text_pair:r,add_special_tokens:n,return_token_type_ids:a})]}if(c===null?c=this.model_max_length:i===null&&(s===!0?(be.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),c=this.model_max_length):s===!1&&(be.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),s===!0&&(c=Math.min(pt(p.map(m=>m.input_ids.length))[0],c??1/0)),c=Math.min(c,this.model_max_length??1/0),s||i)for(let m=0;mc?i&&tk(p[m],c):s&&ek(p[m],c,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));const _={};if(u){if(!(s&&i)&&p.some(w=>{for(const b of Object.keys(w))if(w[b].length!==p[0][b]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const m=[p.length,p[0].input_ids.length];for(const w of Object.keys(p[0]))_[w]=new K("int64",BigInt64Array.from(p.flatMap(b=>b[w]).map(BigInt)),m)}else{for(const m of Object.keys(p[0]))_[m]=p.map(w=>w[m]);if(!h)for(const m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{ids:s,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:s,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n}).ids}batch_decode(e,t={}){return e instanceof K&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof K&&(e=tp(e)),!Array.isArray(e)||e.length===0||!sx(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,t={}){let{tools:r=null,documents:n=null,chat_template:s=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:c=!1,truncation:u=!1,max_length:h=null,return_tensor:p=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=t;if(s=this.get_chat_template({chat_template:s,tools:r}),typeof s!="string")throw Error(`chat_template must be a string, but got ${typeof s}`);let b=this._compiled_template_cache.get(s);b===void 0&&(b=new dE(s),this._compiled_template_cache.set(s,b));const M=Object.create(null);for(const T of ZE){const C=Gn(this.config,T);C&&(M[T]=C)}const E=b.render({messages:e,add_generation_prompt:a,tools:r,documents:n,...M,...w});if(i){const T=this._call(E,{add_special_tokens:!1,padding:c,truncation:u,max_length:h,return_tensor:p,...m});return _?T:T.input_ids}return E}};function rp(e,t,r,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const s=n.src_lang,a=n.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(s!==void 0){if(!e.language_codes.includes(s))throw new Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const i of e._tokenizer.post_processor.config.single)if("SpecialToken"in i&&e.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=e.lang_to_token(s);break}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var dv={};Ss(dv,{AlbertTokenizer:()=>nk,AutoTokenizer:()=>Oe,BartTokenizer:()=>sk,BertTokenizer:()=>ak,BlenderbotSmallTokenizer:()=>ok,BlenderbotTokenizer:()=>ik,BloomTokenizer:()=>lk,CLIPTokenizer:()=>uk,CamembertTokenizer:()=>ck,CodeGenTokenizer:()=>fk,CodeLlamaTokenizer:()=>dk,CohereAsrTokenizer:()=>pk,CohereTokenizer:()=>hk,ConvBertTokenizer:()=>_k,DebertaTokenizer:()=>gk,DebertaV2Tokenizer:()=>mk,DistilBertTokenizer:()=>wk,ElectraTokenizer:()=>yk,EsmTokenizer:()=>vk,FalconTokenizer:()=>bk,GPT2Tokenizer:()=>Tk,GPTNeoXTokenizer:()=>xk,GemmaTokenizer:()=>Mk,HerbertTokenizer:()=>Ek,LlamaTokenizer:()=>kk,M2M100Tokenizer:()=>Ck,MBart50Tokenizer:()=>Sk,MBartTokenizer:()=>fv,MPNetTokenizer:()=>Ik,MarianTokenizer:()=>Ak,MgpstrTokenizer:()=>Pk,MobileBertTokenizer:()=>Fk,NllbTokenizer:()=>Lk,NougatTokenizer:()=>Ok,PreTrainedTokenizer:()=>pe,Qwen2Tokenizer:()=>Nk,RoFormerTokenizer:()=>$k,RobertaTokenizer:()=>Bk,SiglipTokenizer:()=>Dk,SpeechT5Tokenizer:()=>Rk,SqueezeBertTokenizer:()=>zk,T5Tokenizer:()=>Gk,TokenizersBackend:()=>pe,VitsTokenizer:()=>Vk,Wav2Vec2CTCTokenizer:()=>Wk,WhisperTokenizer:()=>Yk,XLMRobertaTokenizer:()=>Xk,XLMTokenizer:()=>Jk});var nk=class extends pe{return_token_type_ids=!0},sk=class extends pe{},ak=class extends pe{return_token_type_ids=!0},ok=class extends pe{},ik=class extends pe{},lk=class extends pe{},ck=class extends pe{},uk=class extends pe{},dk=class extends pe{},fk=class extends pe{},hk=class extends pe{},pk=class extends pe{},_k=class extends pe{return_token_type_ids=!0},mk=class extends pe{return_token_type_ids=!0},gk=class extends pe{return_token_type_ids=!0},wk=class extends pe{},yk=class extends pe{return_token_type_ids=!0},vk=class extends pe{},bk=class extends pe{},Mk=class extends pe{},xk=class extends pe{},Tk=class extends pe{},Ek=class extends pe{return_token_type_ids=!0},kk=class extends pe{padding_side="left"},Ck=class extends pe{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return rp(this,e,t,r)}},Ak=class extends pe{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),be.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[n,s]=r;return this.supported_language_codes.includes(n)||be.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Tr([n],super._encode_text(s))}}},fv=class extends pe{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return rp(this,e,t,r)}},Sk=class extends fv{},Pk=class extends pe{},Fk=class extends pe{return_token_type_ids=!0},Ik=class extends pe{},Lk=class extends pe{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return rp(this,e,t,r)}},Ok=class extends pe{},Nk=class extends pe{},Bk=class extends pe{},$k=class extends pe{return_token_type_ids=!0},Dk=class extends pe{},Rk=class extends pe{},zk=class extends pe{return_token_type_ids=!0},Gk=class extends pe{},Uk=class extends _r{decode_chain(e){let t="";for(let r=1;r[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function qk(e){e=e.toLowerCase();let t=jk.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),sl.has(e))t=e;else{const s=e.length===2?sl.keys():sl.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var Hk="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Vg=new RegExp(`^[${Hk}]+$`,"gu"),Qk=.1,Yk=class extends pe{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null;const i=t==="word";function c(){return{language:a,timestamp:[null,null],text:""}}const u=[];let h=c(),p=0;const _=this.timestamp_begin,w=_+1500;let b=[],M=[],E=!1,T=null;const C=new Set(this.all_special_ids);for(const F of e){const G=F.tokens,v=i?F.token_timestamps:null;let j=null,U=_;if("stride"in F){const[H,I,S]=F.stride;if(p-=I,T=H-S,I&&(U=I/n+_),S)for(let D=G.length-1;D>=0;--D){const Y=Number(G[D]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&I<=w){const S=(I-_)*n+p,D=Vi(S,2);if(j!==null&&I>=j)E=!0;else if(E||b.length>0&&I0&&h.timestamp[1]!==null))for(const $ of h.words)$.timestamp[1]>h.timestamp[1]&&h.timestamp[1]>=$.timestamp[0]&&($.timestamp[1]=h.timestamp[1]);u.push(h),b=[],q=[],M=[],ne=[],h=c()}}else if(q.push(I),i){let S=Vi(v[H]+p,2),D;if(H+10?(b.push(q),i&&M.push(ne)):b.every(H=>H.length===0)&&(h=c(),b=[],q=[],M=[],ne=[])}if(b.length>0){if(s&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[F,G]=this.findLongestCommonSequence(b,M),v=this.decode(F);h.text=v,i&&(h.words=this.collateWordTimestamps(F,G,a)),u.push(h)}let P=Object.create(null);const A=u.map(F=>F.text).join("");if(t||r){for(let F=0;F0;let i=a?[]:null,c=a?t[0]:null;for(let u=1;uI===U[S]&&c[A+S][0]-Qk<=t[u][v+S][0]).length:q=G.filter((I,S)=>I===U[S]).length;const ne=P/1e4,H=q/P+ne;q>1&&H>p&&(p=H,_=[A,F,v,j])}const[w,b,M,E]=_,T=Math.floor((b+w)/2);let C=Math.floor((E+M)/2);if(a&&p===0&&n>0){const P=c[n-1][0],A=t[u].findIndex(F=>F[0]>=P);C=A===-1?h.length:A}s.push(...r.slice(0,T)),r=h.slice(C),n=r.length,a&&(i.push(...c.slice(0,T)),c=t[u].slice(C))}return s.push(...r),a?(i.push(...c),[s,i]):[s,[]]}collateWordTimestamps(e,t,r){const[n,s,a]=this.combineTokensIntoWords(e,r),i=[];for(let c=0;c=n){const i=((a-n)*r).toFixed(2);s.push(`<|${i}|>`),s.push([])}else s[s.length-1].push(a);return s=s.map(a=>typeof a=="string"?a:super.decode(a,t)),s.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",n=[],s=[],a=[];let i=[],c=[],u=0;for(let h=0;h=this._tokenizer.token_to_id("<|endoftext|>"),m=u.startsWith(" "),w=u.trim(),b=Vg.test(w);if(_||m||b||s.length===0)s.push(u),a.push(h),i.push(p);else{const M=s.length-1;s[M]+=u,a[M].push(...h),i[M].push(...p)}}return[s,a,i]}mergePunctuations(e,t,r,n,s){const a=structuredClone(e),i=structuredClone(t),c=structuredClone(r);let u=a.length-2,h=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&n.includes(a[u].trim())?(a[h]=a[u]+a[h],i[h]=Tr(i[u],i[h]),c[h]=Tr(c[u],c[h]),a[u]="",i[u]=[],c[u]=[]):h=u,--u;for(u=0,h=1;hp),i.filter(p=>p.length>0),c.filter(p=>p.length>0)]}},Xk=class extends pe{},Jk=class extends pe{return_token_type_ids=!0;constructor(e,t){super(e,t),be.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Oe=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){const[i,c]=await uv(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),u=c.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let h=dv[u];return h||(be.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),h=pe),new h(i,c)}},Fl="https://github.com/huggingface/transformers.js/issues/new/choose",np="preprocessor_config.json",pv=np,_v="processor_config.json",mv="chat_template.jinja",De=class extends Yt{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,n,s]=await Promise.all([this.uses_processor_config?jr(e,_v,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const i=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?Jh(e,mv,!0,t):null]);return new this(r,n,s)}},Kk={};Ss(Kk,{ChatterboxProcessor:()=>TC,CohereAsrProcessor:()=>kC,Florence2Processor:()=>CA,Gemma3Processor:()=>AA,Gemma3nProcessor:()=>SA,Gemma4Processor:()=>PA,Glm46VProcessor:()=>FA,GraniteSpeechProcessor:()=>IA,GroundingDinoProcessor:()=>OA,Idefics3Processor:()=>Xg,JinaCLIPProcessor:()=>RA,Lfm2VlProcessor:()=>zA,LlavaProcessor:()=>GA,MgpstrProcessor:()=>UA,MoonshineProcessor:()=>VA,OwlViTProcessor:()=>WA,PaliGemmaProcessor:()=>qA,Phi3VProcessor:()=>QA,PixtralProcessor:()=>YA,Processor:()=>De,PyAnnoteProcessor:()=>XA,Qwen2VLProcessor:()=>lp,Qwen2_5_VLProcessor:()=>Qv,Qwen3VLProcessor:()=>JA,Sam2Processor:()=>Xv,Sam2VideoProcessor:()=>KA,SamProcessor:()=>Yv,SmolVLMProcessor:()=>Xg,SpeechT5Processor:()=>ZA,UltravoxProcessor:()=>eS,VLChatProcessor:()=>DA,VoxtralProcessor:()=>sS,VoxtralRealtimeProcessor:()=>iS,Wav2Vec2Processor:()=>lS,Wav2Vec2ProcessorWithLM:()=>cS,WhisperProcessor:()=>uS});var St=class extends Yt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await jr(e,np,!0,t);return new this(r)}};function Et(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var gv={};Ss(gv,{ASTFeatureExtractor:()=>uC,ChatterboxFeatureExtractor:()=>dC,ClapFeatureExtractor:()=>fC,CohereAsrFeatureExtractor:()=>pC,DacFeatureExtractor:()=>Mv,EncodecFeatureExtractor:()=>vv,FeatureExtractor:()=>St,Gemma3nAudioFeatureExtractor:()=>xv,Gemma4AudioFeatureExtractor:()=>Tv,GraniteSpeechFeatureExtractor:()=>_C,MoonshineFeatureExtractor:()=>mC,ParakeetFeatureExtractor:()=>bv,PyAnnoteFeatureExtractor:()=>Ev,SeamlessM4TFeatureExtractor:()=>gC,SnacFeatureExtractor:()=>wC,SpeechT5FeatureExtractor:()=>yC,VoxtralRealtimeFeatureExtractor:()=>MC,Wav2Vec2FeatureExtractor:()=>vC,WeSpeakerFeatureExtractor:()=>bC,WhisperFeatureExtractor:()=>xC});var Zk=()=>{},eC=Zk;async function tC(e,t){if(ve.IS_BROWSER_ENV){if(ve.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(r)}else if(ve.IS_FS_AVAILABLE)t.stream(),qt.createWriteStream(e),await eC();else throw new Error("Unable to save because filesystem is disabled in this environment.")}function wv(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,n=2*Math.PI/(e-1),s=new Float64Array(e);for(let a=0;a2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,n=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*n:3*e/200};function Cf(e,t="htk"){const r=nC[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}var sC={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,n=Math.log(6.4)/27)=>e>=r?t*Math.exp(n*(e-r)):200*e/3};function aC(e,t="htk"){const r=sC[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}function oC(e,t){const r=Float64Array.from({length:t.length-1},(i,c)=>t[c+1]-t[c]),n=Array.from({length:e.length},()=>new Array(t.length));for(let i=0;inew Array(e.length));for(let i=0;ie+n*a)}function kr(e,t,r,n,s,a=null,i="htk",c=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>n)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${n}`);const u=Cf(r,i),h=Cf(n,i),p=jg(u,h,t+2);let _=aC(p,i),m;if(c){const b=s/((e-1)*2);m=Cf(Float64Array.from({length:e},(M,E)=>E*b),i),_=p}else m=jg(0,Math.floor(s/2),e);const w=oC(m,_);if(a!==null&&a==="slaney")for(let b=0;bs)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(U!==r)throw new Error(`Length of the window (${U}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&_!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(i){const Q=Math.floor(r/2);switch(c){case"reflect":{e=iC(e,Q,Q);break}case"constant":{const _e=new e.constructor(e.length+2*Q);_e.set(e,Q),e=_e;break}case"semicausal":{const _e=new e.constructor(e.length+Q);_e.set(e,Q),e=_e;break}default:throw new Error(`pad_mode="${c}" not implemented yet.`)}}let q=Math.floor(1+Math.floor((e.length-r)/n));P!==null&&qq?F&&(I=A):I=H=A);const S=new IE(s),D=new Float64Array(s),Y=new Float64Array(S.outputBufferSize),se=new Float32Array(ne*I);for(let Q=0;Q=1;--de)D[de]-=h*D[de-1];D[0]*=1-h}for(let de=0;deMath.pow(h,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(i=i.subarray(0,e)),n===null||e===n)return i;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);const c=new Float64Array(n),u=s?Math.floor((n-e)/2):0;return c.set(i,u),c}var uC=class extends St{constructor(e){super(e);const t=this.config.sampling_rate,r=kr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=qr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Ar(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){Et(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,n=t.data;for(let s=0;s0)if(r==="rand_trunc"){const i=Math.floor(Qh.random()*(a+1));e=e.subarray(i,i+t),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let i=new Float64Array(t);if(i.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=t*e[n-1];return await Ar(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Et(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,r*t.dims[1]);const[s,a]=t.dims,i=new Float64Array(a),c=new Float64Array(a);for(let p=0;p1?r-1:1;for(let p=0;p=h){c.push(e.slice(u,h));break}const p=Math.max(u,u+a-i),_=Math.min(u+a,h);let m;_<=p?m=u+a:m=this._find_split_point_energy(e,p,_,n),m=Math.max(u+1,Math.min(m,h)),c.push(e.slice(u,m)),u=m}return c}_find_split_point_energy(e,t,r,n){const s=r-t;if(s<=n)return Math.floor((t+r)/2);let a=1/0,i=t;const c=s-n;for(let u=0;u<=c;u+=n){let h=0;for(let p=0;pt&&(e=e.slice(0,t)),n&&e.length%s!==0){const c=s-e.length%s,u=new Float64Array(e.length+c);u.set(e),this.config.padding_value!==0&&u.fill(this.config.padding_value,e.length),e=u}const a=await this._extract_fbank_features(e,this.config.max_length),i=At([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}},Tv=class extends xv{async _extract_fbank_features(e,t){const{frame_length:r,hop_length:n,fft_length:s}=this.config,a=Math.floor(r/2),i=Math.floor((e.length+a-(r+1))/n)+1;return Ar(e,this.window,r,n,{fft_length:s,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,t={}){Et(e,"Gemma4AudioFeatureExtractor");const r=e.length,n=await super._call(e,t),{input_features:s}=n,[,a,i]=s.dims,{frame_length:c,hop_length:u}=this.config,h=Math.floor(c/2),p=c+1,_=new Uint8Array(r+h+(t.pad_to_multiple_of??128));_.fill(1,h,h+r);const m=new Uint8Array(a);for(let b=0;b({id:c,start:u*r,end:h*r,confidence:p/(h-u)})))}return n}},gC=class extends St{constructor(e){super(e);const t=this.config.sampling_rate,r=kr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=qr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Ar(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:s=!0}={}){Et(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[w,b]=a.dims,M=a.data;for(let E=0;E0){const T=new Float32Array(b*(w+E));T.set(M),T.fill(this.config.padding_value,M.length);const C=w+E;a=new K(a.type,T,[C,b]),s&&(i=new K("int64",new BigInt64Array(C),[1,C]),i.data.fill(1n,0,w))}}const[c,u]=a.dims,h=this.config.stride;if(c%h!==0)throw new Error(`The number of frames (${c}) must be a multiple of the stride (${h}).`);const _=a.view(1,Math.floor(c/h),u*h),m={input_features:_};if(s){const w=_.dims[1],b=new BigInt64Array(w);if(i){const M=i.data;for(let E=1,T=0;Es+a,0)/e.length,n=e.reduce((s,a)=>s+(a-r)**2,0)/e.length;return e.map(s=>(s-r)/Math.sqrt(n+1e-7))}async _call(e){Et(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new K("float32",t,r),attention_mask:new K("int64",new BigInt64Array(t.length).fill(1n),r)}}},bC=class extends St{constructor(e){super(e);const t=this.config.sampling_rate,r=kr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=qr(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),Ar(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Et(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,n=t.data,[s,a,i]=t.dims;for(let c=0;cn?(e.length>this.config.n_samples&&be.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},rr=class{static async from_pretrained(e,t={}){const r=await jr(e,np,!0,t),n=r.feature_extractor_type,s=gv[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Fl}.`);return new s(r)}},TC=class extends De{static tokenizer_class=Oe;static feature_extractor_class=rr;async _call(e,t=null){const r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},EC=new Set(["ja","zh"]),kC=class extends De{static tokenizer_class=Oe;static feature_extractor_class=rr;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){const t=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){const r=e.filter(a=>a&&a.trim());if(r.length===0)return"";const n=EC.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}},fh={},jn,kv,nn;if(ve.IS_WEB_ENV)jn=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},nn=self.createImageBitmap,kv=self.ImageData;else if(fh)nn=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new yi(new Uint8ClampedArray(n),s.width,s.height,s.channels);return r!==void 0&&r!==s.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var CC={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},AC=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),yi=class vr{constructor(t,r,n,s){this.data=t,this.width=r,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(t){if(t instanceof vr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!ve.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new vr(n,t.width,t.height,4)}static async fromURL(t){const r=await ml(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const n=await r.blob();return this.fromBlob(n)}static async fromBlob(t){if(ve.IS_WEB_ENV){const r=await nn(t),n=jn(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=fh(await t.arrayBuffer());return await nn(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new vr(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r=0?u=n:p=-n,s>=0?h=s:_=-s,c.drawImage(i,u,h,t,r,p,_,t,r),new vr(c.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(n>=0&&s>=0)a=a.extract({left:Math.floor(n),top:Math.floor(s),width:t,height:r});else if(n<=0&&s<=0){const i=Math.floor(-s),c=Math.floor(-n);a=a.extend({top:i,left:c,right:t-this.width-c,bottom:r-this.height-i})}else{let i=[0,0],c=0;s<0?(i[0]=Math.floor(-s),i[1]=r-this.height-i[0]):c=Math.floor(s);let u=[0,0],h=0;n<0?(u[0]=Math.floor(-n),u[1]=t-this.width-u[0]):h=Math.floor(n),a=a.extend({top:i[0],bottom:i[1],left:u[0],right:u[1]}).extract({left:h,top:c,width:t,height:r})}return await nn(a)}}async toBlob(t="image/png",r=1){if(!ve.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new K("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!ve.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=jn(t.width,t.height),n=new kv(t.data,t.width,t.height);return r.getContext("2d").putImageData(n,0,0),r}split(){const{data:t,width:r,height:n,channels:s}=this,a=t.constructor,i=t.length/s,c=Array.from({length:s},()=>new a(i));for(let u=0;unew vr(u,r,n,1))}_update(t,r,n,s=null){return this.data=t,this.width=r,this.height=n,s!==null&&(this.channels=s),this}clone(){return new vr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(ve.IS_WEB_ENV){if(ve.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=AC.get(r)??"image/png",s=await this.toBlob(n);return tC(t,s)}else if(ve.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ve.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return fh(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};yi.read.bind(yi);function qg(e,t,r=0,n=null){const s=e/t;let a=OE(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),at&&T.push(P)}else{let P=pt(E.data)[1];if(P===u-1||(C=Is(E.data),C[P]F*_[(G+1)%2])),m.boxes.push(A),m.classes.push(P),m.scores.push(C[P])}}h.push(m)}return h}function Av(e,t=null){const r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let a=0;a_[T]&&(_[T]=E[T],m[T]=M)}const w=new Array(c.dims[0]);for(let M=0;MM!==void 0);s.push({segmentation:p,labels:b})}return s}function SC(e,t,r,n){const s=[],a=[],i=[];for(let c=0;cr&&(s.push(h),a.push(m),i.push(p))}return[s,a,i]}function PC(e,t,r,n=.5,s=.8){const a=[];let i=0,c=0;const u=t[r].data;for(let p=0;p=n&&++c;let h=i>0&&c>0;return h&&(h=i/c>s),[h,a]}function FC(e,t,r,n,s,a=null,i=null){const[c,u]=i??e[0].dims,h=new K("int32",new Int32Array(c*u),[c,u]),p=[];if(i!==null)for(let M=0;Mm[C]&&(_[C]=M,m[C]=T[C])}let w=0;const b=h.data;for(let M=0;M200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let i=Math.round(e/r)*r,c=Math.round(t/r)*r;if(a*i*c>s){const u=Math.sqrt(a*e*t/s);i=Math.max(r,Math.floor(e/u/r)*r),c=Math.max(r,Math.floor(t/u/r)*r)}else if(a*i*cs?u=Math.floor(s*c/n):s>n&&(c=Math.floor(n*u/s)),await e.resize(u,c,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),n=lh(r.data)[0],a=pt(r.data)[0]-n;if(a===0)return e;const i=t/255;let c=r.width,u=r.height,h=0,p=0;const _=r.data;for(let m=0;mthis.preprocess(s)));return{pixel_values:Gr(r.map(s=>s.pixel_values),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await jr(e,pv,!0,t);return new this(r)}},Fv={};Ss(Fv,{BeitFeatureExtractor:()=>IC,BitImageProcessor:()=>LC,CHMv2ImageProcessor:()=>NC,CLIPFeatureExtractor:()=>BC,CLIPImageProcessor:()=>Iv,ChineseCLIPFeatureExtractor:()=>OC,ConvNextFeatureExtractor:()=>$C,ConvNextImageProcessor:()=>Lv,DINOv3ViTImageProcessor:()=>zC,DPTFeatureExtractor:()=>UC,DPTImageProcessor:()=>Bv,DeiTFeatureExtractor:()=>DC,DeiTImageProcessor:()=>Ov,DetrFeatureExtractor:()=>RC,DetrImageProcessor:()=>Nv,DonutFeatureExtractor:()=>GC,DonutImageProcessor:()=>ap,EfficientNetImageProcessor:()=>VC,GLPNFeatureExtractor:()=>QC,Gemma3ImageProcessor:()=>WC,Gemma4ImageProcessor:()=>$v,Glm46VImageProcessor:()=>HC,GroundingDinoImageProcessor:()=>YC,Idefics3ImageProcessor:()=>Qg,ImageFeatureExtractor:()=>ge,ImageProcessor:()=>ge,JinaCLIPImageProcessor:()=>JC,Lfm2VlImageProcessor:()=>rA,LlavaOnevisionImageProcessor:()=>nA,Mask2FormerImageProcessor:()=>aA,MaskFormerFeatureExtractor:()=>sA,MaskFormerImageProcessor:()=>op,MobileNetV1FeatureExtractor:()=>oA,MobileNetV1ImageProcessor:()=>Rv,MobileNetV2FeatureExtractor:()=>iA,MobileNetV2ImageProcessor:()=>zv,MobileNetV3FeatureExtractor:()=>lA,MobileNetV3ImageProcessor:()=>Gv,MobileNetV4FeatureExtractor:()=>cA,MobileNetV4ImageProcessor:()=>Uv,MobileViTFeatureExtractor:()=>uA,MobileViTImageProcessor:()=>Vv,NougatImageProcessor:()=>dA,OwlViTFeatureExtractor:()=>fA,OwlViTImageProcessor:()=>ip,Owlv2ImageProcessor:()=>hA,Phi3VImageProcessor:()=>_A,PixtralImageProcessor:()=>mA,PvtImageProcessor:()=>gA,Qwen2VLImageProcessor:()=>Dv,RTDetrImageProcessor:()=>wA,Sam2ImageProcessor:()=>Pf,Sam3ImageProcessor:()=>Pf,SamImageProcessor:()=>Pf,SapiensFeatureExtractor:()=>yA,SapiensImageProcessor:()=>Wv,SegformerFeatureExtractor:()=>vA,SegformerImageProcessor:()=>jv,SiglipImageProcessor:()=>bA,SmolVLMImageProcessor:()=>Qg,Swin2SRImageProcessor:()=>MA,VLMImageProcessor:()=>XC,ViTFeatureExtractor:()=>xA,ViTImageProcessor:()=>qv,VitMatteImageProcessor:()=>TA,VitPoseImageProcessor:()=>EA,YolosFeatureExtractor:()=>kA,YolosImageProcessor:()=>Hv});var IC=class extends ge{},LC=class extends ge{},OC=class extends ge{},NC=class extends ge{},Iv=class extends ge{},BC=class extends Iv{},Lv=class extends ge{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const r=Math.floor(t/this.crop_pct),[n,s]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,s,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},$C=class extends Lv{},Ov=class extends ge{},DC=class extends Ov{},Nv=class extends ge{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=At(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Il(...e)}post_process_panoptic_segmentation(...e){return Sv(...e)}post_process_instance_segmentation(...e){return Pv(...e)}},RC=class extends Nv{},zC=class extends ge{},ap=class extends ge{pad_image(e,t,r,n={}){const[s,a,i]=t;let c=this.image_mean;Array.isArray(this.image_mean)||(c=new Array(i).fill(c));let u=this.image_std;Array.isArray(u)||(u=new Array(i).fill(c));const h=c.map((p,_)=>-p/u[_]);return super.pad_image(e,t,r,{center:!0,constant_values:h,...n})}},GC=class extends ap{},Bv=class extends ge{},UC=class extends Bv{},VC=class extends ge{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},WC=class extends ge{};function jC(e,t,r,n,s){const a=n*r**2,i=Math.sqrt(a/(e*t)),c=s*r;let u=Math.floor(i*e/c)*c,h=Math.floor(i*t/c)*c;if(u===0&&h===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${c}.`);const p=Math.floor(n/s**2)*c;return u===0?(u=c,h=Math.min(Math.floor(t/e)*c,p)):h===0&&(h=c,u=Math.min(Math.floor(e/t)*c,p)),[u,h]}function qC(e,t,r,n,s,a,i){const c=Math.floor(t/s),u=Math.floor(r/s),h=c*u,p=s*s*n,_=new Float32Array(a*p);let m=0;for(let M=0;Ma),0));const h=a.dims[0]/i,p=a.dims[1],_=Math.floor(a.dims[2]/u),m=Math.floor(a.dims[3]/u),w=a.view(h,i,p,Math.floor(_/c),c,u,Math.floor(m/c),c,u).permute(0,3,6,4,7,2,1,5,8).view(h*_*m,p*i*u*u),b=new K("int64",[h,_,m],[1,3]);return{pixel_values:w,image_grid_thw:b,original_sizes:n,reshaped_input_sizes:s}}},HC=class extends Dv{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return sp(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}},QC=class extends ge{},YC=class extends ge{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=Ot([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},Qg=class extends ge{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,n]=e.dims.slice(-2);const s=n/r;return n>=r?(n=Math.ceil(n/t)*t,r=Math.floor(n/s),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,n=Math.floor(r*s),n=Math.ceil(n/t)*t),{height:r,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let s=[],a=[],i=[];const c=[],u=[];for(const E of n){let T=await Promise.all(E.map(A=>this.preprocess(A)));c.push(...T.map(A=>A.original_size)),u.push(...T.map(A=>A.reshaped_input_size)),T.forEach(A=>A.pixel_values.unsqueeze_(0));const{longest_edge:C}=this.max_image_size;let P;if(t??this.do_image_splitting){let A=new Array(T.length),F=new Array(T.length);P=await Promise.all(T.map(async(G,v)=>{const j=this.get_resize_for_vision_encoder(G.pixel_values,C),U=await Er(G.pixel_values,{size:[j.height,j.width]}),{frames:q,num_splits_h:ne,num_splits_w:H}=await this.split_image(U,this.max_image_size);return A[v]=ne,F[v]=H,je(q,0)})),a.push(A),i.push(F)}else{const A=[C,C];P=await Promise.all(T.map(F=>Er(F.pixel_values,{size:A}))),a.push(new Array(T.length).fill(0)),i.push(new Array(T.length).fill(0))}s.push(je(P,0))}const h=s.length,[p,_,m,w]=s[0].dims;let b,M;if(h===1)b=s[0].unsqueeze_(0),M=At([h,p,m,w],!0);else{const E=Math.max(...s.map(P=>P.dims.at(0)));M=At([h,E,m,w],!0);const T=M.data,C=E*m*w;for(let P=0;Pr||i>n){c=Math.ceil(a/r),u=Math.ceil(i/n);const h=Math.ceil(a/c),p=Math.ceil(i/u);for(let w=0;wt*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},JC=class extends ge{constructor(e){const{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,i=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},c=n==="bicubic"?3:2;super({...a,size:i,resample:c,do_center_crop:!0,crop_size:s,do_normalize:!0})}};function Yg(e,t){return Math.round(e/t)*t}function KC(e,t,r,n,s){let a=1/0,i=[1,1];const c=r*n;for(const u of t){const h=Math.abs(e-u[0]/u[1]);h.5*s*s*u[0]*u[1]&&(i=u)}return i}function ZC(e,t){const r=[],n=new Set;for(let s=e;s<=t;++s)for(let a=1;a<=s;++a)for(let i=1;i<=s;++i){const c=a*i;if(c>=e&&c<=t){const u=a<<16|i;n.has(u)||(n.add(u),r.push([a,i]))}}return r.sort((s,a)=>s[0]*s[1]-a[0]*a[1])}function eA(e,t){const[r,n,s,a]=e.dims,i=Math.floor(s/t),c=Math.floor(a/t),u=t*t*n,h=e.data,p=new Float32Array(r*i*c*u),_=s*a;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=ZC(this.min_tiles,this.max_tiles),[n,s]=KC(t/e,r,t,e,this.tile_size);return{grid_width:n,grid_height:s,target_width:this.tile_size*n,target_height:this.tile_size*s}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];const n=[],s=[],a=[],i=[],c=[],u=[];for(const p of r){const _=await Promise.all(p.map(m=>this.preprocess(m,{do_pad:!1})));for(const{pixel_values:m}of _){const[,w,b]=m.dims,M=m.unsqueeze_(0),E=this.encoder_patch_size*this.downsample_factor,T=E**2,[C,P]=sp(Math.max(E,w),Math.max(E,b),E,this.min_image_tokens*T,this.max_image_tokens*T).map(U=>Math.max(E,U));let A,F=1,G=1;const v=this._is_image_too_large(w,b),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(v&&j){const{grid_width:U,grid_height:q,target_width:ne,target_height:H}=this._get_grid_layout(w,b);F=q,G=U;const I=await Er(M,{size:[H,ne]});A=[];for(let S=0;S(h-this.image_mean[p])/this.image_std[p]);return super.pad_image(e,t,{width:c,height:i},{center:!0,constant_values:u,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Sf(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),s=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(const{pixel_values:_}of n){_.unsqueeze_(0);const[m,w]=_.dims.slice(-2),b=await Er(_,{size:[zt,zt],mode:"bicubic"});if(t>0){const M=[],E=Sf(t),T=fs(w/E),C=fs(m/E);for(let A=0;A_.map(m=>zt*Af(m/zt))),h=new K("int64",u.flat(),[r,2]),p=u.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:c,original_sizes:s,reshaped_input_sizes:a,image_sizes:h,num_img_tokens:p}}},mA=class extends ge{get_resize_output_image_size(e,t){const{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[n,s]=e.size,a=Math.max(n,s)/r;let i=n,c=s;a>1&&(i=Math.floor(n/a),c=Math.floor(s/a));const{patch_size:u,spatial_merge_size:h}=this.config;if(!h)throw new Error("config must contain 'spatial_merge_size'");const p=u*h,_=Math.floor((i-1)/p)+1,m=Math.floor((c-1)/p)+1;return[_*p,m*p]}},gA=class extends ge{},wA=class extends ge{post_process_object_detection(...e){return Il(...e)}},Pf=class extends ge{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=fg(e);if(s.length===3)n||(s=[1,...s]),e=[e];else if(s.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new K("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:n=null}={}){const s=await super._call(e);if(t&&(s.input_points=this.reshape_input_points(t,s.original_sizes,s.reshaped_input_sizes)),r){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(r,s.input_points)}return n&&(s.input_boxes=this.reshape_input_points(n,s.original_sizes,s.reshaped_input_sizes,!0)),s}async post_process_masks(e,t,r,{mask_threshold:n=0,binarize:s=!0,pad_size:a=null}={}){const i=[];a=a??this.pad_size??this.size;const c=[a.height,a.width];for(let u=0;un&&(w[b]=1);_=new K("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:s=32,crop_n_points_downscale_factor:a=1}={}){}},Wv=class extends ge{post_process_semantic_segmentation(...e){return Av(...e)}},yA=class extends Wv{},jv=class extends ge{post_process_semantic_segmentation(...e){return Av(...e)}},vA=class extends jv{},bA=class extends ge{},MA=class extends ge{pad_image(e,t,r,n={}){const[s,a,i]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}},qv=class extends ge{},xA=class extends qv{},TA=class extends ge{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Gr(r.map((a,i)=>je([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},EA=class extends ge{post_process_pose_estimation(e,t,{threshold:r=null}={}){const n=e.tolist(),[s,a,i,c]=e.dims,u=[];for(let h=0;h/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const t=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(const[n,s]of this.task_prompts_with_input)if(r.includes(n)){t.push(s.replaceAll("{input}",r).replaceAll(n,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const n=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("","").replaceAll("","");let s;switch(n){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),c=[],u=[];for(const[h,p,..._]of i)c.push(p?p.trim():c.at(-1)??""),u.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*r[w%2]));s={labels:c,[a]:u};break;default:throw new Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:s}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=await this.image_processor(e,r),s=t?this.tokenizer(this.construct_prompts(t),r):{};return{...n,...s}}},AA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;const{boi_token:n,image_token:s,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=s,this.eoi_token=a;const i=s.repeat(this.image_seq_length);this.full_image_sequence=` ${n}${i}${a} `}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let n;return t&&(n=await this.image_processor(t,r),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...n}}},SA=class extends De{static image_processor_class=Pt;static feature_extractor_class=rr;static tokenizer_class=Oe;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:n,boa_token:s,audio_token:a,eoa_token:i,image_token_id:c,boi_token:u,image_token:h,eoi_token:p}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const _=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${s}${_}${i} `,this.image_token_id=c,this.boi_token=u,this.image_token=h;const m=h.repeat(this.image_seq_length);this.full_image_sequence=` ${u}${m}${p} `}async _call(e,t=null,r=null,n={}){typeof e=="string"&&(e=[e]);let s;r&&(s=await this.feature_extractor(r,n),e=e.map(c=>c.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,n),e=e.map(c=>c.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...s}}},PA=class extends De{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;const{audio_token:n,boa_token:s,eoa_token:a,image_token:i,boi_token:c,eoi_token:u}=this.tokenizer.config;this.audio_token=n,this.boa_token=s,this.eoa_token=a,this.image_token=i,this.boi_token=c,this.eoi_token=u}static async from_pretrained(e,t={}){const[r,n,s]=await Promise.all([jr(e,_v,!0,t),Oe.from_pretrained(e,t),Jh(e,mv,!1,t)]),a={tokenizer:n};return r.image_processor&&(a.image_processor=new $v(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new Tv(r.feature_extractor)),new this(r,a,s)}_compute_audio_num_tokens(e,t){const r=Math.round(t*20/1e3),n=Math.round(t*10/1e3),s=Math.floor(r/2);let a=Math.floor((e+s-r-1)/n)+1;if(a<=0)return 0;for(let i=0;i<2;++i)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,r=null,n={}){typeof e=="string"&&(e=[e]);let s;if(t){s=await this.image_processor(t,n);const i=s.num_soft_tokens_per_image;let c=0;e=e.map(u=>u.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(i[c++])}${this.eoi_token} `))}let a;if(r){const i=Array.isArray(r)?r:[r];a=await this.feature_extractor(i[0],n);const c=this.feature_extractor.config.sampling_rate??16e3;let u=0;e=e.map(h=>h.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[u++].length,c))}${this.eoa_token} `))}return{...this.tokenizer(e,n),...s,...a}}},lp=class extends De{static image_processor_class=Pt;static tokenizer_class=Oe;static image_token="<|image_pad|>";async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let n,s;if(t&&(n=await this.image_processor(t),s=n.image_grid_thw),s){let i=this.image_processor.config.merge_size**2,c=0;const u=this.constructor.image_token,h=s.tolist();e=e.map(p=>{for(;p.includes(u);){const _=Number(h[c++].reduce((m,w)=>m*w,1n));p=p.replace(u,"<|placeholder|>".repeat(Math.floor(_/i)))}return p.replaceAll("<|placeholder|>",u)})}return{...this.tokenizer(e),...n}}},FA=class extends lp{static image_token="<|image|>"},IA=class extends De{static tokenizer_class=Oe;static feature_extractor_class=rr;static uses_processor_config=!0;_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:n}=this.feature_extractor.config,s=Math.floor(r/n),a=Math.floor(e/t)+1,i=Math.floor(a/2);return Math.ceil(i/r)*s}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){const{input_features:a}=await this.feature_extractor(t);n.input_features=a;const i=this._get_num_audio_features(t.length),c=new Uint8Array(i).fill(1);n.input_features_mask=new K("bool",c,[1,i]);const u=this.config.audio_token??"<|audio|>";if(!e.includes(u))throw new Error(`The input text does not contain the audio token ${u}.`);e=e.replaceAll(u,u.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}};function LA(e,t){const n=e.dims.at(-1)-1,s=e.tolist();s.fill(!1,0,1),s.fill(!1,n);const a=t.tolist();return s.map((i,c)=>i?c:null).filter(i=>i!==null).map(i=>a[i])}var OA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;async _call(e,t,r={}){const n=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:n=.25,target_sizes:s=null}={}){const{logits:a,pred_boxes:i}=e,c=a.dims[0];if(s!==null&&s.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const u=a.dims.at(1),h=a.sigmoid(),p=h.max(-1).tolist(),_=i.tolist().map(w=>w.map(b=>Cv(b))),m=[];for(let w=0;wP.map((A,F)=>A*b[(F+1)%2])));const M=p[w],E=[],T=[],C=[];for(let P=0;P`+s.repeat(e);i+=` `}return i+=` ${n}${a}`+s.repeat(e)+`${n}`,i}function BA(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function $A(e,t,r,n,s,a){return e===0&&t===0?BA(r,n,s,a):NA(r,e,t,n,s,a)}var Xg=class extends De{static image_processor_class=Pt;static tokenizer_class=Oe;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,t=null,r={}){r.return_row_col_info??=!0;let n;t&&(n=await this.image_processor(t,r)),Array.isArray(e)||(e=[e]);const s=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,c=[],u=[];for(let p=0;p$A(T,w[C],i,this.fake_image_token,this.image_token,this.global_img_token)),M=_.split(this.image_token);if(M.length===0)throw new Error("The image token should be present in the text.");let E=M[0];for(let T=0;TM.images).flatMap(M=>M.images).map(M=>yi.read(M)));const n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=M=>n.encode(M,{add_special_tokens:!1}),i=s.split(this.image_tag),c=i.length-1;if(t.length!==c)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${c})`);const[u,h,p]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let _=a(i[0]),m=new Array(_.length).fill(!1);for(let M=1;M0){const M=await this.image_processor(t);return M.pixel_values.unsqueeze_(0),{...b,...M}}return b}},RA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=e?this.tokenizer(e,r):{},s=t?await this.image_processor(t,r):{};return{...n,...s}}},zA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;async _call(e,t=null,r={}){const{image_rows:n,image_cols:s,image_sizes:a,...i}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){const c=this.config.image_token??"",{tile_size:u=512,downsample_factor:h=2,encoder_patch_size:p=16,use_thumbnail:_=!0}=this.image_processor.config,m=C=>Math.ceil(Math.floor(C/p)/h),w=m(u)**2,b=this.config.image_start_token??"<|image_start|>",M=this.config.image_end_token??"<|image_end|>",E=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let T=0;t=t.map(C=>{const P=C.split(c);return P[0]+P.slice(1).map(A=>{const F=T++,[G,v]=a[F],j=n[F],U=s[F],q=m(G)*m(v);let ne=b;if(j>1||U>1){const H=c.repeat(w);for(let I=0;I`+H;_&&(ne+=E+c.repeat(q))}else ne+=c.repeat(q);return ne+M+A}).join("")})}return{...i,...t?this.tokenizer(t,r):{}}}},GA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,i]=n.pixel_values.dims.slice(-2),{image_token:c,patch_size:u,num_additional_image_tokens:h}=this.config,p=Math.floor(a/u)*Math.floor(i/u)+h;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let _=0;_0?b.reduce((E,T)=>E*T,1):0;u.push(w),c.push(M)}return[s(u),c]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[n,s]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(t,"bpe"),[c,u]=this._decode_helper(r,"wp"),h=[],p=[];for(let _=0;_";function jA(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e} `}var qA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(be.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=this.tokenizer.bos_token,s=this.image_processor.config.image_seq_length;let a;t.some(u=>u.includes(hs))?a=t.map(u=>{const h=u.replaceAll(hs,hs.repeat(s)),p=h.lastIndexOf(hs),_=p===-1?0:p+hs.length;return h.slice(0,_)+n+h.slice(_)+` `}):(be.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(u=>jA(u,n,s,hs,e.length)));const i=this.tokenizer(a,r);return{...await this.image_processor(e,r),...i}}},Kg="<|image|>",HA=/<\|image_\d+\|>/g,QA=class extends De{static image_processor_class=Pt;static tokenizer_class=Oe;async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(t){i=await this.image_processor(t,{num_crops:s});const{num_img_tokens:c}=i,u=e.map((p,_)=>p.split(HA).join(Kg.repeat(c[_])));a=this.tokenizer(u,{padding:r,truncation:n});const h=this.tokenizer._tokenizer.token_to_id(Kg);a.input_ids.map_(p=>p==h?-p:p)}else a=this.tokenizer(e);return{...a,...i}}},YA=class extends De{static tokenizer_class=Oe;static image_processor_class=Pt;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,i]=n.pixel_values.dims.slice(-2),{image_token:c,image_break_token:u,image_end_token:h,patch_size:p,spatial_merge_size:_}=this.config,m=p*_,w=Math.floor(a/m),b=Math.floor(i/m);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let M=0;MnS(w,c)),h=u.map(w=>w.length),p=u.flat(),_=(await Promise.all(p.map(w=>this.feature_extractor(w,r)))).map(w=>w.input_features);n.audio_values=_.length>1?je(_,0):_[0];let m=a[0];for(let w=0;w0){if(h>Fg)throw new Error(`The number of external data chunks (${h}) exceeds the maximum allowed value (${Fg}).`);const p=Kv(i,h);for(const _ of p){const m=`${n.subfolder??""}/${_}`;u.push(new Promise(async(w,b)=>{const M=await gl(e,m,!0,n,c);w(M instanceof Uint8Array?{path:_,data:M}:_)}))}}else a.externalData!==void 0&&(u=a.externalData.map(async p=>{if(typeof p.data=="string"){const _=await gl(e,p.data,!0,n);return{...p,data:_}}return p}));return Promise.all(u)}async function _S(e,t,r,n=!1,s=void 0){let a=r.config?.["transformers.js_config"]??{};const i=rv(r.device??a.device,t,{warn:C=>be.info(C)}),c=VE(i),u=a.device_config??{};u.hasOwnProperty(i)&&(a={...a,...u[i]});const h=nv(r.dtype??a.dtype,t,i,{configDtype:a.dtype,warn:C=>be.info(C)});if(uh.hasOwnProperty(h)){if(i==="webgpu"&&!ve.IS_NODE_ENV&&h===st.fp16&&!await qE())throw new Error(`The device (${i}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${h}. Should be one of: ${Object.keys(st).join(", ")}`);const p=uh[h],_={...r.session_options};_.executionProviders??=c;const m=a.free_dimension_overrides;m?_.freeDimensionOverrides??=m:i.startsWith("webnn")&&!_.freeDimensionOverrides&&be.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${i}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const w=hS(e,t,r,p),b=r.use_external_data_format??a.use_external_data_format,M=await pS(e,t,p,r,b,_);if(M.length>0&&(!ve.IS_NODE_ENV||M.some(C=>typeof C!="string"))&&(_.externalData=M),n&&i==="webgpu"){const C=Ll(r.config,{prefix:"present",session_name:s});if(C.size>0&&!Kh()){const P={};for(const A of C)P[A]="gpu-buffer";_.preferredOutputLocation=P}}return{buffer_or_path:await w,session_options:_,session_config:{dtype:h,device:i}}}async function mS(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const a=n?.[s]??!1,{buffer_or_path:i,session_options:c,session_config:u}=await _S(e,t[s],r,a,s),h=await Zy(i,c,u);return[s,h]})))}function Zv(e){for(let t in e)tv(e[t])?e[t]=new K(e[t]):typeof e[t]=="object"&&Zv(e[t]);return e}async function Pe(e,t){const r=gS(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,i])=>{const c=i.ort_tensor;return ve.IS_NODE_ENV&&typeof Float16Array<"u"&&c.cpuData instanceof Float16Array&&(c.cpuData=new Uint16Array(c.cpuData.buffer)),[a,c]})),s=await ev(e,n);return Zv(s)}catch(n){const s=Object.fromEntries(Object.entries(r).map(([a,i])=>{const c={type:i.type,dims:i.dims,location:i.location};return c.location!=="gpu-buffer"&&(c.data=i.data),[a,c]}));throw be.error(`An error occurred during model execution: "${n}".`),be.error("Inputs given to model:",s),n}}function gS(e,t){const r=Object.create(null),n=[];for(const i of e.inputNames){const c=t[i];if(!(c instanceof K)){n.push(i);continue}r[i]=Kh()?c.clone():c}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let i=Object.keys(t).filter(c=>!e.inputNames.includes(c));be.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${i.join(", ")}".`)}return r}var _t=class{},fe=class extends _t{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},at=class extends _t{constructor({logits:e}){super(),this.logits=e}},mt=class extends _t{constructor({logits:e}){super(),this.logits=e}},Ft=class extends _t{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},as=class extends _t{constructor({logits:e}){super(),this.logits=e}},wS=class extends _t{constructor({alphas:e}){super(),this.alphas=e}},nr=class extends Yt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},yS=class extends Yt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},yl=class extends Yt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const n of this.processors)r=n(e,r);return r}[Symbol.iterator](){return this.processors.values()}},vS=class extends nr{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r=1&&s[s.length-1]>=this.timestamp_begin,i=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const p=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(p+1).fill(-1/0)}const c=PE(n),u=Math.log(c.subarray(this.timestamp_begin).map(Math.exp).reduce((p,_)=>p+_)),h=pt(c.subarray(0,this.timestamp_begin))[0];u>h&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},TS=class extends nr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let s=0;s1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,n=t.slice([0,r],null),s=t.slice([r,t.dims[0]],null);for(let a=0;at.length>=this.max_length)}},IS=class extends Ol{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const n=r.at(-1);return this.eos_token_id.some(s=>n==s)})}},Nl=class extends Yt{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),n=e.data;if(t===-1)n=n.slice(-r);else{let s=t*r;n=n.slice(s,s+r)}return n}randomSelect(e){return hE(e)}static getSampler(e){if(e.do_sample)return new OS(e);if(e.num_beams>1)return new NS(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new LS(e)}},LS=class extends Nl{async sample(e){const t=pt(e.data)[1];return[[BigInt(t),0]]}},OS=class extends Nl{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,n]=await av(e,t),s=Is(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},NS=class extends Nl{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,n]=await av(e,t),s=Is(r.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(s[i])])}},BS=class{constructor(e){if(e)for(const t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);const r=e[t];if(!(r instanceof K))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){const e=this;if(Object.keys(e).length===0)return 0;for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(const t in e){const r=this[t],n=e[t];r&&r!==n&&r.location==="gpu-buffer"&&r.dispose(),this[t]=n}}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},cp=BS,Z={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},sn={[Z.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[Z.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[Z.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[Z.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...sn[Z.ImageTextToText].text_only_sessions};return r||(n.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(n.model="encoder_model"),n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...sn[Z.AudioTextToText].text_only_sessions};return r||(n.audio_encoder="audio_encoder"),n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...sn[Z.ImageAudioTextToText].text_only_sessions};return r||(n.audio_encoder="audio_encoder",n.vision_encoder="vision_encoder"),n},optional_configs:{generation_config:"generation_config.json"}},[Z.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[Z.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[Z.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Z.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...sn[Z.VoxtralRealtime].text_only_sessions};return r||(n.audio_encoder="audio_encoder"),n},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};function $S(e,t,r={}){const n=sn[e]??sn.default;return{sessions:n.sessions(t,r,r.textOnly??!1),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}function DS(e,{warn:t=!0}={}){const r=e.architectures||[];for(const n of r){const s=zr.get(n);if(s!==void 0)return s}if(e.model_type){const n=zr.get(e.model_type);if(n!==void 0)return n;for(const s of Object.values(ys))if(s.has(e.model_type)){const a=zr.get(s.get(e.model_type));if(a!==void 0)return a}}if(t){const n=r.length>0?r.join(", "):"(none)";be.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${n}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Fl}`)}return Z.EncoderOnly}function RS(e,{config:t=null,cache_dir:r=null,local_files_only:n=!1,revision:s="main"}={}){if(t!==null)return wl.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s});const a=JSON.stringify([e,r,n,s]);return Wy(a,()=>wl.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s}))}async function zS(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await RS(e,{config:t});const a=["config.json"],i=t["transformers.js_config"]??{},c=i.use_external_data_format,u="onnx",h=n??i.device;let p=r??i.dtype;const _=DS(t),m=(M,E=null)=>{E=E??M;const T=rv(h,M),C=nv(p,M,T),P=uh[C]??"",A=`${E}${P}.onnx`,F=`${u}/${A}`;a.push(F);const G=Jv(c,A,M);for(const v of Kv(A,G)){const j=`${u}/${v}`;a.push(j)}},{sessions:w,optional_configs:b}=$S(_,t,{model_file_name:s});for(const[M,E]of Object.entries(w))m(M,E);if(b)for(const M of Object.values(b))a.push(M);return a}var ys=null;function GS(e){ys=e}function _h(e){if(e instanceof K)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new K("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new K("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function s0(e){return new K("bool",[e],[1])}var ew={[Z.DecoderOnly]:{can_generate:!0,forward:Ur,prepare_inputs:mi},[Z.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ur,prepare_inputs:mi},[Z.Seq2Seq]:{can_generate:!0,forward:Hi,prepare_inputs:vl},[Z.Vision2Seq]:{can_generate:!0,forward:Hi,prepare_inputs:vl},[Z.Musicgen]:{can_generate:!0,forward:Hi},[Z.EncoderDecoder]:{can_generate:!1,forward:Hi},[Z.ImageTextToText]:{can_generate:!0,forward:jS,prepare_inputs:Qi},[Z.AudioTextToText]:{can_generate:!0,forward:WS,prepare_inputs:Qi},[Z.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Qi},[Z.Phi3V]:{can_generate:!0,prepare_inputs:Qi},[Z.MultiModality]:{can_generate:!0},[Z.AutoEncoder]:{can_generate:!1,forward:US},[Z.Chatterbox]:{can_generate:!0,forward:ln},[Z.VoxtralRealtime]:{can_generate:!0,prepare_inputs:mi},default:{can_generate:!1,forward:ln}};function tw(e,t){let r=zr.get(e),n=!1;const s=t?.architectures?.[0];if(s&&s!==e&&e?.endsWith("ForCausalLM")&&s.endsWith("ForConditionalGeneration")){const c=zr.get(s);c!==void 0&&(r=c,n=!0)}const a=ew[r]??ew.default,i=sn[r]??sn.default;return{typeConfig:{...a,...i},textOnly:n,modelType:r}}var zr=new Map,up=new Map,Es=new Map,O=class extends Yt{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,r){super(),this.config=e,this.sessions=t,this.configs=r;const n=Es.get(this.constructor),{typeConfig:s}=tw(n,e);this.can_generate=s.can_generate,this._forward=s.forward,this._prepare_inputs_for_generation=s.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:i=null,subfolder:c="onnx",device:u=null,dtype:h=null,use_external_data_format:p=null,session_options:_={}}={}){const m={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:i,subfolder:c,device:u,dtype:h,use_external_data_format:p,session_options:_},w=Es.get(this);r=m.config=await wl.from_pretrained(e,m);const{typeConfig:b,textOnly:M,modelType:E}=tw(w,r);if(E===void 0){const A=w??r?.model_type;A!=="custom"&&be.warn(`Model type for '${A}' not found, assuming encoder-only architecture. Please report this at ${Fl}.`)}if(t&&!(t instanceof ug)){const A={};try{const F=await zS(e,{config:r,dtype:h,device:u,model_file_name:i});(await Promise.all(F.map(v=>Xh(e,v,m)))).forEach((v,j)=>{if(v.exists){const U=F[j]==="config.json";A[F[j]]={loaded:U?v.size??0:0,total:v.size??0}}})}catch(F){be.warn(`Unable to fetch model file metadata for total progress tracking: ${F}`)}Object.keys(A).length>0&&(m.progress_callback=new ug(t,A))}const T=b.sessions(r,m,M),C=[mS(e,T,m,b.cache_sessions)];b.optional_configs&&C.push(HS(e,b.optional_configs,m));const P=await Promise.all(C);return new this(r,...P)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,r=null){const n=new yl;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new ES(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new TS(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new AS(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new kS(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new CS(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new vS(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new bS(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new MS(e.suppress_tokens)),e.begin_suppress_tokens!==null){const s=t>1||e.forced_bos_token_id===null?t:t+1;n.push(new e0(e.begin_suppress_tokens,s))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new SS(e.guidance_scale)),e.temperature===0&&e.do_sample&&(be.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new PS(e.temperature)),r!==null&&n.extend(r),n}_prepare_generation_config(e,t,r=t0){const n={...this.config};for(const a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);const s=new r(n);return Object.assign(s,this.generation_config??{}),e&&Object.assign(s,e),t&&Object.assign(s,xt(t,Object.getOwnPropertyNames(s))),s}_get_stopping_criteria(e,t=null){const r=new r0;return e.max_length!==null&&r.push(new FS(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new IS(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[ys.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,ys.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,ys.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,ys.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Es.get(this.constructor),r=new Set,n=this.config.model_type;for(const a of e){const i=a?.get(n);i&&r.add(i)}let s=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(s+=` Please use the following class instead: ${[...r].join(", ")}`),Error(s)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:n}){return r.past_key_values=mh(t,r.past_key_values),r.input_ids=new K("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in r&&(r.decoder_attention_mask=je([r.decoder_attention_mask,Ot([r.decoder_attention_mask.dims[0],1])],1)):r.attention_mask=je([r.attention_mask,Ot([r.attention_mask.dims[0],1])],1),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){const n=xt(r,this.forward_params),s=this.main_input_name;if(s in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[s]=e;return{inputs_tensor:n[s],model_inputs:n,model_input_name:s}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:a,pixel_values:i,attention_mask:c,...u}=t,h=await this._prepare_inputs_embeds(t);t={...u,...xt(h,["inputs_embeds","attention_mask"])}}let{last_hidden_state:s}=await ln(this,t);if(n.guidance_scale!==null&&n.guidance_scale>1)s=je([s,dh(s,0)],0),"attention_mask"in t&&(t.attention_mask=je([t.attention_mask,cv(t.attention_mask)],0));else if(t.decoder_input_ids){const a=_h(t.decoder_input_ids).dims[0];if(a!==s.dims[0]){if(s.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${s.dims[0]}) than the decoder inputs (${a}).`);s=je(Array.from({length:a},()=>s),0)}}return t.encoder_outputs=s,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:n,bos_token_id:s,generation_config:a}){let{decoder_input_ids:i,...c}=r;if(!(i instanceof K)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=s,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=_h(i)}return c.decoder_attention_mask=iv(i),{input_ids:i,model_inputs:c}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,streamer:s=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:i,model_inputs:c,model_input_name:u}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const h=this.config.is_encoder_decoder;h&&("encoder_outputs"in c||(c=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:c,model_input_name:u,generation_config:t})));let p;h?{input_ids:p,model_inputs:c}=this._prepare_decoder_input_ids_for_generation({batch_size:c[u].dims.at(0),model_input_name:u,model_kwargs:c,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):p=c[u];let _=p.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=_+t.max_new_tokens);const m=this._get_logits_processor(t,_,r),w=this._get_stopping_criteria(t,n),b=c[u].dims.at(0),M=Nl.getSampler(t),E=new Array(b).fill(0),T=p.tolist();s&&s.put(T);let C,P={},A={};for(;;){if(c=this.prepare_inputs_for_generation(T,c,t),C=await this.forward(c),t.return_dict_in_generate)if(t.output_attentions){const I=VS(C);for(const S in I)S in P||(P[S]=[]),P[S].push(I[S])}else this._return_dict_in_generate_keys&&Object.assign(A,xt(C,this._return_dict_in_generate_keys));const U=C.logits.slice(null,-1,null).to("float32"),q=m(T,U),ne=[];for(let I=0;II))break;c=this._update_model_kwargs_for_generation({generated_input_ids:ne,outputs:C,model_inputs:c,is_encoder_decoder:h})}s&&s.end();const F=new K("int64",T.flat(),[T.length,T[0].length]),G=mh(C,c.past_key_values),v=new Set(Object.values(G));for(const U of Object.values(C))U.location==="gpu-buffer"&&!v.has(U)&&U.dispose();return"past_key_values"in a||t.return_dict_in_generate||await G.dispose(),t.return_dict_in_generate?{sequences:F,past_key_values:G,...P,...A}:F}async _encode_input(e,t,r){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);const n=this.sessions[e];return(await Pe(n,xt(t,n.inputNames)))[r]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function Hi(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,decoder_attention_mask:a,...i}=t;if(!r){const c=xt(t,e.sessions.model.inputNames);r=(await ln(e,c)).last_hidden_state}return i.input_ids=s,i.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),a&&!i.attention_mask&&(i.attention_mask=a),await Ur(e,i,!0)}async function ln(e,t){const r=e.sessions.model,n=xt(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=cv(n.input_ids)}if(r.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const s=n.pixel_values.dims;n.pixel_mask=Ot([s[0],s[2],s[3]])}return await Pe(r,n)}async function US(e,t){const r=await e.encode(t);return await e.decode(r)}function mh(e,t){const r=Object.create(null);for(const n in e)if(n.startsWith("present")){const s=n.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");n.includes("encoder")&&t?r[s]=t[s]:r[s]=e[n]}return t?(t.update(r),t):new cp(r)}function VS(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const n in e)n.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[n]));return t}function a0(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function dp(e,t,r){if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;const n=e.sessions.decoder_model_merged??e.sessions.model,s=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=Ll(e.config),i=e.config?.normalized_config?.num_heads,c={batch_size:s};typeof i=="number"&&(c["batch_size x num_heads"]=s*i);const u=Object.create(null);for(const h of n.inputMetadata){if(!a.has(h.name))continue;const p=a0(h.shape,c),_=p.reduce((b,M)=>b*M,1),m=wi[h.type],w=new K(h.type,new m(_),p);t[h.name]=w,u[h.name]=w}return r?(r.update(u),r):new cp(u)}async function Ur(e,t,r=!1){const n=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:s,...a}=t;if(n.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=s0(s!=null&&Object.keys(s).length>0)),n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const c=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=qS(a,s,c)}n.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new K("int64",[0n],[])),dp(e,a,s);const i=xt(a,n.inputNames);return await Pe(n,i)}async function o0(e,{encode_function:t,merge_function:r,modality_input_names:n,modality_output_name:s,input_ids:a=null,attention_mask:i=null,position_ids:c=null,inputs_embeds:u=null,past_key_values:h=null,generation_config:p=null,logits_processor:_=null,...m}){if(!u){u=await e.encode_text({input_ids:a,...m});const b=xt(m,n);if(Object.keys(b).length>0){if(a.dims[1]!==1){const M=await t({...b,...m});({inputs_embeds:u,attention_mask:i}=r({[s]:M,inputs_embeds:u,input_ids:a,attention_mask:i}))}else if(h&&a.dims[1]===1){const M=a.dims[1],E=h.get_seq_length();i=je([Ot([a.dims[0],E]),i.slice(null,[i.dims[1]-M,i.dims[1]])],1)}}}if(!c&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){const{image_grid_thw:b,video_grid_thw:M}=m;[c]=e.get_rope_index(a,b,M,i)}return await Ur(e,{inputs_embeds:u,past_key_values:h,attention_mask:i,position_ids:c,generation_config:p,logits_processor:_},!0)}async function WS(e,t){return await o0(e,{...t,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function jS(e,t){return await o0(e,{...t,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function i0(e,t=0){const[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let i=0;ii.dims[1]||s[s.at(-1)])),{...r,decoder_input_ids:_h(t)}}function Qi(e,...t){return e.config.is_encoder_decoder?vl(e,...t):mi(e,...t)}function l0({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(h=>h.reduce((p,_,m)=>(_==e&&p.push(m),p),[])),i=a.reduce((h,p)=>h+p.length,0),c=r.dims[0];if(i!==c)throw new Error(`Number of tokens and features do not match: tokens: ${i}, features ${c}`);let u=0;for(let h=0;h{const s=await jr(e,t[n],!1,r);return[n,s]})))}var hp={};Ss(hp,{ASTForAudioClassification:()=>aP,ASTModel:()=>sP,ASTPreTrainedModel:()=>gp,AfmoeForCausalLM:()=>tP,AfmoeModel:()=>eP,AfmoePreTrainedModel:()=>_p,AlbertForMaskedLM:()=>JS,AlbertForQuestionAnswering:()=>XS,AlbertForSequenceClassification:()=>YS,AlbertModel:()=>QS,AlbertPreTrainedModel:()=>Ti,ApertusForCausalLM:()=>ZS,ApertusModel:()=>KS,ApertusPreTrainedModel:()=>pp,ArceeForCausalLM:()=>nP,ArceeModel:()=>rP,ArceePreTrainedModel:()=>mp,BartForConditionalGeneration:()=>iP,BartForSequenceClassification:()=>lP,BartModel:()=>oP,BartPretrainedModel:()=>Bl,BeitForImageClassification:()=>uP,BeitModel:()=>cP,BeitPreTrainedModel:()=>wp,BertForMaskedLM:()=>fP,BertForQuestionAnswering:()=>_P,BertForSequenceClassification:()=>hP,BertForTokenClassification:()=>pP,BertModel:()=>dP,BertPreTrainedModel:()=>Ls,BlenderbotForConditionalGeneration:()=>gP,BlenderbotModel:()=>mP,BlenderbotPreTrainedModel:()=>yp,BlenderbotSmallForConditionalGeneration:()=>yP,BlenderbotSmallModel:()=>wP,BlenderbotSmallPreTrainedModel:()=>vp,BloomForCausalLM:()=>bP,BloomModel:()=>vP,BloomPreTrainedModel:()=>bp,CHMv2ForDepthEstimation:()=>SP,CHMv2PreTrainedModel:()=>h0,CLIPModel:()=>FP,CLIPPreTrainedModel:()=>os,CLIPSegForImageSegmentation:()=>BP,CLIPSegModel:()=>NP,CLIPSegPreTrainedModel:()=>Mp,CLIPTextModel:()=>IP,CLIPTextModelWithProjection:()=>m0,CLIPVisionModel:()=>LP,CLIPVisionModelWithProjection:()=>OP,CamembertForMaskedLM:()=>xP,CamembertForQuestionAnswering:()=>kP,CamembertForSequenceClassification:()=>TP,CamembertForTokenClassification:()=>EP,CamembertModel:()=>MP,CamembertPreTrainedModel:()=>Os,ChatterboxModel:()=>d0,ChatterboxPreTrainedModel:()=>u0,ChineseCLIPModel:()=>AP,ChineseCLIPPreTrainedModel:()=>f0,ClapAudioModelWithProjection:()=>_0,ClapModel:()=>PP,ClapPreTrainedModel:()=>$l,ClapTextModelWithProjection:()=>p0,CodeGenForCausalLM:()=>DP,CodeGenModel:()=>$P,CodeGenPreTrainedModel:()=>xp,Cohere2ForCausalLM:()=>UP,Cohere2Model:()=>GP,Cohere2PreTrainedModel:()=>Ep,CohereAsrForConditionalGeneration:()=>WP,CohereAsrModel:()=>VP,CohereAsrPreTrainedModel:()=>kp,CohereForCausalLM:()=>zP,CohereModel:()=>RP,CoherePreTrainedModel:()=>Tp,ConvBertForMaskedLM:()=>qP,ConvBertForQuestionAnswering:()=>YP,ConvBertForSequenceClassification:()=>HP,ConvBertForTokenClassification:()=>QP,ConvBertModel:()=>jP,ConvBertPreTrainedModel:()=>Ns,ConvNextForImageClassification:()=>JP,ConvNextModel:()=>XP,ConvNextPreTrainedModel:()=>Cp,ConvNextV2ForImageClassification:()=>ZP,ConvNextV2Model:()=>KP,ConvNextV2PreTrainedModel:()=>Ap,DFineForObjectDetection:()=>nF,DFineModel:()=>rF,DFinePreTrainedModel:()=>Pp,DINOv3ConvNextModel:()=>SF,DINOv3ConvNextPreTrainedModel:()=>E0,DINOv3ViTModel:()=>PF,DINOv3ViTPreTrainedModel:()=>k0,DPTForDepthEstimation:()=>DF,DPTModel:()=>$F,DPTPreTrainedModel:()=>Bp,DacDecoderModel:()=>v0,DacDecoderOutput:()=>w0,DacEncoderModel:()=>y0,DacEncoderOutput:()=>g0,DacModel:()=>sF,DacPreTrainedModel:()=>Dl,DebertaForMaskedLM:()=>oF,DebertaForQuestionAnswering:()=>cF,DebertaForSequenceClassification:()=>iF,DebertaForTokenClassification:()=>lF,DebertaModel:()=>aF,DebertaPreTrainedModel:()=>Bs,DebertaV2ForMaskedLM:()=>hF,DebertaV2ForQuestionAnswering:()=>mF,DebertaV2ForSequenceClassification:()=>pF,DebertaV2ForTokenClassification:()=>_F,DebertaV2Model:()=>fF,DebertaV2PreTrainedModel:()=>$s,DecisionTransformerModel:()=>gF,DecisionTransformerPreTrainedModel:()=>b0,DeepseekV3ForCausalLM:()=>dF,DeepseekV3Model:()=>uF,DeepseekV3PreTrainedModel:()=>Fp,DeiTForImageClassification:()=>yF,DeiTModel:()=>wF,DeiTPreTrainedModel:()=>Ip,DepthAnythingForDepthEstimation:()=>vF,DepthAnythingPreTrainedModel:()=>M0,DepthProForDepthEstimation:()=>bF,DepthProPreTrainedModel:()=>x0,DetrForObjectDetection:()=>xF,DetrForSegmentation:()=>TF,DetrModel:()=>MF,DetrObjectDetectionOutput:()=>Lp,DetrPreTrainedModel:()=>Rl,DetrSegmentationOutput:()=>T0,Dinov2ForImageClassification:()=>kF,Dinov2Model:()=>EF,Dinov2PreTrainedModel:()=>Op,Dinov2WithRegistersForImageClassification:()=>AF,Dinov2WithRegistersModel:()=>CF,Dinov2WithRegistersPreTrainedModel:()=>Np,DistilBertForMaskedLM:()=>NF,DistilBertForQuestionAnswering:()=>OF,DistilBertForSequenceClassification:()=>IF,DistilBertForTokenClassification:()=>LF,DistilBertModel:()=>FF,DistilBertPreTrainedModel:()=>Ds,DonutSwinModel:()=>BF,DonutSwinPreTrainedModel:()=>C0,EdgeTamModel:()=>Y3,EfficientNetForImageClassification:()=>zF,EfficientNetModel:()=>RF,EfficientNetPreTrainedModel:()=>$p,ElectraForMaskedLM:()=>UF,ElectraForQuestionAnswering:()=>jF,ElectraForSequenceClassification:()=>VF,ElectraForTokenClassification:()=>WF,ElectraModel:()=>GF,ElectraPreTrainedModel:()=>Rs,Ernie4_5ForCausalLM:()=>HF,Ernie4_5Model:()=>qF,Ernie4_5PretrainedModel:()=>Dp,EsmForMaskedLM:()=>YF,EsmForSequenceClassification:()=>XF,EsmForTokenClassification:()=>JF,EsmModel:()=>QF,EsmPreTrainedModel:()=>ki,EuroBertForMaskedLM:()=>ZF,EuroBertForSequenceClassification:()=>eI,EuroBertForTokenClassification:()=>tI,EuroBertModel:()=>KF,EuroBertPreTrainedModel:()=>Ci,ExaoneForCausalLM:()=>nI,ExaoneModel:()=>rI,ExaonePreTrainedModel:()=>Rp,FalconForCausalLM:()=>aI,FalconH1ForCausalLM:()=>iI,FalconH1Model:()=>oI,FalconH1PreTrainedModel:()=>Gp,FalconModel:()=>sI,FalconPreTrainedModel:()=>zp,FastViTForImageClassification:()=>cI,FastViTModel:()=>lI,FastViTPreTrainedModel:()=>Up,Florence2ForConditionalGeneration:()=>uI,Florence2PreTrainedModel:()=>A0,GLPNForDepthEstimation:()=>CI,GLPNModel:()=>kI,GLPNPreTrainedModel:()=>Xp,GPT2LMHeadModel:()=>$I,GPT2Model:()=>BI,GPT2PreTrainedModel:()=>t_,GPTBigCodeForCausalLM:()=>SI,GPTBigCodeModel:()=>AI,GPTBigCodePreTrainedModel:()=>Jp,GPTJForCausalLM:()=>RI,GPTJModel:()=>DI,GPTJPreTrainedModel:()=>r_,GPTNeoForCausalLM:()=>FI,GPTNeoModel:()=>PI,GPTNeoPreTrainedModel:()=>Kp,GPTNeoXForCausalLM:()=>LI,GPTNeoXModel:()=>II,GPTNeoXPreTrainedModel:()=>Zp,Gemma2ForCausalLM:()=>pI,Gemma2Model:()=>hI,Gemma2PreTrainedModel:()=>Wp,Gemma3ForCausalLM:()=>wI,Gemma3ForConditionalGeneration:()=>F0,Gemma3Model:()=>gI,Gemma3PreTrainedModel:()=>P0,Gemma3nForCausalLM:()=>yI,Gemma3nForConditionalGeneration:()=>zl,Gemma3nPreTrainedModel:()=>I0,Gemma4ForCausalLM:()=>vI,Gemma4ForConditionalGeneration:()=>jp,GemmaForCausalLM:()=>fI,GemmaModel:()=>dI,GemmaPreTrainedModel:()=>Vp,GlmForCausalLM:()=>MI,GlmModel:()=>bI,GlmMoeDsaForCausalLM:()=>TI,GlmMoeDsaModel:()=>xI,GlmMoeDsaPreTrainedModel:()=>Hp,GlmOcrForConditionalGeneration:()=>EI,GlmPreTrainedModel:()=>qp,GptOssForCausalLM:()=>NI,GptOssModel:()=>OI,GptOssPreTrainedModel:()=>e_,GraniteForCausalLM:()=>GI,GraniteModel:()=>zI,GraniteMoeHybridForCausalLM:()=>VI,GraniteMoeHybridModel:()=>UI,GraniteMoeHybridPreTrainedModel:()=>s_,GranitePreTrainedModel:()=>n_,GraniteSpeechForConditionalGeneration:()=>WI,GroundingDinoForObjectDetection:()=>jI,GroundingDinoPreTrainedModel:()=>$0,GroupViTModel:()=>qI,GroupViTPreTrainedModel:()=>D0,HeliumForCausalLM:()=>QI,HeliumModel:()=>HI,HeliumPreTrainedModel:()=>o_,HieraForImageClassification:()=>XI,HieraModel:()=>YI,HieraPreTrainedModel:()=>i_,HubertForCTC:()=>nL,HubertForSequenceClassification:()=>sL,HubertModel:()=>rL,HubertPreTrainedModel:()=>tL,HunYuanDenseV1ForCausalLM:()=>oL,HunYuanDenseV1Model:()=>aL,HunYuanDenseV1PreTrainedModel:()=>l_,IJepaForImageClassification:()=>lL,IJepaModel:()=>iL,IJepaPreTrainedModel:()=>c_,Idefics3ForConditionalGeneration:()=>R0,JAISLMHeadModel:()=>uL,JAISModel:()=>cL,JAISPreTrainedModel:()=>u_,JinaCLIPModel:()=>dL,JinaCLIPPreTrainedModel:()=>Gl,JinaCLIPTextModel:()=>z0,JinaCLIPVisionModel:()=>fL,Lfm2ForCausalLM:()=>pL,Lfm2Model:()=>hL,Lfm2MoeForCausalLM:()=>gL,Lfm2MoeModel:()=>mL,Lfm2MoePreTrainedModel:()=>f_,Lfm2PreTrainedModel:()=>d_,Lfm2VlForConditionalGeneration:()=>wL,LightOnOcrForConditionalGeneration:()=>_L,LiteWhisperForConditionalGeneration:()=>m4,Llama4ForCausalLM:()=>bL,Llama4PreTrainedModel:()=>G0,LlamaForCausalLM:()=>vL,LlamaModel:()=>yL,LlamaPreTrainedModel:()=>h_,LlavaForConditionalGeneration:()=>Vr,LlavaOnevisionForConditionalGeneration:()=>Vr,LlavaPreTrainedModel:()=>S0,LlavaQwen2ForCausalLM:()=>mI,LongT5ForConditionalGeneration:()=>xL,LongT5Model:()=>ML,LongT5PreTrainedModel:()=>p_,M2M100ForConditionalGeneration:()=>EL,M2M100Model:()=>TL,M2M100PreTrainedModel:()=>__,MBartForCausalLM:()=>LL,MBartForConditionalGeneration:()=>FL,MBartForSequenceClassification:()=>IL,MBartModel:()=>PL,MBartPreTrainedModel:()=>Ai,MPNetForMaskedLM:()=>yO,MPNetForQuestionAnswering:()=>MO,MPNetForSequenceClassification:()=>vO,MPNetForTokenClassification:()=>bO,MPNetModel:()=>wO,MPNetPreTrainedModel:()=>zs,MT5ForConditionalGeneration:()=>kO,MT5Model:()=>EO,MT5PreTrainedModel:()=>k_,MarianMTModel:()=>CL,MarianModel:()=>kL,MarianPreTrainedModel:()=>m_,MaskFormerForInstanceSegmentation:()=>SL,MaskFormerModel:()=>AL,MaskFormerPreTrainedModel:()=>g_,Metric3DForDepthEstimation:()=>OL,Metric3DPreTrainedModel:()=>U0,Metric3Dv2ForDepthEstimation:()=>NL,Metric3Dv2PreTrainedModel:()=>V0,MgpstrForSceneTextRecognition:()=>BL,MgpstrModelOutput:()=>W0,MgpstrPreTrainedModel:()=>j0,MimiDecoderModel:()=>Y0,MimiDecoderOutput:()=>H0,MimiEncoderModel:()=>Q0,MimiEncoderOutput:()=>q0,MimiModel:()=>$L,MimiPreTrainedModel:()=>Ul,Mistral4ForCausalLM:()=>GL,Mistral4Model:()=>zL,Mistral4PreTrainedModel:()=>y_,MistralForCausalLM:()=>RL,MistralModel:()=>DL,MistralPreTrainedModel:()=>w_,MobileBertForMaskedLM:()=>VL,MobileBertForQuestionAnswering:()=>jL,MobileBertForSequenceClassification:()=>WL,MobileBertModel:()=>UL,MobileBertPreTrainedModel:()=>Si,MobileLLMForCausalLM:()=>HL,MobileLLMModel:()=>qL,MobileLLMPreTrainedModel:()=>v_,MobileNetV1ForImageClassification:()=>YL,MobileNetV1ForSemanticSegmentation:()=>XL,MobileNetV1Model:()=>QL,MobileNetV1PreTrainedModel:()=>Vl,MobileNetV2ForImageClassification:()=>KL,MobileNetV2ForSemanticSegmentation:()=>ZL,MobileNetV2Model:()=>JL,MobileNetV2PreTrainedModel:()=>Wl,MobileNetV3ForImageClassification:()=>tO,MobileNetV3ForSemanticSegmentation:()=>rO,MobileNetV3Model:()=>eO,MobileNetV3PreTrainedModel:()=>jl,MobileNetV4ForImageClassification:()=>sO,MobileNetV4ForSemanticSegmentation:()=>aO,MobileNetV4Model:()=>nO,MobileNetV4PreTrainedModel:()=>ql,MobileViTForImageClassification:()=>iO,MobileViTModel:()=>oO,MobileViTPreTrainedModel:()=>b_,MobileViTV2ForImageClassification:()=>cO,MobileViTV2Model:()=>lO,MobileViTV2PreTrainedModel:()=>M_,ModernBertDecoderForCausalLM:()=>_O,ModernBertDecoderModel:()=>pO,ModernBertDecoderPreTrainedModel:()=>x_,ModernBertForMaskedLM:()=>dO,ModernBertForSequenceClassification:()=>fO,ModernBertForTokenClassification:()=>hO,ModernBertModel:()=>uO,ModernBertPreTrainedModel:()=>Pi,Moondream1ForConditionalGeneration:()=>_I,MoonshineForConditionalGeneration:()=>gO,MoonshineModel:()=>mO,MoonshinePreTrainedModel:()=>T_,MptForCausalLM:()=>TO,MptModel:()=>xO,MptPreTrainedModel:()=>E_,MultiModalityCausalLM:()=>CO,MultiModalityPreTrainedModel:()=>X0,MusicgenForCausalLM:()=>SO,MusicgenForConditionalGeneration:()=>J0,MusicgenModel:()=>AO,MusicgenPreTrainedModel:()=>C_,NanoChatForCausalLM:()=>FO,NanoChatModel:()=>PO,NanoChatPreTrainedModel:()=>A_,NemotronHForCausalLM:()=>LO,NemotronHModel:()=>IO,NemotronHPreTrainedModel:()=>S_,NeoBertForMaskedLM:()=>NO,NeoBertForQuestionAnswering:()=>DO,NeoBertForSequenceClassification:()=>BO,NeoBertForTokenClassification:()=>$O,NeoBertModel:()=>OO,NeoBertPreTrainedModel:()=>Gs,NomicBertModel:()=>RO,NomicBertPreTrainedModel:()=>K0,OPTForCausalLM:()=>ZO,OPTModel:()=>KO,OPTPreTrainedModel:()=>B_,Olmo2ForCausalLM:()=>VO,Olmo2Model:()=>UO,Olmo2PreTrainedModel:()=>F_,Olmo3ForCausalLM:()=>jO,Olmo3Model:()=>WO,Olmo3PreTrainedModel:()=>I_,OlmoForCausalLM:()=>GO,OlmoHybridForCausalLM:()=>HO,OlmoHybridModel:()=>qO,OlmoHybridPreTrainedModel:()=>L_,OlmoModel:()=>zO,OlmoPreTrainedModel:()=>P_,OpenAIPrivacyFilterForTokenClassification:()=>YO,OpenAIPrivacyFilterModel:()=>QO,OpenAIPrivacyFilterPreTrainedModel:()=>O_,OpenELMForCausalLM:()=>JO,OpenELMModel:()=>XO,OpenELMPreTrainedModel:()=>N_,OwlViTForObjectDetection:()=>n3,OwlViTModel:()=>r3,OwlViTPreTrainedModel:()=>D_,Owlv2ForObjectDetection:()=>t3,Owlv2Model:()=>e3,Owlv2PreTrainedModel:()=>$_,PaliGemmaForConditionalGeneration:()=>s3,ParakeetForCTC:()=>a3,ParakeetPreTrainedModel:()=>Z0,PatchTSMixerForPrediction:()=>i3,PatchTSMixerModel:()=>o3,PatchTSMixerPreTrainedModel:()=>R_,PatchTSTForPrediction:()=>c3,PatchTSTModel:()=>l3,PatchTSTPreTrainedModel:()=>z_,Phi3ForCausalLM:()=>h3,Phi3Model:()=>f3,Phi3PreTrainedModel:()=>U_,Phi3VForCausalLM:()=>tb,Phi3VPreTrainedModel:()=>eb,PhiForCausalLM:()=>d3,PhiModel:()=>u3,PhiPreTrainedModel:()=>G_,PreTrainedModel:()=>O,PvtForImageClassification:()=>_3,PvtModel:()=>p3,PvtPreTrainedModel:()=>V_,PyAnnoteForAudioFrameClassification:()=>g3,PyAnnoteModel:()=>m3,PyAnnotePreTrainedModel:()=>W_,Qwen2ForCausalLM:()=>y3,Qwen2Model:()=>w3,Qwen2MoeForCausalLM:()=>b3,Qwen2MoeModel:()=>v3,Qwen2MoePreTrainedModel:()=>q_,Qwen2PreTrainedModel:()=>j_,Qwen2VLForCausalLM:()=>O0,Qwen2VLForConditionalGeneration:()=>Qp,Qwen2VLPreTrainedModel:()=>L0,Qwen2_5_VLForCausalLM:()=>N0,Qwen2_5_VLForConditionalGeneration:()=>Yp,Qwen3ForCausalLM:()=>x3,Qwen3Model:()=>M3,Qwen3MoeForCausalLM:()=>E3,Qwen3MoeModel:()=>T3,Qwen3MoePreTrainedModel:()=>Q_,Qwen3NextForCausalLM:()=>C3,Qwen3NextModel:()=>k3,Qwen3NextPreTrainedModel:()=>Y_,Qwen3PreTrainedModel:()=>H_,Qwen3VLForCausalLM:()=>rb,Qwen3VLForConditionalGeneration:()=>X_,Qwen3VLMoeForCausalLM:()=>S3,Qwen3VLMoeForConditionalGeneration:()=>A3,Qwen3_5ForCausalLM:()=>nb,Qwen3_5ForConditionalGeneration:()=>J_,Qwen3_5MoeForCausalLM:()=>F3,Qwen3_5MoeForConditionalGeneration:()=>P3,RFDetrForObjectDetection:()=>N3,RFDetrModel:()=>O3,RFDetrObjectDetectionOutput:()=>sb,RFDetrPreTrainedModel:()=>Z_,RTDetrForObjectDetection:()=>tF,RTDetrModel:()=>eF,RTDetrObjectDetectionOutput:()=>Ei,RTDetrPreTrainedModel:()=>Sp,RTDetrV2ForObjectDetection:()=>H3,RTDetrV2Model:()=>q3,RTDetrV2ObjectDetectionOutput:()=>ab,RTDetrV2PreTrainedModel:()=>em,ResNetForImageClassification:()=>L3,ResNetModel:()=>I3,ResNetPreTrainedModel:()=>K_,RoFormerForMaskedLM:()=>U3,RoFormerForQuestionAnswering:()=>j3,RoFormerForSequenceClassification:()=>V3,RoFormerForTokenClassification:()=>W3,RoFormerModel:()=>G3,RoFormerPreTrainedModel:()=>Vs,RobertaForMaskedLM:()=>$3,RobertaForQuestionAnswering:()=>z3,RobertaForSequenceClassification:()=>D3,RobertaForTokenClassification:()=>R3,RobertaModel:()=>B3,RobertaPreTrainedModel:()=>Us,Sam2ImageSegmentationOutput:()=>lb,Sam2Model:()=>tm,Sam2PreTrainedModel:()=>cb,Sam3TrackerModel:()=>X3,SamImageSegmentationOutput:()=>ob,SamModel:()=>Q3,SamPreTrainedModel:()=>ib,SapiensForDepthEstimation:()=>K3,SapiensForNormalEstimation:()=>Z3,SapiensForSemanticSegmentation:()=>J3,SapiensPreTrainedModel:()=>Hl,SegformerForImageClassification:()=>tN,SegformerForSemanticSegmentation:()=>rN,SegformerModel:()=>eN,SegformerPreTrainedModel:()=>Ql,SiglipModel:()=>nN,SiglipPreTrainedModel:()=>rm,SiglipTextModel:()=>ub,SiglipVisionModel:()=>sN,SmolLM3ForCausalLM:()=>oN,SmolLM3Model:()=>aN,SmolLM3PreTrainedModel:()=>nm,SmolVLMForConditionalGeneration:()=>iN,SnacDecoderModel:()=>fb,SnacEncoderModel:()=>db,SnacModel:()=>lN,SnacPreTrainedModel:()=>Yl,SolarOpenForCausalLM:()=>uN,SolarOpenModel:()=>cN,SolarOpenPreTrainedModel:()=>sm,SpeechT5ForSpeechToText:()=>fN,SpeechT5ForTextToSpeech:()=>hN,SpeechT5HifiGan:()=>pN,SpeechT5Model:()=>dN,SpeechT5PreTrainedModel:()=>Xl,SqueezeBertForMaskedLM:()=>mN,SqueezeBertForQuestionAnswering:()=>wN,SqueezeBertForSequenceClassification:()=>gN,SqueezeBertModel:()=>_N,SqueezeBertPreTrainedModel:()=>Fi,StableLmForCausalLM:()=>vN,StableLmModel:()=>yN,StableLmPreTrainedModel:()=>am,Starcoder2ForCausalLM:()=>MN,Starcoder2Model:()=>bN,Starcoder2PreTrainedModel:()=>om,StyleTextToSpeech2Model:()=>xN,StyleTextToSpeech2PreTrainedModel:()=>hb,SupertonicForConditionalGeneration:()=>_b,SupertonicPreTrainedModel:()=>pb,Swin2SRForImageSuperResolution:()=>AN,Swin2SRModel:()=>CN,Swin2SRPreTrainedModel:()=>im,SwinForImageClassification:()=>EN,SwinForSemanticSegmentation:()=>kN,SwinModel:()=>TN,SwinPreTrainedModel:()=>Jl,T5ForConditionalGeneration:()=>PN,T5Model:()=>SN,T5PreTrainedModel:()=>lm,TableTransformerForObjectDetection:()=>IN,TableTransformerModel:()=>FN,TableTransformerObjectDetectionOutput:()=>mb,TableTransformerPreTrainedModel:()=>cm,TrOCRForCausalLM:()=>LN,TrOCRPreTrainedModel:()=>gb,UltravoxModel:()=>a_,UltravoxPreTrainedModel:()=>B0,UniSpeechForCTC:()=>NN,UniSpeechForSequenceClassification:()=>BN,UniSpeechModel:()=>ON,UniSpeechPreTrainedModel:()=>Kl,UniSpeechSatForAudioFrameClassification:()=>zN,UniSpeechSatForCTC:()=>DN,UniSpeechSatForSequenceClassification:()=>RN,UniSpeechSatModel:()=>$N,UniSpeechSatPreTrainedModel:()=>Ii,VaultGemmaForCausalLM:()=>UN,VaultGemmaModel:()=>GN,VaultGemmaPreTrainedModel:()=>um,ViTForImageClassification:()=>jN,ViTMAEModel:()=>qN,ViTMAEPreTrainedModel:()=>wb,ViTMSNForImageClassification:()=>QN,ViTMSNModel:()=>HN,ViTMSNPreTrainedModel:()=>fm,ViTModel:()=>WN,ViTPreTrainedModel:()=>dm,VisionEncoderDecoderModel:()=>VN,VitMatteForImageMatting:()=>YN,VitMattePreTrainedModel:()=>yb,VitPoseForPoseEstimation:()=>XN,VitPosePreTrainedModel:()=>vb,VitsModel:()=>JN,VitsModelOutput:()=>bb,VitsPreTrainedModel:()=>Mb,VoxtralForConditionalGeneration:()=>KN,VoxtralRealtimeForConditionalGeneration:()=>Tb,VoxtralRealtimePreTrainedModel:()=>xb,Wav2Vec2BertForCTC:()=>o4,Wav2Vec2BertForSequenceClassification:()=>i4,Wav2Vec2BertModel:()=>a4,Wav2Vec2BertPreTrainedModel:()=>Zl,Wav2Vec2ForAudioFrameClassification:()=>eL,Wav2Vec2ForCTC:()=>KI,Wav2Vec2ForSequenceClassification:()=>ZI,Wav2Vec2Model:()=>JI,Wav2Vec2PreTrainedModel:()=>cn,WavLMForAudioFrameClassification:()=>f4,WavLMForCTC:()=>c4,WavLMForSequenceClassification:()=>u4,WavLMForXVector:()=>d4,WavLMModel:()=>l4,WavLMPreTrainedModel:()=>Ws,WeSpeakerResNetModel:()=>h4,WeSpeakerResNetPreTrainedModel:()=>kb,WhisperForConditionalGeneration:()=>Cb,WhisperModel:()=>_4,WhisperPreTrainedModel:()=>hm,XLMForQuestionAnswering:()=>b4,XLMForSequenceClassification:()=>y4,XLMForTokenClassification:()=>v4,XLMModel:()=>g4,XLMPreTrainedModel:()=>js,XLMRobertaForMaskedLM:()=>x4,XLMRobertaForQuestionAnswering:()=>k4,XLMRobertaForSequenceClassification:()=>T4,XLMRobertaForTokenClassification:()=>E4,XLMRobertaModel:()=>M4,XLMRobertaPreTrainedModel:()=>qs,XLMWithLMHeadModel:()=>w4,XVectorOutput:()=>Eb,YolosForObjectDetection:()=>A4,YolosModel:()=>C4,YolosObjectDetectionOutput:()=>Ab,YolosPreTrainedModel:()=>pm,YoutuForCausalLM:()=>P4,YoutuModel:()=>S4,YoutuPreTrainedModel:()=>_m});var Ti=class extends O{},QS=class extends Ti{},YS=class extends Ti{async _call(e){return new fe(await super._call(e))}},XS=class extends Ti{async _call(e){return new Ft(await super._call(e))}},JS=class extends Ti{async _call(e){return new mt(await super._call(e))}},pp=class extends O{},KS=class extends pp{},ZS=class extends pp{},_p=class extends O{},eP=class extends _p{},tP=class extends _p{},mp=class extends O{},rP=class extends mp{},nP=class extends mp{},gp=class extends O{},sP=class extends gp{},aP=class extends gp{},Bl=class extends O{},oP=class extends Bl{},iP=class extends Bl{},lP=class extends Bl{async _call(e){return new fe(await super._call(e))}},wp=class extends O{},cP=class extends wp{},uP=class extends wp{async _call(e){return new fe(await super._call(e))}},Ls=class extends O{},dP=class extends Ls{},fP=class extends Ls{async _call(e){return new mt(await super._call(e))}},hP=class extends Ls{async _call(e){return new fe(await super._call(e))}},pP=class extends Ls{async _call(e){return new at(await super._call(e))}},_P=class extends Ls{async _call(e){return new Ft(await super._call(e))}},yp=class extends O{},mP=class extends yp{},gP=class extends yp{},vp=class extends O{},wP=class extends vp{},yP=class extends vp{},bp=class extends O{},vP=class extends bp{},bP=class extends bp{},Os=class extends O{},MP=class extends Os{},xP=class extends Os{async _call(e){return new mt(await super._call(e))}},TP=class extends Os{async _call(e){return new fe(await super._call(e))}},EP=class extends Os{async _call(e){return new at(await super._call(e))}},kP=class extends Os{async _call(e){return new Ft(await super._call(e))}},CP=4299n,rw=6561n,u0=class extends O{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},d0=class extends u0{async encode_speech(e){return Pe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:c=null,logits_processor:u=null,audio_features:h=null,audio_tokens:p=null,speaker_embeddings:_=null,speaker_features:m=null,...w}){let b;if(!a){const E=this.sessions.embed_tokens.inputNames,T={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof K)){const C=e.dims[0];if(n==null)n=At([C],.5);else if(typeof n=="number")n=At([C],n);else if(Array.isArray(n))n=new K("float32",n,[C]);else throw new Error("Unsupported type for `exaggeration` input")}T.exaggeration=n}if(E.includes("position_ids")&&(T.position_ids=s),{inputs_embeds:a}=await Pe(this.sessions.embed_tokens,T),h&&p&&_&&m&&(b={audio_features:h,audio_tokens:p,speaker_embeddings:_,speaker_features:m}),b||r)b??=await this.encode_speech(r),a=je([b.audio_features,a],1),t=Ot([a.dims[0],a.dims[1]]);else{const C=a.dims[1];if(!i||C!==1)throw new Error("Incorrect state encountered during generation.");const P=i.get_seq_length();t=Ot([a.dims[0],P+C])}}return{...await Ur(this,{inputs_embeds:a,past_key_values:i,attention_mask:t,generation_config:c,logits_processor:u},!1),...b}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const n=Array.from({length:e.length},(s,a)=>e[a].length-e[a].findLastIndex(i=>i==rw)-1);t.position_ids=new K("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let i=0;return a.map(c=>c>=rw?0:i++)});t.position_ids=new K("int64",s.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),mi(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:n,speaker_features:s}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),i=At([a.dims[0],3],CP),c=je([r,a,i],1),{waveform:u}=await Pe(this.sessions.conditional_decoder,{speech_tokens:c,speaker_features:s,speaker_embeddings:n});return u}},f0=class extends O{},AP=class extends f0{},h0=class extends O{},SP=class extends h0{},$l=class extends O{},PP=class extends $l{},p0=class extends $l{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_0=class extends $l{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},os=class extends O{},FP=class extends os{},IP=class extends os{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},m0=class extends os{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},LP=class extends os{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},OP=class extends os{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Mp=class extends O{},NP=class extends Mp{},BP=class extends Mp{},xp=class extends O{},$P=class extends xp{},DP=class extends xp{},Tp=class extends O{},RP=class extends Tp{},zP=class extends Tp{},Ep=class extends O{},GP=class extends Ep{},UP=class extends Ep{},kp=class extends O{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},VP=class extends kp{},WP=class extends kp{},Ns=class extends O{},jP=class extends Ns{},qP=class extends Ns{async _call(e){return new mt(await super._call(e))}},HP=class extends Ns{async _call(e){return new fe(await super._call(e))}},QP=class extends Ns{async _call(e){return new at(await super._call(e))}},YP=class extends Ns{async _call(e){return new Ft(await super._call(e))}},Cp=class extends O{},XP=class extends Cp{},JP=class extends Cp{async _call(e){return new fe(await super._call(e))}},Ap=class extends O{},KP=class extends Ap{},ZP=class extends Ap{async _call(e){return new fe(await super._call(e))}},Sp=class extends O{},eF=class extends Sp{},tF=class extends Sp{async _call(e){return new Ei(await super._call(e))}},Ei=class extends _t{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Pp=class extends O{},rF=class extends Pp{},nF=class extends Pp{async _call(e){return new Ei(await super._call(e))}},g0=class extends _t{constructor({audio_codes:e}){super(),this.audio_codes=e}},w0=class extends _t{constructor({audio_values:e}){super(),this.audio_values=e}},Dl=class extends O{main_input_name="input_values";forward_params=["input_values"]},sF=class extends Dl{async encode(e){return new g0(await Pe(this.sessions.encoder_model,e))}async decode(e){return new w0(await Pe(this.sessions.decoder_model,e))}},y0=class extends Dl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},v0=class extends Dl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Bs=class extends O{},aF=class extends Bs{},oF=class extends Bs{async _call(e){return new mt(await super._call(e))}},iF=class extends Bs{async _call(e){return new fe(await super._call(e))}},lF=class extends Bs{async _call(e){return new at(await super._call(e))}},cF=class extends Bs{async _call(e){return new Ft(await super._call(e))}},Fp=class extends O{},uF=class extends Fp{},dF=class extends Fp{},$s=class extends O{},fF=class extends $s{},hF=class extends $s{async _call(e){return new mt(await super._call(e))}},pF=class extends $s{async _call(e){return new fe(await super._call(e))}},_F=class extends $s{async _call(e){return new at(await super._call(e))}},mF=class extends $s{async _call(e){return new Ft(await super._call(e))}},b0=class extends O{},gF=class extends b0{},Ip=class extends O{},wF=class extends Ip{},yF=class extends Ip{async _call(e){return new fe(await super._call(e))}},M0=class extends O{},vF=class extends M0{},x0=class extends O{},bF=class extends x0{},Rl=class extends O{},MF=class extends Rl{},xF=class extends Rl{async _call(e){return new Lp(await super._call(e))}},TF=class extends Rl{async _call(e){return new T0(await super._call(e))}},Lp=class extends _t{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},T0=class extends _t{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},Op=class extends O{},EF=class extends Op{},kF=class extends Op{async _call(e){return new fe(await super._call(e))}},Np=class extends O{},CF=class extends Np{},AF=class extends Np{async _call(e){return new fe(await super._call(e))}},E0=class extends O{},SF=class extends E0{},k0=class extends O{},PF=class extends k0{},Ds=class extends O{},FF=class extends Ds{},IF=class extends Ds{async _call(e){return new fe(await super._call(e))}},LF=class extends Ds{async _call(e){return new at(await super._call(e))}},OF=class extends Ds{async _call(e){return new Ft(await super._call(e))}},NF=class extends Ds{async _call(e){return new mt(await super._call(e))}},C0=class extends O{},BF=class extends C0{},Bp=class extends O{},$F=class extends Bp{},DF=class extends Bp{},$p=class extends O{},RF=class extends $p{},zF=class extends $p{async _call(e){return new fe(await super._call(e))}},Rs=class extends O{},GF=class extends Rs{},UF=class extends Rs{async _call(e){return new mt(await super._call(e))}},VF=class extends Rs{async _call(e){return new fe(await super._call(e))}},WF=class extends Rs{async _call(e){return new at(await super._call(e))}},jF=class extends Rs{async _call(e){return new Ft(await super._call(e))}},Dp=class extends O{},qF=class extends Dp{},HF=class extends Dp{},ki=class extends O{},QF=class extends ki{},YF=class extends ki{async _call(e){return new mt(await super._call(e))}},XF=class extends ki{async _call(e){return new fe(await super._call(e))}},JF=class extends ki{async _call(e){return new at(await super._call(e))}},Ci=class extends O{},KF=class extends Ci{},ZF=class extends Ci{async _call(e){return new mt(await super._call(e))}},eI=class extends Ci{async _call(e){return new fe(await super._call(e))}},tI=class extends Ci{async _call(e){return new at(await super._call(e))}},Rp=class extends O{},rI=class extends Rp{},nI=class extends Rp{},zp=class extends O{},sI=class extends zp{},aI=class extends zp{},Gp=class extends O{},oI=class extends Gp{},iI=class extends Gp{},Up=class extends O{},lI=class extends Up{},cI=class extends Up{async _call(e){return new fe(await super._call(e))}},A0=class extends O{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},uI=class extends A0{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:je([t,e],1),attention_mask:je([Ot(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:n}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let s,a;return e&&(s=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),s&&a?{inputs_embeds:r,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:s,image_features:a,input_ids:e,attention_mask:n}):r=s||a,{inputs_embeds:r,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:n,decoder_attention_mask:s,encoder_outputs:a,past_key_values:i,inputs_embeds:c,decoder_inputs_embeds:u}){if(c||({inputs_embeds:c,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:c,attention_mask:r})),!a){let{last_hidden_state:p}=await ln(this,{inputs_embeds:c,attention_mask:r});a=p}if(!u){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");u=await this.encode_text({input_ids:n})}return await Ur(this,{inputs_embeds:u,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:i},!0)}},Vp=class extends O{},dI=class extends Vp{},fI=class extends Vp{},Wp=class extends O{},hI=class extends Wp{},pI=class extends Wp{},S0=class extends O{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Vr=class extends S0{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return fp({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},_I=class extends Vr{},mI=class extends Vr{},P0=class extends O{},gI=class extends P0{},F0=class extends Vr{},wI=class extends F0{},I0=class extends O{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},zl=class extends I0{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:n=null,input_features_mask:s=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:c=null,past_key_values:u=null,generation_config:h=null,logits_processor:p=null,..._}){if((!i||!c)&&({inputs_embeds:i,per_layer_inputs:c}=await Pe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:w}=await this._encode_vision({pixel_values:r,..._});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:t}))}if(n){const{audio_features:w}=await Pe(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:t}))}}return await Ur(this,{inputs_embeds:i,per_layer_inputs:c,past_key_values:u,attention_mask:t,position_ids:a,generation_config:h,logits_processor:p},!0)}_encode_vision(e){return Pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return fp({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return c0({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},yI=class extends zl{},jp=class extends zl{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return Pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},vI=class extends jp{},qp=class extends O{},bI=class extends qp{},MI=class extends qp{},Hp=class extends O{},xI=class extends Hp{},TI=class extends Hp{},L0=class extends O{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Qp=class extends L0{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){const{data:r,dims:n}=i0(t),s=BigInt64Array.from({length:3*r.length},(i,c)=>r[c%r.length]),a=Array.from({length:n[0]},(i,c)=>pt(r.subarray(n[1]*c,n[1]*(c+1)))[0]+1n+BigInt(n[1]));return[new K("int64",s,[3,...n]),new K("int64",a,[a.length,1])]}else{const[r,n]=e.dims,s=BigInt64Array.from({length:3*r*n},(a,i)=>BigInt(Math.floor(i%n/r)));return[new K("int64",s,[3,...e.dims]),lv([r,1])]}}_reorder_and_write_positions(e,t,r,n){const s=e.reduce((u,h)=>u+h.length,0),a=new Array(s);let i=0;for(let u=0;u<3;++u)for(const h of e){const p=h.length/3;for(let _=u*p;_<(u+1)*p;++_)a[i++]=h[_]}let c=0;for(let u=0;u(C==c&&T.push(P),T),[]).map(T=>u[T+1]),_=p.filter(T=>T==a).length,m=p.filter(T=>T==i).length,w=[];let b=0,M=_,E=m;for(let T=0;TQ>b&&z==a),P=u.findIndex((z,Q)=>Q>b&&z==i),A=M>0&&C!==-1?C:u.length+1,F=E>0&&P!==-1?P:u.length+1;let G,v,j,U;A0?pt(w.at(-1))[0]+1:0;w.push(Array.from({length:3*I},(z,Q)=>S+Q%I));const D=I+S,Y=q*ne*H,se=Array.from({length:Y},(z,Q)=>D+Math.floor(Q/(ne*H))),N=Array.from({length:Y},(z,Q)=>D+Math.floor(Q/H)%ne),$=Array.from({length:Y},(z,Q)=>D+Q%H);w.push([se,N,$].flat()),b=G+Y}if(b0?pt(w.at(-1))[0]+1:0,C=u.length-b;w.push(Array.from({length:3*C},(P,A)=>T+A%C))}return w}get_rope_index(e,t,r,n){const{vision_config:s}=this.config,a=s.spatial_merge_size??2;if(t||r){const i=e.tolist();n||(n=iv(e));const c=n.tolist(),u=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),h=t?t.tolist():[],p=r?r.tolist():[],_={image_index:0,video_index:0},m=[];for(let w=0;wc[w][C]==1),M=this._get_multimodal_rope_positions({filtered_ids:b,image_grid_thw_list:h,video_grid_thw_list:p,spatial_merge_size:a,state:_}),E=this._reorder_and_write_positions(M,c[w],u,w);m.push(pt(E)[0]+1-i[w].length)}return[new K("int64",u.flat(1/0),[3,e.dims[0],e.dims[1]]),new K("int64",m,[m.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await Pe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return fp({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const s=t.past_key_values.get_seq_length();if(sa+c);t.position_ids=Gr([i,i,i],0)}}return t}},O0=class extends Qp{},Yp=class extends Qp{image_grid_thw_name="image_grid_thw"},N0=class extends O0{image_grid_thw_name="image_grid_thw"},EI=class extends Yp{get_vision_position_ids(e,t,r,n){const s=Math.floor(t[0]/r),a=Math.floor(t[1]/n),i=Math.floor(t[2]/n),c=a*i*s,u=Array.from({length:c},()=>e),h=Array.from({length:c},(_,m)=>e+Math.floor(m/(i*s))),p=Array.from({length:c},(_,m)=>e+m%i);return[...u,...h,...p]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:n,state:s}){const{image_token_id:a}=this.config,i=[];let c=0,u=e[0]==a?1:0;for(let _=1;_<=e.length;++_){const m=_h+E%b)),h+=b}else{const b=t[s.image_index++].map(Number),M=b[0];p.push(this.get_vision_position_ids(h,b,M,n)),h+=Math.max(b[1],b[2])/n}return p}},Xp=class extends O{},kI=class extends Xp{},CI=class extends Xp{},Jp=class extends O{},AI=class extends Jp{},SI=class extends Jp{},Kp=class extends O{},PI=class extends Kp{},FI=class extends Kp{},Zp=class extends O{},II=class extends Zp{},LI=class extends Zp{},e_=class extends O{},OI=class extends e_{},NI=class extends e_{},t_=class extends O{},BI=class extends t_{},$I=class extends t_{},r_=class extends O{},DI=class extends r_{},RI=class extends r_{},n_=class extends O{},zI=class extends n_{},GI=class extends n_{},s_=class extends O{},UI=class extends s_{},VI=class extends s_{},B0=class extends O{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},a_=class extends B0{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return c0({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},WI=class extends a_{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},$0=class extends O{},jI=class extends $0{},D0=class extends O{},qI=class extends D0{},o_=class extends O{},HI=class extends o_{},QI=class extends o_{},i_=class extends O{},YI=class extends i_{},XI=class extends i_{async _call(e){return new fe(await super._call(e))}},cn=class extends O{},JI=class extends cn{},KI=class extends cn{async _call(e){return new as(await super._call(e))}},ZI=class extends cn{async _call(e){return new fe(await super._call(e))}},eL=class extends cn{async _call(e){return new at(await super._call(e))}},tL=class extends O{},rL=class extends cn{},nL=class extends cn{async _call(e){return new as(await super._call(e))}},sL=class extends cn{async _call(e){return new fe(await super._call(e))}},l_=class extends O{},aL=class extends l_{},oL=class extends l_{},R0=class extends Vr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},c_=class extends O{},iL=class extends c_{},lL=class extends c_{async _call(e){return new fe(await super._call(e))}},u_=class extends O{},cL=class extends u_{},uL=class extends u_{},Gl=class extends O{},dL=class extends Gl{async forward(e){const t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=Ot([e.pixel_values.dims[0],1])),r){const{image_size:u}=this.config.vision_config;e.pixel_values=At([0,3,u,u],0)}const{text_embeddings:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),c={};return t||(c.text_embeddings=n,c.l2norm_text_embeddings=a),r||(c.image_embeddings=s,c.l2norm_image_embeddings=i),c}},z0=class extends Gl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},fL=class extends Gl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},d_=class extends O{},hL=class extends d_{},pL=class extends d_{},_L=class extends Vr{},f_=class extends O{},mL=class extends f_{},gL=class extends f_{},wL=class extends Vr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},h_=class extends O{},yL=class extends h_{},vL=class extends h_{},G0=class extends O{},bL=class extends G0{},p_=class extends O{},ML=class extends p_{},xL=class extends p_{},__=class extends O{},TL=class extends __{},EL=class extends __{},m_=class extends O{},kL=class extends m_{},CL=class extends m_{},g_=class extends O{},AL=class extends g_{},SL=class extends g_{},Ai=class extends O{},PL=class extends Ai{},FL=class extends Ai{},IL=class extends Ai{async _call(e){return new fe(await super._call(e))}},LL=class extends Ai{},U0=class extends O{},OL=class extends U0{},V0=class extends O{},NL=class extends V0{},W0=class extends _t{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},j0=class extends O{},BL=class extends j0{async _call(e){return new W0(await super._call(e))}},q0=class extends _t{constructor({audio_codes:e}){super(),this.audio_codes=e}},H0=class extends _t{constructor({audio_values:e}){super(),this.audio_values=e}},Ul=class extends O{main_input_name="input_values";forward_params=["input_values"]},$L=class extends Ul{async encode(e){return new q0(await Pe(this.sessions.encoder_model,e))}async decode(e){return new H0(await Pe(this.sessions.decoder_model,e))}},Q0=class extends Ul{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Y0=class extends Ul{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},w_=class extends O{},DL=class extends w_{},RL=class extends w_{},y_=class extends O{},zL=class extends y_{},GL=class extends y_{},Si=class extends O{},UL=class extends Si{},VL=class extends Si{async _call(e){return new mt(await super._call(e))}},WL=class extends Si{async _call(e){return new fe(await super._call(e))}},jL=class extends Si{async _call(e){return new Ft(await super._call(e))}},v_=class extends O{},qL=class extends v_{},HL=class extends v_{},Vl=class extends O{},QL=class extends Vl{},YL=class extends Vl{async _call(e){return new fe(await super._call(e))}},XL=class extends Vl{},Wl=class extends O{},JL=class extends Wl{},KL=class extends Wl{async _call(e){return new fe(await super._call(e))}},ZL=class extends Wl{},jl=class extends O{},eO=class extends jl{},tO=class extends jl{async _call(e){return new fe(await super._call(e))}},rO=class extends jl{},ql=class extends O{},nO=class extends ql{},sO=class extends ql{async _call(e){return new fe(await super._call(e))}},aO=class extends ql{},b_=class extends O{},oO=class extends b_{},iO=class extends b_{async _call(e){return new fe(await super._call(e))}},M_=class extends O{},lO=class extends M_{},cO=class extends M_{async _call(e){return new fe(await super._call(e))}},Pi=class extends O{},uO=class extends Pi{},dO=class extends Pi{async _call(e){return new mt(await super._call(e))}},fO=class extends Pi{async _call(e){return new fe(await super._call(e))}},hO=class extends Pi{async _call(e){return new at(await super._call(e))}},x_=class extends O{},pO=class extends x_{},_O=class extends x_{},T_=class extends O{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},mO=class extends T_{},gO=class extends T_{},zs=class extends O{},wO=class extends zs{},yO=class extends zs{async _call(e){return new mt(await super._call(e))}},vO=class extends zs{async _call(e){return new fe(await super._call(e))}},bO=class extends zs{async _call(e){return new at(await super._call(e))}},MO=class extends zs{async _call(e){return new Ft(await super._call(e))}},E_=class extends O{},xO=class extends E_{},TO=class extends E_{},k_=class extends O{},EO=class extends k_{},kO=class extends k_{},X0=class extends O{},CO=class extends X0{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let r;if(t==="text"||!e.past_key_values){const c=this.sessions.prepare_inputs_embeds,u=xt(e,c.inputNames);r=await Pe(c,u)}else{const c=this.sessions.gen_img_embeds,u=xt({image_ids:e.input_ids},c.inputNames);r=await Pe(c,u)}const n={...e,...r},s=await Ur(this,n),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);const i=await Pe(a,xt(s,a.inputNames));return{...r,...s,...i}}prepare_inputs_for_generation(e,t,r){const n=!!t.past_key_values;return r.guidance_scale!==null&&r.guidance_scale>1&&(n?t.input_ids=je([t.input_ids,t.input_ids],0):(t.input_ids=je([t.input_ids,dh(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=je([t.attention_mask,dh(t.attention_mask,0n)],0))),(n||!t.pixel_values)&&(t.pixel_values=At([0,0,3,384,384],1)),n&&(t.images_seq_mask=new K("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new K("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),s=this.sessions.image_decode,{decoded_image:a}=await Pe(s,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),c=[];for(const u of i){const h=yi.fromTensor(u);c.push(h)}return c}},C_=class extends O{},AO=class extends C_{},SO=class extends C_{},J0=class extends O{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,r]=e.dims,n=this.config.decoder.num_codebooks,s=r-n;let a=0;for(let u=0;u0&&_<=s&&(e.data[a++]=e.data[u])}const i=Math.floor(t/n),c=a/(i*n);return new K(e.type,e.data.slice(0,a),[i,n,c])}prepare_inputs_for_generation(e,t,r){const n=BigInt(this.config.decoder.pad_token_id);let s=structuredClone(e);for(let a=0;a=i&&(s[a][i]=n);return r.guidance_scale!==null&&r.guidance_scale>1&&(s=s.concat(s)),vl(this,s,t)}async generate(e){const t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:n}=await Pe(this.sessions.encodec_decode,{audio_codes:r});return n}},A_=class extends O{},PO=class extends A_{},FO=class extends A_{},S_=class extends O{},IO=class extends S_{},LO=class extends S_{},Gs=class extends O{},OO=class extends Gs{},NO=class extends Gs{async _call(e){return new mt(await super._call(e))}},BO=class extends Gs{async _call(e){return new fe(await super._call(e))}},$O=class extends Gs{async _call(e){return new at(await super._call(e))}},DO=class extends Gs{async _call(e){return new Ft(await super._call(e))}},K0=class extends O{},RO=class extends K0{},P_=class extends O{},zO=class extends P_{},GO=class extends P_{},F_=class extends O{},UO=class extends F_{},VO=class extends F_{},I_=class extends O{},WO=class extends I_{},jO=class extends I_{},L_=class extends O{},qO=class extends L_{},HO=class extends L_{},O_=class extends O{},QO=class extends O_{},YO=class extends O_{async _call(e){return new fe(await super._call(e))}},N_=class extends O{},XO=class extends N_{},JO=class extends N_{},B_=class extends O{},KO=class extends B_{},ZO=class extends B_{},$_=class extends O{},e3=class extends $_{},t3=class extends $_{},D_=class extends O{},r3=class extends D_{},n3=class extends D_{},s3=class extends Vr{},Z0=class extends O{},a3=class extends Z0{async _call(e){return new as(await super._call(e))}},R_=class extends O{},o3=class extends R_{},i3=class extends R_{},z_=class extends O{},l3=class extends z_{},c3=class extends z_{},G_=class extends O{},u3=class extends G_{},d3=class extends G_{},U_=class extends O{},f3=class extends U_{},h3=class extends U_{},eb=class extends O{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},tb=class extends eb{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:c=null,logits_processor:u=null,...h}){if(!a){let _;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await Pe(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const m=this.config.normalized_config.hidden_size;_=new K("float32",[],[0,m])}({inputs_embeds:a}=await Pe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await Ur(this,{inputs_embeds:a,past_key_values:i,attention_mask:t,position_ids:s,generation_config:c,logits_processor:u},!1)}},V_=class extends O{},p3=class extends V_{},_3=class extends V_{async _call(e){return new fe(await super._call(e))}},W_=class extends O{},m3=class extends W_{},g3=class extends W_{async _call(e){return new at(await super._call(e))}},j_=class extends O{},w3=class extends j_{},y3=class extends j_{},q_=class extends O{},v3=class extends q_{},b3=class extends q_{},H_=class extends O{},M3=class extends H_{},x3=class extends H_{},Q_=class extends O{},T3=class extends Q_{},E3=class extends Q_{},Y_=class extends O{},k3=class extends Y_{},C3=class extends Y_{},X_=class extends Yp{},rb=class extends N0{},A3=class extends X_{},S3=class extends rb{},J_=class extends X_{},nb=class extends J_{},P3=class extends J_{},F3=class extends nb{},K_=class extends O{},I3=class extends K_{},L3=class extends K_{async _call(e){return new fe(await super._call(e))}},Z_=class extends O{},O3=class extends Z_{},N3=class extends Z_{async _call(e){return new sb(await super._call(e))}},sb=class extends Ei{},Us=class extends O{},B3=class extends Us{},$3=class extends Us{async _call(e){return new mt(await super._call(e))}},D3=class extends Us{async _call(e){return new fe(await super._call(e))}},R3=class extends Us{async _call(e){return new at(await super._call(e))}},z3=class extends Us{async _call(e){return new Ft(await super._call(e))}},Vs=class extends O{},G3=class extends Vs{},U3=class extends Vs{async _call(e){return new mt(await super._call(e))}},V3=class extends Vs{async _call(e){return new fe(await super._call(e))}},W3=class extends Vs{async _call(e){return new at(await super._call(e))}},j3=class extends Vs{async _call(e){return new Ft(await super._call(e))}},em=class extends O{},q3=class extends em{},H3=class extends em{async _call(e){return new ab(await super._call(e))}},ab=class extends Ei{},ob=class extends _t{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},ib=class extends O{},Q3=class extends ib{async get_image_embeddings({pixel_values:e}){return await ln(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=Ot(e.input_points.dims.slice(0,-1));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await Pe(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new ob(await super._call(e))}},lb=class extends _t{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},cb=class extends O{},tm=class extends cb{async get_image_embeddings({pixel_values:e}){return await ln(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const a=e.input_points.dims;e.input_labels??=Ot(a.slice(0,-1)),e.input_boxes??=At([a[0],0,4],0)}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=At([a[0],a[1],0],-1n),e.input_points=At([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const n=this.sessions.prompt_encoder_mask_decoder,s=xt(e,n.inputNames);return await Pe(n,s)}async _call(e){return new lb(await super._call(e))}},Y3=class extends tm{},X3=class extends tm{},Hl=class extends O{},J3=class extends Hl{},K3=class extends Hl{},Z3=class extends Hl{},Ql=class extends O{},eN=class extends Ql{},tN=class extends Ql{},rN=class extends Ql{},rm=class extends O{},nN=class extends rm{},ub=class extends rm{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},sN=class extends os{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},nm=class extends O{},aN=class extends nm{},oN=class extends nm{},iN=class extends R0{},Yl=class extends O{main_input_name="input_values";forward_params=["input_values"]},lN=class extends Yl{async encode(e){return await Pe(this.sessions.encoder_model,e)}async decode(e){return await Pe(this.sessions.decoder_model,e)}},db=class extends Yl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},fb=class extends Yl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},sm=class extends O{},cN=class extends sm{},uN=class extends sm{},Xl=class extends O{},dN=class extends Xl{},fN=class extends Xl{},hN=class extends Xl{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){const i={input_ids:e},{encoder_outputs:c,encoder_attention_mask:u}=await ln(this,i),h=c.dims[1]/this.config.reduction_factor,p=Math.floor(h*s),_=Math.floor(h*n),m=this.config.num_mel_bins;let w=[],b=null,M=null,E=0;for(;;){++E;const P=s0(!!M);let A;M?A=M.output_sequence_out:A=new K("float32",new Float32Array(m),[1,1,m]);let F={use_cache_branch:P,output_sequence:A,encoder_attention_mask:u,speaker_embeddings:t,encoder_hidden_states:c};dp(this,F,b),M=await Pe(this.sessions.decoder_model_merged,F),b=mh(M,b);const{prob:G,spectrum:v}=M;if(w.push(v),E>=_&&(Array.from(G.data).filter(j=>j>=r).length>0||E>=p))break}const T=je(w),{waveform:C}=await Pe(a.sessions.model,{spectrogram:T});return{spectrogram:T,waveform:C}}},pN=class extends O{main_input_name="spectrogram"},Fi=class extends O{},_N=class extends Fi{},mN=class extends Fi{async _call(e){return new mt(await super._call(e))}},gN=class extends Fi{async _call(e){return new fe(await super._call(e))}},wN=class extends Fi{async _call(e){return new Ft(await super._call(e))}},am=class extends O{},yN=class extends am{},vN=class extends am{},om=class extends O{},bN=class extends om{},MN=class extends om{},hb=class extends O{},xN=class extends hb{},pb=class extends O{},_b=class extends pb{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:n=5,speed:s=1.05}){const{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:c,latent_dim:u}=this.config,{last_hidden_state:h,durations:p}=await Pe(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),_=p.div(s).mul_(a),m=c*i,w=_.data,b=Int32Array.from(w,U=>Math.ceil(U/m)),M=Math.max(...b),E=e.dims[0],T=new BigInt64Array(E*M);for(let U=0;UP*A,1),C=wi[M.type];u[M.name]=new K(M.type,new C(T),E)}const m=wi[_],w=new K(_,new m(c*nw),[1,c,nw]),b=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!b)throw new Error("input_features must be iterable or async iterable");return{encoder_session:s,enc_kv_cache:u,enc_padding_cache:w,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:b,text_hidden_size:r.hidden_size}}async function t4(e,t){const r=t.dims[2],n=Math.floor((ZN+r-3)/2)+1,s=new K("int64",BigInt64Array.from({length:n},(p,_)=>BigInt(e.enc_past_seq_len+_)),[1,n]),a=e.enc_past_seq_len+n,i=Ot([1,a]),{audio_embeds:c,present_padding_cache:u,...h}=await Pe(e.encoder_session,{input_features:t,attention_mask:i,position_ids:s,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=u;for(const p in h)if(p.startsWith("present.")){const _=p.replace("present","past_key_values"),m=e.enc_kv_cache[_];m?.location==="gpu-buffer"&&m.dispose(),e.enc_kv_cache[_]=h[p]}return e.enc_past_seq_len=a,c}async function r4(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){const i=e.audio_embed_queue[0],c=i.tokens-e.audio_queue_offset,u=Math.min(a,c),h=e.audio_queue_offset*e.text_hidden_size;for(let p=0;p=i.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}var s4=class extends Ol{constructor(e){super(),this._s=e}_call(e){const t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},xb=class extends O{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Tb=class extends xb{async forward({input_ids:e,past_key_values:t,...r}){const n=e.dims[1],s=If.get(this);s&&await r4(s,s.audio_consumed+n);const{inputs_embeds:a}=await Pe(this.sessions.embed_tokens,{input_ids:e});s&&n4(s,a,n);const i={inputs_embeds:a,...r};dp(this,i,t);const c=this.sessions.decoder_model_merged,u=xt(i,c.inputNames);return await Pe(c,u)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const n=e4(this,e);If.set(this,n);const s=new r0;s.push(new s4(n)),t&&s.extend(t);try{return await super.generate({...r,stopping_criteria:s})}finally{n.enc_kv_cache.dispose(),If.delete(this)}}},Zl=class extends O{},a4=class extends Zl{},o4=class extends Zl{async _call(e){return new as(await super._call(e))}},i4=class extends Zl{async _call(e){return new fe(await super._call(e))}},Eb=class extends _t{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Ws=class extends O{},l4=class extends Ws{},c4=class extends Ws{async _call(e){return new as(await super._call(e))}},u4=class extends Ws{async _call(e){return new fe(await super._call(e))}},d4=class extends Ws{async _call(e){return new Eb(await super._call(e))}},f4=class extends Ws{async _call(e){return new at(await super._call(e))}},kb=class extends O{},h4=class extends kb{},p4=class extends t0{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},hm=class extends O{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},_4=class extends hm{},Cb=class extends hm{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,p4)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const n=e.task;if(e.is_multilingual){r||(be.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${qk(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(r||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(be.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(s=>s!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,...s}){t=this._prepare_generation_config(t,s);const a=s.decoder_input_ids instanceof K?tp(s.decoder_input_ids):s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new yl,r.push(new xS(t,a))),t.begin_suppress_tokens&&(r??=new yl,r.push(new e0(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&be.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!s.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:s});const i=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});return t.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,t.alignment_heads,t.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:n,kwargs:s}){const a=t.no_timestamps_token_id+1,i=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,c=t.return_token_timestamps,u=e,h=u.dims[2],p=2,_=this.config.max_source_positions,m=p*_;let w=0;const b=[],M=[];for(;wse+Y)}if(v.length>0&&v.at(-1)===i&&v.pop(),v.length===0)break;const U=v.map(Y=>Y>=a),q=v.length>=2&&U[v.length-1]&&!U[v.length-2],ne=[];for(let Y=0;Y0)if(q)H=T-w;else{const Y=ne.at(-1);H=(v[Y-1]-a)*p,I=Y}else H=T-w;const S=Math.floor(w/p),D=a+1500;for(let Y=0;Y=a&&(v[Y]=Math.min(v[Y]+S,D));b.push(...v.slice(0,I)),j&&M.push(...j.slice(0,I)),w+=H}b.push(i);const E=[...n,...b];if(c){const T=new K("int64",E.map(BigInt),[1,E.length]),C=[...new Array(n.length).fill(0),...M,0],P=new K("float32",new Float32Array(C),[1,C.length]);return{sequences:T,token_timestamps:P}}return new K("int64",E.map(BigInt),[1,E.length])}_extract_token_timestamps(e,t,r=null,n=.02,s=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&be.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(be.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const i=e.cross_attentions,c=Array.from({length:this.config.decoder_layers},(E,T)=>je(i.map(C=>C[T]),2)),u=Gr(t.map(([E,T])=>{if(E>=c.length)throw new Error(`Layer index ${E} is out of bounds for cross attentions (length ${c.length}).`);return r?c[E].slice(null,T,null,[0,r]):c[E].slice(null,T)})).transpose(1,0,2,3),[h,p]=XE(u,-2,0,!0),_=u.clone();for(let E=0;E<_.dims[0];++E){const T=_[E];for(let C=0;C0?_.slice(null,null,[s,_.dims[2]],null):_,w=[Zh(m,1)],b=e.sequences.dims,M=new K("float32",new Float32Array(b[0]*b[1]),b);for(let E=0;EC[U+1]-C[U]),F=Tr([1],A).map(j=>!!j),G=[];for(let j=0;j0&&v.push(G.at(-1)),M[E].data.set(v)}return M}},m4=class extends Cb{},js=class extends O{},g4=class extends js{},w4=class extends js{async _call(e){return new mt(await super._call(e))}},y4=class extends js{async _call(e){return new fe(await super._call(e))}},v4=class extends js{async _call(e){return new at(await super._call(e))}},b4=class extends js{async _call(e){return new Ft(await super._call(e))}},qs=class extends O{},M4=class extends qs{},x4=class extends qs{async _call(e){return new mt(await super._call(e))}},T4=class extends qs{async _call(e){return new fe(await super._call(e))}},E4=class extends qs{async _call(e){return new at(await super._call(e))}},k4=class extends qs{async _call(e){return new Ft(await super._call(e))}},pm=class extends O{},C4=class extends pm{},A4=class extends pm{async _call(e){return new Ab(await super._call(e))}},Ab=class extends _t{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},_m=class extends O{},S4=class extends _m{},P4=class extends _m{},F4=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),I4=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),L4=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),O4=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),Sb=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Pb=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Fb=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Ib=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),Lb=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),Ob=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Nb=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),N4=new Map([["multi_modality","MultiModalityCausalLM"]]),Bb=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),$b=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),Db=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Rb=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),zb=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),B4=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Gb=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),Ub=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Vb=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),vs=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Wb=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),jb=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),qb=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Hb=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Qb=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Yb=new Map([["wavlm","WavLMForXVector"]]),Xb=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),Jb=new Map([["vitmatte","VitMatteForImageMatting"]]),$4=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),Kb=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),Zb=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),eM=new Map([["sapiens","SapiensForNormalEstimation"]]),tM=new Map([["vitpose","VitPoseForPoseEstimation"]]),rM=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),nM=[[F4,Z.EncoderOnly],[I4,Z.EncoderDecoder],[O4,Z.DecoderOnlyWithoutHead],[L4,Z.AutoEncoder],[Ib,Z.EncoderOnly],[Lb,Z.EncoderOnly],[Ob,Z.Seq2Seq],[Sb,Z.Seq2Seq],[Nb,Z.DecoderOnly],[N4,Z.MultiModality],[Bb,Z.EncoderOnly],[$b,Z.EncoderOnly],[Db,Z.Vision2Seq],[Rb,Z.ImageTextToText],[zb,Z.AudioTextToText],[Gb,Z.EncoderOnly],[vs,Z.EncoderOnly],[jb,Z.EncoderOnly],[Wb,Z.EncoderOnly],[Jb,Z.EncoderOnly],[$4,Z.EncoderOnly],[Kb,Z.EncoderOnly],[Zb,Z.EncoderOnly],[eM,Z.EncoderOnly],[tM,Z.EncoderOnly],[Ub,Z.EncoderOnly],[Vb,Z.EncoderOnly],[qb,Z.MaskGeneration],[Hb,Z.EncoderOnly],[Qb,Z.EncoderOnly],[Pb,Z.Seq2Seq],[Fb,Z.EncoderOnly],[Yb,Z.EncoderOnly],[Xb,Z.EncoderOnly],[rM,Z.EncoderOnly]];for(const[e,t]of nM)for(const r of e.values()){zr.set(r,t);const n=hp[r];Es.set(n,r),up.set(r,n)}var D4=[["MusicgenForConditionalGeneration",J0,Z.Musicgen],["Phi3VForCausalLM",tb,Z.Phi3V],["CLIPTextModelWithProjection",m0,Z.EncoderOnly],["SiglipTextModel",ub,Z.EncoderOnly],["JinaCLIPTextModel",z0,Z.EncoderOnly],["ClapTextModelWithProjection",p0,Z.EncoderOnly],["ClapAudioModelWithProjection",_0,Z.EncoderOnly],["DacEncoderModel",y0,Z.EncoderOnly],["DacDecoderModel",v0,Z.EncoderOnly],["MimiEncoderModel",Q0,Z.EncoderOnly],["MimiDecoderModel",Y0,Z.EncoderOnly],["SnacEncoderModel",db,Z.EncoderOnly],["SnacDecoderModel",fb,Z.EncoderOnly],["Gemma3nForConditionalGeneration",zl,Z.ImageAudioTextToText],["Gemma4ForConditionalGeneration",jp,Z.ImageAudioTextToText],["SupertonicForConditionalGeneration",_b,Z.Supertonic],["ChatterboxModel",d0,Z.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Tb,Z.VoxtralRealtime]];for(const[e,t,r]of D4)zr.set(e,r),Es.set(t,e),up.set(e,t);var sM=new Map([["modnet",vs],["birefnet",vs],["isnet",vs],["ben",vs]]);for(const[e,t]of sM.entries())t.set(e,"PreTrainedModel"),zr.set(e,Z.EncoderOnly),up.set(e,O);var R4=new Set(sM.keys());zr.set("PreTrainedModel",Z.EncoderOnly);Es.set(O,"PreTrainedModel");var Ne={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Ib,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Lb,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Pb,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Fb,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Bb,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:$b,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Gb,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:vs,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Wb,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:jb,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Ub,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Vb,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:qb,MODEL_FOR_CTC_MAPPING_NAMES:Hb,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Qb,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Yb,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Xb,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:B4,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:Jb,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:Kb,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:Zb,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:eM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:tM,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:rM,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Rb,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:zb,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Ob,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Sb,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Nb,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Db};GS(Ne);var Be=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(const t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:i=null,subfolder:c="onnx",device:u=null,dtype:h=null,use_external_data_format:p=null,session_options:_={}}={}){const m={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:i,subfolder:c,device:u,dtype:h,use_external_data_format:p,session_options:_};if(m.config=await wl.from_pretrained(e,m),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const{model_type:w}=m.config;for(const b of this.MODEL_CLASS_MAPPINGS){let M=b.get(w);if(!M){for(const E of b.values())if(E[0]===w){M=E;break}if(!M)continue}return await hp[M].from_pretrained(e,m)}if(this.BASE_IF_FAIL)return R4.has(w)||be.warn(`Unknown model class "${w}", attempting to construct from base class.`),await O.from_pretrained(e,m);throw Error(`Unsupported model type: ${w}`)}};(class extends Be{static MODEL_CLASS_MAPPINGS=nM.map(e=>e[0]);static BASE_IF_FAIL=!0});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]});var z4=class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]};(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASKED_LM_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CTC_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends Be{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});ve.IS_PROCESS_AVAILABLE;/*! * ONNX Runtime Web v1.25.1 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var mm=Object.defineProperty,G4=Object.getOwnPropertyDescriptor,U4=Object.getOwnPropertyNames,V4=Object.prototype.hasOwnProperty,W4=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ee=(e,t)=>()=>(e&&(t=e(e=0)),t),Li=(e,t)=>{for(var r in t)mm(e,r,{get:t[r],enumerable:!0})},j4=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of U4(t))!V4.call(e,s)&&s!==r&&mm(e,s,{get:()=>t[s],enumerable:!(n=G4(t,s))||n.enumerable});return e},bl=e=>j4(mm({},"__esModule",{value:!0}),e),ii,Zr,bs,sw,aM,oM=Ee(()=>{ii=new Map,Zr=[],bs=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=ii.get(e);if(n===void 0)ii.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=Zr.indexOf(e);s!==-1&&Zr.splice(s,1);for(let a=0;a{let t=ii.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},aM=async e=>{let t=e.executionProviders||[],r=t.map(u=>typeof u=="string"?u:u.name),n=r.length===0?Zr:r,s,a=[],i=new Set;for(let u of n){let h=await sw(u);typeof h=="string"?a.push({name:u,err:h}):(s||(s=h),s===h&&i.add(u))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(u=>`[${u.name}] ${u.err}`).join(", ")}`);for(let{name:u,err:h}of a)r.includes(u)&&console.warn(`removing requested execution provider "${u}" from session options because it is not available: ${h}`);let c=t.filter(u=>i.has(typeof u=="string"?u:u.name));return[s,new Proxy(e,{get:(u,h)=>h==="executionProviders"?c:Reflect.get(u,h)})]}}),q4=Ee(()=>{oM()}),iM,H4=Ee(()=>{iM="1.25.1"}),Lf,wt,lM=Ee(()=>{H4(),Lf="warning",wt={wasm:{},webgl:{},webgpu:{},versions:{common:iM},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Lf=e}},get logLevel(){return Lf}},Object.defineProperty(wt,"logLevel",{enumerable:!0})}),Qe,Q4=Ee(()=>{lM(),Qe=wt}),cM,uM,Y4=Ee(()=>{cM=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=t?.format!==void 0?t.format:"RGB",c=t?.norm,u,h;c===void 0||c.mean===void 0?u=[255,255,255,255]:typeof c.mean=="number"?u=[c.mean,c.mean,c.mean,c.mean]:(u=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(u[3]=c.mean[3])),c===void 0||c.bias===void 0?h=[0,0,0,0]:typeof c.bias=="number"?h=[c.bias,c.bias,c.bias,c.bias]:(h=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(h[3]=c.bias[3]));let p=a*s,_=0,m=p,w=p*2,b=-1;i==="RGBA"?(_=0,m=p,w=p*2,b=p*3):i==="RGB"?(_=0,m=p,w=p*2):i==="RBG"&&(_=0,w=p,m=p*2);for(let M=0;M{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",u=t?.norm,h,p;u===void 0||u.mean===void 0?h=[255,255,255,255]:typeof u.mean=="number"?h=[u.mean,u.mean,u.mean,u.mean]:(h=[u.mean[0],u.mean[1],u.mean[2],255],u.mean[3]!==void 0&&(h[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let _=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,w=0,b=1,M=2,E=3,T=0,C=_,P=_*2,A=-1;c==="RGBA"?(T=0,C=_,P=_*2,A=_*3):c==="RGB"?(T=0,C=_,P=_*2):c==="RBG"&&(T=0,P=_,C=_*2),n=r.createImageData(s,a);for(let F=0;F{gm(),Yi=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",u=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=r*n,p=u==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),_=4,m=0,w=1,b=2,M=3,E=0,T=h,C=h*2,P=-1;c==="RGB"&&(_=3,m=0,w=1,b=2,M=-1),u==="RGBA"?P=h*3:u==="RBG"?(E=0,C=h,T=h*2):u==="BGR"&&(C=0,T=h,E=h*2);for(let A=0;A{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,c=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=u();p.width=e.width,p.height=e.height;let _=h(p);if(_!=null){let m=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(m=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=m,c.width=w}else c.tensorFormat="RGBA",c.height=m,c.width=w;_.drawImage(e,0,0),i=_.getImageData(0,0,w,m).data}else throw new Error("Can not access image data")}else if(n){let p,_;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,_=t.resizedWidth):(p=e.height,_=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=p,c.width=_,t!==void 0){let m=u();m.width=_,m.height=p;let w=h(m);if(w!=null)w.putImageData(e,0,0),i=w.getImageData(0,0,_,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=u();p.width=e.width,p.height=e.height;let _=h(p);if(_!=null){let m=e.height,w=e.width;return _.drawImage(e,0,0,w,m),i=_.getImageData(0,0,w,m).data,c.height=m,c.width=w,Yi(i,c)}else throw new Error("Can not access image data")}else{if(a)return new Promise((p,_)=>{let m=u(),w=h(m);if(!e||!w)return _();let b=new Image;b.crossOrigin="Anonymous",b.src=e,b.onload=()=>{m.width=b.width,m.height=b.height,w.drawImage(b,0,0,m.width,m.height);let M=w.getImageData(0,0,m.width,m.height);c.height=m.height,c.width=m.width,p(Yi(M.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Yi(i,c);throw new Error("Input data provided is not supported - aborted tensor creation")},fM=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new Ht({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},hM=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new Ht({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},pM=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new Ht({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},_M=(e,t,r)=>new Ht({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Yn,pi,Of,mM,J4=Ee(()=>{Yn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),pi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Of=!1,mM=()=>{if(!Of){Of=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Yn.set("int64",BigInt64Array),pi.set(BigInt64Array,"int64")),t&&(Yn.set("uint64",BigUint64Array),pi.set(BigUint64Array,"uint64")),n?(Yn.set("float16",r),pi.set(r,"float16")):Yn.set("float16",Uint16Array)}}}),gM,wM,K4=Ee(()=>{gm(),gM=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Ht(e.type,e.data,t);case"cpu-pinned":return new Ht({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ht({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ht({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ht({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ht,gm=Ee(()=>{Y4(),X4(),J4(),K4(),Ht=class{constructor(e,t,r){mM();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=Yn.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,c;if(typeof e=="string")if(n=e,c=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let u=Yn.get(e);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&u===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${u.name} as data.`);e==="uint64"||e==="int64"?i=u.from(t,BigInt):i=u.from(t)}else if(t instanceof u)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&u!==Uint16Array)i=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${u}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let u=typeof e[0];if(u==="string")n="string",i=e;else if(u==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let u=pi.get(e.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=u,i=e}if(c===void 0)c=[i.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");s=c,this.cpuData=i,this.dataLocation="cpu"}let a=gM(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return dM(e,t)}static fromTexture(e,t){return fM(e,t)}static fromGpuBuffer(e,t){return hM(e,t)}static fromMLTensor(e,t){return pM(e,t)}static fromPinnedBuffer(e,t,r){return _M(e,t,r)}toDataURL(e){return cM(this,e)}toImageData(e){return uM(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return wM(this,e)}}}),Qt,yM=Ee(()=>{gm(),Qt=Ht}),gh,Nf,ks,Cs,Zn,es,vM=Ee(()=>{lM(),gh=(e,t)=>{(typeof wt.trace>"u"?!wt.wasm.trace:!wt.trace)||console.timeStamp(`${e}::ORT::${t}`)},Nf=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s{(typeof wt.trace>"u"?!wt.wasm.trace:!wt.trace)||Nf("BEGIN",e)},Cs=e=>{(typeof wt.trace>"u"?!wt.wasm.trace:!wt.trace)||Nf("END",e)},Zn=e=>{(typeof wt.trace>"u"?!wt.wasm.trace:!wt.trace)||console.time(`ORT::${e}`)},es=e=>{(typeof wt.trace>"u"?!wt.wasm.trace:!wt.trace)||console.timeEnd(`ORT::${e}`)}}),bM,Z4=Ee(()=>{oM(),yM(),vM(),bM=class MM{constructor(t){this.handler=t}async run(t,r,n){ks(),Zn("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Qt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Qt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let h of r){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);s[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,p=Object.getOwnPropertyNames(r);for(let _ of this.outputNames)if(p.indexOf(_)!==-1){let m=r[_];(m===null||m instanceof Qt)&&(h=!0,i=!1,s[_]=m)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)s[h]=null;let c=await this.handler.run(t,s,a),u={};for(let h in c)if(Object.hasOwnProperty.call(c,h)){let p=c[h];p instanceof Qt?u[h]=p:u[h]=new Qt(p.type,p.data,p.dims)}return es("InferenceSession.run"),Cs(),u}async release(){return this.handler.dispose()}static async create(t,r,n,s){ks(),Zn("InferenceSession.create");let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let p=t,_=0,m=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(_=r,!Number.isSafeInteger(_))throw new RangeError("'byteOffset' must be an integer.");if(_<0||_>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(m=t.byteLength-_,typeof n=="number"){if(m=n,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||_+m>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-_}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(p,_,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,u]=await aM(i),h=await c.createInferenceSessionHandler(a,u);return es("InferenceSession.create"),Cs(),new MM(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),wm,eB=Ee(()=>{Z4(),wm=bM}),tB=Ee(()=>{}),rB=Ee(()=>{}),nB=Ee(()=>{}),sB=Ee(()=>{}),aB={};Li(aB,{InferenceSession:()=>wm,TRACE:()=>gh,TRACE_EVENT_BEGIN:()=>Zn,TRACE_EVENT_END:()=>es,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Cs,Tensor:()=>Qt,env:()=>Qe,registerBackend:()=>bs});var is=Ee(()=>{q4(),Q4(),eB(),yM(),tB(),rB(),vM(),nB(),sB()}),ym=Ee(()=>{}),xM={};Li(xM,{default:()=>TM});var Bf,$f,TM,oB=Ee(()=>{RM(),ls(),vm(),Bf="ort-wasm-proxy-worker",$f=globalThis.self?.name===Bf,$f&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":bm(r.wasm).then(()=>{km(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;Cm(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=Tl(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;Am(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":Sm(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:i,options:c}=r;Pm(n,s,a,i,new Array(i.length).fill(null),c).then(u=>{u.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},Im([...a,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":Fm(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),TM=$f?null:e=>new Worker(e??Ut,{type:"module",name:Bf})}),EM={};Li(EM,{default:()=>kM});async function aw(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(o,l)=>{o.startsWith("./")&&(o=o.substring(2)),(t.Uc||(t.Uc=new Map)).set(o,l)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Ae:!0}).buffer.constructor;let a=()=>{let o=l=>(...d)=>{let f=tt;return d=l(...d),tt!=f?new Promise((g,y)=>{yn={resolve:g,reject:y}}):d};(()=>{for(let l of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[l]=o(t[l])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var i,c,u=(o,l)=>{throw l},h=import.meta.url,p="";if(r||n){try{p=new URL(".",h).href}catch{}n&&(c=o=>{var l=new XMLHttpRequest;return l.open("GET",o,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),i=async o=>{if(G(o))return new Promise((d,f)=>{var g=new XMLHttpRequest;g.open("GET",o,!0),g.responseType="arraybuffer",g.onload=()=>{g.status==200||g.status==0&&g.response?d(g.response):f(g.status)},g.onerror=f,g.send(null)});var l=await fetch(o,{credentials:"same-origin"});if(l.ok)return l.arrayBuffer();throw Error(l.status+" : "+l.url)}}var _,m,w,b,M,E,T=console.log.bind(console),C=console.error.bind(console),P=T,A=C,F=!1,G=o=>o.startsWith("file://");function v(){bt.buffer!=U.buffer&&Q()}if(s){let o=function(l){try{var d=l.data,f=d.Oc;if(f==="load"){let g=[];self.onmessage=y=>g.push(y),E=()=>{postMessage({Oc:"loaded"});for(let y of g)o(y);self.onmessage=o};for(let y of d.ce)t[y]&&!t[y].proxy||(t[y]=(...x)=>{postMessage({Oc:"callHandler",be:y,args:x})},y=="print"&&(P=t[y]),y=="printErr"&&(A=t[y]));bt=d.ie,Q(),m=d.je,nt(),Rr()}else if(f==="run"){(function(g){var y=(v(),S)[g+52>>>2>>>0];g=(v(),S)[g+56>>>2>>>0],uo(y,y-g),X(y)})(d.Nc),Fn(d.Nc,0,0,1,0,0),Js(),mn(d.Nc),j||(qa(),j=!0);try{rc(d.ge,d.Wc)}catch(g){if(g!="unwind")throw g}}else d.target!=="setimmediate"&&(f==="checkMailbox"?j&&Fr():f&&(A(`worker: received unknown command ${f}`),A(d)))}catch(g){throw ao(),g}};var j=!1;self.onunhandledrejection=l=>{throw l.reason||l},self.onmessage=o}var U,q,ne,H,I,S,D,Y,se,N,$,z=!1;function Q(){var o=bt.buffer;t.HEAP8=U=new Int8Array(o),ne=new Int16Array(o),t.HEAPU8=q=new Uint8Array(o),H=new Uint16Array(o),t.HEAP32=I=new Int32Array(o),t.HEAPU32=S=new Uint32Array(o),D=new Float32Array(o),Y=new Float64Array(o),se=new BigInt64Array(o),N=new BigUint64Array(o)}function _e(){z=!0,s?E():dt._b()}function me(o){throw A(o="Aborted("+o+")"),F=!0,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),M?.(o),o}function de(){return{a:{f:nc,J:sc,k:ac,p:oc,l:ic,sa:lc,b:cc,ca:uc,Ja:na,q:dc,da:ia,Za:la,Fa:ca,Ha:ua,_a:da,Xa:fa,Qa:ha,Wa:pa,oa:_a,Ga:ma,Xb:ga,Ya:wa,Yb:ya,db:fc,Da:hc,Sb:pc,Qb:mc,Ca:wc,M:yc,I:vc,Rb:bc,ja:Ac,Tb:Sc,Ta:Pc,Vb:Ic,Ka:Lc,Ob:Oc,ka:Nc,Sa:mn,ab:Bc,U:zc,n:jc,c:pn,rb:qc,w:Hc,L:Qc,z:Yc,j:Xc,o:Ca,sb:Jc,G:Kc,T:Zc,h:eu,u:tu,m:ru,i:nu,Na:su,Oa:au,Pa:ou,La:Fa,Ma:Ia,Pb:La,eb:lu,cb:uu,Y:du,qb:fu,la:hu,bb:cu,fb:pu,$a:_u,Wb:mu,N:iu,gb:gu,X:wu,Ub:yu,nb:Au,C:Su,ra:Pu,qa:Fu,pb:Iu,W:Lu,v:Ou,mb:Nu,lb:Bu,kb:$u,ob:Du,jb:Ru,ib:zu,hb:Gu,Ua:Ra,Va:za,Ia:wr,V:Ga,na:Ua,Ra:Va,ma:Wa,Cb:Jd,xa:jd,Db:Xd,ya:Wd,F:Ld,e:vd,s:wd,x:gd,B:Pd,Fb:Gd,ba:zd,D:xd,za:Ud,$:qd,ga:Rd,Gb:Dd,Hb:$d,Ba:Od,Aa:Bd,Ib:Nd,wa:Yd,aa:Vd,d:yd,A:Md,r:bd,Bb:Kd,t:Ed,y:Fd,H:Td,E:kd,K:Id,R:Hd,ia:Sd,_:Qd,Jb:Ad,Kb:Cd,g:Vu,a:bt,Nb:gr,Eb:Wu,ha:ju,O:qu,pa:Hu,Lb:Qu,ta:Yu,Q:Xu,yb:Ju,zb:Ku,ua:Zu,ea:ed,P:td,Ea:rd,va:nd,Z:sd,wb:ad,Zb:od,S:id,Ab:ld,tb:cd,ub:dd,vb:fd,fa:hd,xb:pd,Mb:_d}}}async function nt(){function o(f,g){var y=dt=f.exports;f={};for(let[x,k]of Object.entries(y))typeof k=="function"?(y=$c(k),f[x]=y):f[x]=k;return dt=f,dt=(function(){var x=dt,k=B=>re=>B(re)>>>0,L=B=>()=>B()>>>0;return(x=Object.assign({},x)).$b=k(x.$b),x.Cc=L(x.Cc),x.Ec=k(x.Ec),x.rd=(B=>(re,R)=>B(re,R)>>>0)(x.rd),x.wd=k(x.wd),x.xd=L(x.xd),x.Bd=k(x.Bd),x})(),Ys.push(dt.id),ja=(f=dt).$b,qa=f.ac,t._OrtInit=f.bc,t._OrtGetLastError=f.cc,t._OrtCreateSessionOptions=f.dc,t._OrtAppendExecutionProvider=f.ec,t._OrtAddFreeDimensionOverride=f.fc,t._OrtAddSessionConfigEntry=f.gc,t._OrtReleaseSessionOptions=f.hc,t._OrtCreateSession=f.ic,t._OrtReleaseSession=f.jc,t._OrtGetInputOutputCount=f.kc,t._OrtGetInputOutputMetadata=f.lc,t._OrtFree=f.mc,t._OrtCreateTensor=f.nc,t._OrtGetTensorData=f.oc,t._OrtReleaseTensor=f.pc,t._OrtCreateRunOptions=f.qc,t._OrtAddRunConfigEntry=f.rc,t._OrtReleaseRunOptions=f.sc,t._OrtCreateBinding=f.tc,t._OrtBindInput=f.uc,t._OrtBindOutput=f.vc,t._OrtClearBoundOutputs=f.wc,t._OrtReleaseBinding=f.xc,t._OrtRunWithBinding=f.yc,t._OrtRun=f.zc,t._OrtEndProfiling=f.Ac,En=t._OrtGetWebGpuDevice=f.Bc,$r=f.Cc,Je=t._free=f.Dc,Rt=t._malloc=f.Ec,Ha=t._wgpuBufferRelease=f.Fc,Qa=t._wgpuCreateInstance=f.Gc,Ya=f.Hc,Xa=f.Ic,Ja=f.Jc,Ka=f.Kc,Za=f.Lc,eo=f.Pc,to=f.Zc,ro=f._c,no=f.$c,kn=f.bd,Cn=f.cd,An=f.dd,Sn=f.ed,ir=f.fd,Pn=f.gd,so=f.hd,Fn=f.kd,ao=f.ld,oo=f.md,io=f.nd,In=f.od,lo=f.pd,co=f.qd,Ln=f.rd,te=f.sd,lr=f.td,uo=f.ud,X=f.vd,Dr=f.wd,J=f.xd,fo=f.yd,On=f.zd,ho=f.Ad,po=f.Bd,_o=f.Cd,Nn=f.Dd,mo=f.Ed,go=f.Fd,wo=f.Gd,yo=f.Hd,vo=f.Id,bo=f.Jd,Mo=f.Kd,xo=f.Ld,To=f.Md,Eo=f.Nd,ko=f.Od,Co=f.Pd,Ao=f.Qd,So=f.Rd,Po=f.Td,Fo=f.Ud,Io=f.Vd,Lo=f.Wd,Oo=f.Yd,No=f.Zd,Bo=f._d,$o=f.$d,Do=f.ae,Ro=f.oe,zo=f.pe,Go=f.qe,Uo=f.re,Vo=f.se,Wo=f.te,jo=f.ue,qo=f.ve,Ho=f.we,Qo=f.xe,Yo=f.ye,Xo=f.Ye,Jo=f.Ze,Ko=f._e,Zo=f.$e,m=g,dt}var l,d=de();return t.instantiateWasm?new Promise(f=>{t.instantiateWasm(d,(g,y)=>{f(o(g,y))})}):s?o(new WebAssembly.Instance(m,de()),m):($??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-C7SQPqnH.wasm",import.meta.url).href,l=await(async function(f){var g=$;if(!_&&!G(g))try{var y=fetch(g,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(y,f)}catch(x){A(`wasm streaming compile failed: ${x}`),A("falling back to ArrayBuffer instantiation")}return(async function(x,k){try{var L=await(async function(B){if(!_)try{var re=await i(B);return new Uint8Array(re)}catch{}if(B==$&&_)B=new Uint8Array(_);else{if(!c)throw"both async and sync fetching of the wasm failed";B=c(B)}return B})(x);return await WebAssembly.instantiate(L,k)}catch(B){A(`failed to asynchronously prepare wasm: ${B}`),me(B)}})(g,f)})(d),o(l.instance,l.module))}class ye{name="ExitStatus";constructor(l){this.message=`Program terminated with exit(${l})`,this.status=l}}var $e=o=>{o.terminate(),o.onmessage=()=>{}},qe=[],ue=0,oe=null,Re=o=>{vt.length==0&&(Zs(),Ks(vt[0]));var l=vt.pop();if(!l)return 6;sr.push(l),It[o.Nc]=l,l.Nc=o.Nc;var d={Oc:"run",ge:o.fe,Wc:o.Wc,Nc:o.Nc};return l.postMessage(d,o.Yc),0},ie=0,le=(o,l,...d)=>{var f,g=16*d.length,y=J(),x=Dr(g),k=x>>>3;for(f of d)typeof f=="bigint"?((v(),se)[k++>>>0]=1n,(v(),se)[k++>>>0]=f):((v(),se)[k++>>>0]=0n,(v(),Y)[k++>>>0]=f);return o=oo(o,0,g,x,l),X(y),o};function gr(o){if(s)return le(0,1,o);if(w=o,!(0{if(w=o,s)throw Hr(o),"unwind";gr(o)},vt=[],sr=[],Ys=[],It={},Xs=o=>{var l=o.Nc;delete It[l],vt.push(o),sr.splice(sr.indexOf(o),1),o.Nc=0,io(l)};function Js(){Ys.forEach(o=>o())}var Ks=o=>new Promise(l=>{o.onmessage=g=>{var y=g.data;if(g=y.Oc,y.Vc&&y.Vc!=$r()){var x=It[y.Vc];x?x.postMessage(y,y.Yc):A(`Internal error! Worker sent a message "${g}" to target pthread ${y.Vc}, but that thread no longer exists!`)}else g==="checkMailbox"?Fr():g==="spawnThread"?Re(y):g==="cleanupThread"?Le(()=>{Xs(It[y.he])}):g==="loaded"?(o.loaded=!0,l(o)):y.target==="setimmediate"?o.postMessage(y):g==="uncaughtException"?o.onerror(y.error):g==="callHandler"?t[y.be](...y.args):g&&A(`worker sent an unknown command ${g}`)},o.onerror=g=>{throw A(`worker sent an error! ${g.filename}:${g.lineno}: ${g.message}`),g};var d,f=[];for(d of[])t.propertyIsEnumerable(d)&&f.push(d);o.postMessage({Oc:"load",ce:f,ie:bt,je:m})});function Zs(){var o=new Worker((()=>{let l=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new l("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});vt.push(o)}var bt,rc=(o,l)=>{ie=0,o=Nn(o,l),0-9007199254740992>o||9007199254740992>>=0);return(v(),U)[l.Qc+12>>>0]==0&&(ea(l,!0),Pr--),ta(l,!1),Sr.push(l),po(o)}var Nt=0,sc=()=>{te(0,0);var o=Sr.pop();fo(o.Xc),Nt=0};function ea(o,l){l=l?1:0,(v(),U)[o.Qc+12>>>0]=l}function ta(o,l){l=l?1:0,(v(),U)[o.Qc+13>>>0]=l}class un{constructor(l){this.Xc=l,this.Qc=l-24}}var dn=o=>{var l=Nt;if(!l)return lr(0),0;var d=new un(l);(v(),S)[d.Qc+16>>>2>>>0]=l;var f=(v(),S)[d.Qc+4>>>2>>>0];if(!f)return lr(0),l;for(var g of o){if(g===0||g===f)break;if(ho(g,f,d.Qc+16))return lr(g),l}return lr(f),l};function ac(){return dn([])}function oc(o){return dn([o>>>0])}function ic(o,l,d,f){return dn([o>>>0,l>>>0,d>>>0,f>>>0])}var lc=()=>{var o=Sr.pop();o||me("no exception to throw");var l=o.Xc;throw(v(),U)[o.Qc+13>>>0]==0&&(Sr.push(o),ta(o,!0),ea(o,!1),Pr++),On(l),Nt=l};function cc(o,l,d){var f=new un(o>>>=0);throw l>>>=0,d>>>=0,(v(),S)[f.Qc+16>>>2>>>0]=0,(v(),S)[f.Qc+4>>>2>>>0]=l,(v(),S)[f.Qc+8>>>2>>>0]=d,On(o),Pr++,Nt=o}var uc=()=>Pr;function ra(o,l,d,f){return s?le(2,1,o,l,d,f):na(o,l,d,f)}function na(o,l,d,f){if(o>>>=0,l>>>=0,d>>>=0,f>>>=0,!globalThis.SharedArrayBuffer)return 6;var g=[];return s&&g.length===0?ra(o,l,d,f):(o={fe:d,Nc:o,Wc:f,Yc:g},s?(o.Oc="spawnThread",postMessage(o,g),0):Re(o))}function dc(o){throw Nt||=o>>>0,Nt}var sa=globalThis.TextDecoder&&new TextDecoder,aa=(o,l,d,f)=>{if(d=l+d,f)return d;for(;o[l]&&!(l>=d);)++l;return l},oa=(o,l=0,d,f)=>{if(16<(d=aa(o,l>>>=0,d,f))-l&&o.buffer&&sa)return sa.decode(o.buffer instanceof ArrayBuffer?o.subarray(l,d):o.slice(l,d));for(f="";l(g=(240&g)==224?(15&g)<<12|y<<6|x:(7&g)<<18|y<<12|x<<6|63&o[l++])?f+=String.fromCharCode(g):(g-=65536,f+=String.fromCharCode(55296|g>>10,56320|1023&g))}}else f+=String.fromCharCode(g)}return f},Bt=(o,l,d)=>(o>>>=0)?oa((v(),q),o,l,d):"";function ia(o,l,d){return s?le(3,1,o,l,d):0}function la(o,l){if(s)return le(4,1,o,l)}function ca(o,l){if(s)return le(5,1,o,l)}function ua(o,l,d){if(s)return le(6,1,o,l,d)}function da(o,l,d){return s?le(7,1,o,l,d):0}function fa(o,l){if(s)return le(8,1,o,l)}function ha(o,l,d){if(s)return le(9,1,o,l,d)}function pa(o,l,d,f){if(s)return le(10,1,o,l,d,f)}function _a(o,l,d,f){if(s)return le(11,1,o,l,d,f)}function ma(o,l,d,f){if(s)return le(12,1,o,l,d,f)}function ga(o){if(s)return le(13,1,o)}function wa(o,l){if(s)return le(14,1,o,l)}function ya(o,l,d){if(s)return le(15,1,o,l,d)}var fc=()=>me(""),et=o=>{o>>>=0;for(var l="";;){var d=(v(),q)[o++>>>0];if(!d)return l;l+=String.fromCharCode(d)}},fn={},hn={},$t=class extends Error{constructor(o){super(o),this.name="BindingError"}};function ot(o,l,d={}){return(function(f,g,y={}){var x=g.name;if(!f)throw new $t(`type "${x}" must have a positive integer typeid pointer`);if(hn.hasOwnProperty(f)){if(y.de)return;throw new $t(`Cannot register type '${x}' twice`)}hn[f]=g,fn.hasOwnProperty(f)&&(g=fn[f],delete fn[f],g.forEach(k=>k()))})(o,l,d)}var va=(o,l,d)=>{switch(l){case 1:return d?f=>(v(),U)[f>>>0]:f=>(v(),q)[f>>>0];case 2:return d?f=>(v(),ne)[f>>>1>>>0]:f=>(v(),H)[f>>>1>>>0];case 4:return d?f=>(v(),I)[f>>>2>>>0]:f=>(v(),S)[f>>>2>>>0];case 8:return d?f=>(v(),se)[f>>>3>>>0]:f=>(v(),N)[f>>>3>>>0];default:throw new TypeError(`invalid integer width (${l}): ${o}`)}};function hc(o,l,d,f,g){o>>>=0,d>>>=0,l=et(l>>>0);let y=x=>x;if(f=f===0n){let x=8*d;y=k=>BigInt.asUintN(x,k),g=y(g)}ot(o,{name:l,Mc:y,Sc:(x,k)=>(typeof k=="number"&&(k=BigInt(k)),k),Rc:va(l,d,!f),Tc:null})}function pc(o,l,d,f){ot(o>>>=0,{name:l=et(l>>>0),Mc:function(g){return!!g},Sc:function(g,y){return y?d:f},Rc:function(g){return this.Mc((v(),q)[g>>>0])},Tc:null})}var ba=[],Lt=[0,1,,1,null,1,!0,1,!1,1];function pn(o){9<(o>>>=0)&&--Lt[o+1]==0&&(Lt[o]=void 0,ba.push(o))}var Ue=o=>{if(!o)throw new $t(`Cannot use deleted val. handle = ${o}`);return Lt[o]},Xe=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=ba.pop()||Lt.length;return Lt[l]=o,Lt[l+1]=1,l}};function _n(o){return this.Mc((v(),S)[o>>>2>>>0])}var _c={name:"emscripten::val",Mc:o=>{var l=Ue(o);return pn(o),l},Sc:(o,l)=>Xe(l),Rc:_n,Tc:null};function mc(o){return ot(o>>>0,_c)}var gc=(o,l)=>{switch(l){case 4:return function(d){return this.Mc((v(),D)[d>>>2>>>0])};case 8:return function(d){return this.Mc((v(),Y)[d>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${o}`)}};function wc(o,l,d){d>>>=0,ot(o>>>=0,{name:l=et(l>>>0),Mc:f=>f,Sc:(f,g)=>g,Rc:gc(l,d),Tc:null})}function yc(o,l,d,f,g){o>>>=0,d>>>=0,l=et(l>>>0);let y=k=>k;if(f===0){var x=32-8*d;y=k=>k<>>x,g=y(g)}ot(o,{name:l,Mc:y,Sc:(k,L)=>L,Rc:va(l,d,f!==0),Tc:null})}function vc(o,l,d){function f(y){var x=(v(),S)[y>>>2>>>0];return y=(v(),S)[y+4>>>2>>>0],new g((v(),U).buffer,y,x)}var g=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];ot(o>>>=0,{name:d=et(d>>>0),Mc:f,Rc:f},{de:!0})}var it=(o,l,d)=>{var f=(v(),q);if(l>>>=0,0=x){if(l>=d)break;f[l++>>>0]=x}else if(2047>=x){if(l+1>=d)break;f[l++>>>0]=192|x>>6,f[l++>>>0]=128|63&x}else if(65535>=x){if(l+2>=d)break;f[l++>>>0]=224|x>>12,f[l++>>>0]=128|x>>6&63,f[l++>>>0]=128|63&x}else{if(l+3>=d)break;f[l++>>>0]=240|x>>18,f[l++>>>0]=128|x>>12&63,f[l++>>>0]=128|x>>6&63,f[l++>>>0]=128|63&x,y++}}f[l>>>0]=0,o=l-g}else o=0;return o},lt=o=>{for(var l=0,d=0;d=f?l++:2047>=f?l+=2:55296<=f&&57343>=f?(l+=4,++d):l+=3}return l};function bc(o,l){ot(o>>>=0,{name:l=et(l>>>0),Mc(d){var f=(v(),S)[d>>>2>>>0];return f=Bt(d+4,f,!0),Je(d),f},Sc(d,f){f instanceof ArrayBuffer&&(f=new Uint8Array(f));var g=typeof f=="string";if(!(g||ArrayBuffer.isView(f)&&f.BYTES_PER_ELEMENT==1))throw new $t("Cannot pass non-string to std::string");var y=g?lt(f):f.length,x=Rt(4+y+1),k=x+4;return(v(),S)[x>>>2>>>0]=y,g?it(f,k,y+1):(v(),q).set(f,k>>>0),d!==null&&d.push(Je,x),x},Rc:_n,Tc(d){Je(d)}})}var Ma=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Mc=(o,l,d)=>{if(o>>>=1,16<(l=aa((v(),H),o,l/2,d))-o&&Ma)return Ma.decode((v(),H).slice(o,l));for(d="";o>>0];d+=String.fromCharCode(f)}return d},xc=(o,l,d)=>{if(d??=2147483647,2>d)return 0;var f=l;d=(d-=2)<2*o.length?d/2:o.length;for(var g=0;g>>1>>>0]=y,l+=2}return(v(),ne)[l>>>1>>>0]=0,l-f},Tc=o=>2*o.length,Ec=(o,l,d)=>{var f="";o>>>=2;for(var g=0;!(g>=l/4);g++){var y=(v(),S)[o+g>>>0];if(!y&&!d)break;f+=String.fromCodePoint(y)}return f},kc=(o,l,d)=>{if(l>>>=0,d??=2147483647,4>d)return 0;var f=l;d=f+d-4;for(var g=0;g>>2>>>0]=y,(l+=4)+4>d)break}return(v(),I)[l>>>2>>>0]=0,l-f},Cc=o=>{for(var l=0,d=0;d>>=0,l>>>=0,d=et(d>>>=0),l===2)var f=Mc,g=xc,y=Tc;else f=Ec,g=kc,y=Cc;ot(o,{name:d,Mc:x=>{var k=(v(),S)[x>>>2>>>0];return k=f(x+4,k*l,!0),Je(x),k},Sc:(x,k)=>{if(typeof k!="string")throw new $t(`Cannot pass non-string to C++ string type ${d}`);var L=y(k),B=Rt(4+L+l);return(v(),S)[B>>>2>>>0]=L/l,g(k,B+4,L+l),x!==null&&x.push(Je,B),B},Rc:_n,Tc(x){Je(x)}})}function Sc(o,l){ot(o>>>=0,{ee:!0,name:l=et(l>>>0),Mc:()=>{},Sc:()=>{}})}function Pc(o){Fn(o>>>0,!n,1,!r,131072,!1),Js()}var Le=o=>{if(!F)try{if(o(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function mn(o){o>>>=0,Fc||(Atomics.waitAsync((v(),I),o>>>2,o).value.then(Fr),o+=128,Atomics.store((v(),I),o>>>2,1))}var Fr=()=>Le(()=>{var o=$r();o&&(mn(o),co())});function Ic(o,l){(o>>>=0)==l>>>0?setTimeout(Fr):s?postMessage({Vc:o,Oc:"checkMailbox"}):(o=It[o])&&o.postMessage({Oc:"checkMailbox"})}var gn=[];function Lc(o,l,d,f,g){for(l>>>=0,g>>>=0,gn.length=0,d=g>>>3,f=g+f>>>3;d>>0]?(v(),se)[d++>>>0]:(v(),Y)[d++>>>0],gn.push(y)}return(l?Bn[l]:md[o])(...gn)}var Oc=()=>{ie=0};function Nc(o){o>>>=0,s?postMessage({Oc:"cleanupThread",he:o}):Xs(It[o])}function Bc(o){}var Ir=o=>{try{o()}catch(l){me(l)}};function $c(o){var l=(...d)=>{Lr.push(o);try{return o(...d)}finally{F||(Lr.pop(),tt&&Mt===1&&Lr.length===0&&(Mt=0,ie+=1,Ir(Jo),typeof Fibers<"u"&&Fibers.Ce()))}};return Ea.set(o,l),l}var Mt=0,tt=null,xa=0,Lr=[],wn=new Map,Ta=new Map,Ea=new Map,Dc=0,yn=null,Rc=[],ka=o=>(function(l){if(!F){if(Mt===0){var d=!1,f=!1;l((g=0)=>{if(!F&&(xa=g,d=!0,f)){Mt=2,Ir(()=>Ko(tt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),g=!1;try{var y=(function(){var L=(v(),I)[tt+8>>>2>>>0];return L=Ta.get(L),L=Ea.get(L),--ie,L()})()}catch(L){y=L,g=!0}var x=!1;if(!tt){var k=yn;k&&(yn=null,(g?k.reject:k.resolve)(y),x=!0)}if(g&&!x)throw y}}),f=!0,d||(Mt=1,tt=(function(){var g=Rt(65548),y=g+12;if((v(),S)[g>>>2>>>0]=y,(v(),S)[g+4>>>2>>>0]=y+65536,y=Lr[0],!wn.has(y)){var x=Dc++;wn.set(y,x),Ta.set(x,y)}return y=wn.get(y),(v(),I)[g+8>>>2>>>0]=y,g})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ir(()=>Xo(tt)))}else Mt===2?(Mt=0,Ir(Zo),Je(tt),tt=null,Rc.forEach(Le)):me(`invalid state: ${Mt}`);return xa}})(l=>{o().then(l)});function zc(o){return o>>>=0,ka(async()=>{var l=await Ue(o);return Xe(l)})}var vn=[],Gc=o=>{var l=vn.length;return vn.push(o),l},Uc=(o,l)=>{for(var d=Array(o),f=0;f>>2>>>0],x=hn[y];if(x===void 0)throw o=`parameter ${f}`,y=ja(y),l=et(y),Je(y),new $t(`${o} has unknown type ${l}`);d[g]=x}return d},Vc=(o,l,d)=>{var f=[];return o=o(f,d),f.length&&((v(),S)[l>>>2>>>0]=Xe(f)),o},Wc={},Or=o=>{var l=Wc[o];return l===void 0?et(o):l};function jc(o,l,d){var[f,...g]=Uc(o,l>>>0);l=f.Sc.bind(f);var y=g.map(L=>L.Rc.bind(L));o--;var x={toValue:Ue};switch(o=y.map((L,B)=>{var re=`argFromPtr${B}`;return x[re]=L,`${re}(args${B?"+"+8*B:""})`}),d){case 0:var k="toValue(handle)";break;case 2:k="new (toValue(handle))";break;case 3:k="";break;case 1:x.getStringOrSymbol=Or,k="toValue(handle)[getStringOrSymbol(methodName)]"}return k+=`(${o})`,f.ee||(x.toReturnWire=l,x.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`),k=`return function (handle, methodName, destructorsRef, args) { ${k} }`,d=new Function(Object.keys(x),k)(...Object.values(x)),k=`methodCaller<(${g.map(L=>L.name)}) => ${f.name}>`,Gc(Object.defineProperty(d,"name",{value:k}))}function qc(o,l){return l>>>=0,(o=Ue(o>>>0))==Ue(l)}function Hc(o){return(o>>>=0)?(o=Or(o),Xe(globalThis[o])):Xe(globalThis)}function Qc(o){return o=Or(o>>>0),Xe(t[o])}function Yc(o,l){return l>>>=0,o=Ue(o>>>0),l=Ue(l),Xe(o[l])}function Xc(o){9<(o>>>=0)&&(Lt[o+1]+=1)}function Ca(o,l,d,f,g){return vn[o>>>0](l>>>0,d>>>0,f>>>0,g>>>0)}function Jc(o,l,d,f,g){return Ca(o>>>0,l>>>0,d>>>0,f>>>0,g>>>0)}function Kc(){return Xe([])}function Zc(o){o=Ue(o>>>0);for(var l=Array(o.length),d=0;d>>0))}function tu(){return Xe({})}function ru(o){for(var l=Ue(o>>>=0);l.length;){var d=l.pop();l.pop()(d)}pn(o)}function nu(o,l,d){l>>>=0,d>>>=0,o=Ue(o>>>0),l=Ue(l),d=Ue(d),o[l]=d}function su(o,l){o=Ce(o),l>>>=0,o=new Date(1e3*o),(v(),I)[l>>>2>>>0]=o.getUTCSeconds(),(v(),I)[l+4>>>2>>>0]=o.getUTCMinutes(),(v(),I)[l+8>>>2>>>0]=o.getUTCHours(),(v(),I)[l+12>>>2>>>0]=o.getUTCDate(),(v(),I)[l+16>>>2>>>0]=o.getUTCMonth(),(v(),I)[l+20>>>2>>>0]=o.getUTCFullYear()-1900,(v(),I)[l+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),I)[l+28>>>2>>>0]=o}var Aa=o=>o%4==0&&(o%100!=0||o%400==0),Sa=[0,31,60,91,121,152,182,213,244,274,305,335],Pa=[0,31,59,90,120,151,181,212,243,273,304,334];function au(o,l){o=Ce(o),l>>>=0,o=new Date(1e3*o),(v(),I)[l>>>2>>>0]=o.getSeconds(),(v(),I)[l+4>>>2>>>0]=o.getMinutes(),(v(),I)[l+8>>>2>>>0]=o.getHours(),(v(),I)[l+12>>>2>>>0]=o.getDate(),(v(),I)[l+16>>>2>>>0]=o.getMonth(),(v(),I)[l+20>>>2>>>0]=o.getFullYear()-1900,(v(),I)[l+24>>>2>>>0]=o.getDay();var d=(Aa(o.getFullYear())?Sa:Pa)[o.getMonth()]+o.getDate()-1|0;(v(),I)[l+28>>>2>>>0]=d,(v(),I)[l+36>>>2>>>0]=-60*o.getTimezoneOffset(),d=new Date(o.getFullYear(),6,1).getTimezoneOffset();var f=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(d!=f&&o.getTimezoneOffset()==Math.min(f,d)),(v(),I)[l+32>>>2>>>0]=o}function ou(o){o>>>=0;var l=new Date((v(),I)[o+20>>>2>>>0]+1900,(v(),I)[o+16>>>2>>>0],(v(),I)[o+12>>>2>>>0],(v(),I)[o+8>>>2>>>0],(v(),I)[o+4>>>2>>>0],(v(),I)[o>>>2>>>0],0),d=(v(),I)[o+32>>>2>>>0],f=l.getTimezoneOffset(),g=new Date(l.getFullYear(),6,1).getTimezoneOffset(),y=new Date(l.getFullYear(),0,1).getTimezoneOffset(),x=Math.min(y,g);return 0>d?(v(),I)[o+32>>>2>>>0]=+(g!=y&&x==f):0>>2>>>0]=l.getDay(),d=(Aa(l.getFullYear())?Sa:Pa)[l.getMonth()]+l.getDate()-1|0,(v(),I)[o+28>>>2>>>0]=d,(v(),I)[o>>>2>>>0]=l.getSeconds(),(v(),I)[o+4>>>2>>>0]=l.getMinutes(),(v(),I)[o+8>>>2>>>0]=l.getHours(),(v(),I)[o+12>>>2>>>0]=l.getDate(),(v(),I)[o+16>>>2>>>0]=l.getMonth(),(v(),I)[o+20>>>2>>>0]=l.getYear(),o=l.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Fa(o,l,d,f,g,y,x){return s?le(16,1,o,l,d,f,g,y,x):-52}function Ia(o,l,d,f,g,y){if(s)return le(17,1,o,l,d,f,g,y)}var ar={},iu=()=>performance.timeOrigin+performance.now();function La(o,l){if(s)return le(18,1,o,l);if(ar[o]&&(clearTimeout(ar[o].id),delete ar[o]),!l)return 0;var d=setTimeout(()=>{delete ar[o],Le(()=>lo(o,performance.timeOrigin+performance.now()))},l);return ar[o]={id:d,Be:l},0}function lu(o,l,d,f){o>>>=0,l>>>=0,d>>>=0,f>>>=0;var g=new Date().getFullYear(),y=new Date(g,0,1).getTimezoneOffset();g=new Date(g,6,1).getTimezoneOffset();var x=Math.max(y,g);(v(),S)[o>>>2>>>0]=60*x,(v(),I)[l>>>2>>>0]=+(y!=g),o=(l=k=>{var L=Math.abs(k);return`UTC${0<=k?"-":"+"}${String(Math.floor(L/60)).padStart(2,"0")}${String(L%60).padStart(2,"0")}`})(y),l=l(g),gDate.now();function uu(o,l,d){return d>>>=0,0<=o&&3>=o?(o===0?o=Date.now():o=performance.timeOrigin+performance.now(),o=Math.round(1e6*o),(v(),se)[d>>>3>>>0]=BigInt(o),0):28}var bn=[],Oa=(o,l)=>{bn.length=0;for(var d;d=(v(),q)[o++>>>0];){var f=d!=105;l+=(f&=d!=112)&&l%8?4:0,bn.push(d==112?(v(),S)[l>>>2>>>0]:d==106?(v(),se)[l>>>3>>>0]:d==105?(v(),I)[l>>>2>>>0]:(v(),Y)[l>>>3>>>0]),l+=f?8:4}return bn};function du(o,l,d){return o>>>=0,l=Oa(l>>>0,d>>>0),Bn[o](...l)}function fu(o,l,d){return o>>>=0,l=Oa(l>>>0,d>>>0),Bn[o](...l)}var hu=()=>{};function pu(o,l){return A(Bt(o>>>0,l>>>0))}var _u=()=>{throw ie+=1,"unwind"};function mu(){return 4294901760}var gu=()=>1,wu=()=>navigator.hardwareConcurrency;function yu(o){o>>>=0;var l=(v(),q).length;if(o<=l||4294901760=d;d*=2){var f=l*(1+.2/d);f=Math.min(f,o+100663296);e:{f=(Math.min(4294901760,65536*Math.ceil(Math.max(o,f)/65536))-bt.buffer.byteLength+65535)/65536|0;try{bt.grow(f),Q();var g=1;break e}catch{}g=void 0}if(g)return!0}return!1}var rt=o=>{var l=lt(o)+1,d=Dr(l);return it(o,d,l),d},Mn=(o,l)=>{(v(),S)[o>>>2>>>0]=l;var d=(v(),S)[o>>>2>>>0];(v(),S)[o+4>>>2>>>0]=(l-d)/4294967296},or=o=>(v(),S)[o>>>2>>>0]+4294967296*(v(),I)[o+4>>>2>>>0],Ae=[],vu=(o,l)=>{Ae[o>>>0]=l},ct=[],Nr=[],Dt=(o,l)=>{Nr[o]=new Promise(d=>l.finally(()=>d(o)))},W=o=>{if(o)return Ae[o>>>0]},bu=(o,l)=>{for(o=(v(),S)[o>>>2>>>0];o;o=(v(),S)[o>>>2>>>0])l[(v(),I)[o+4>>>2>>>0]](o)},Br=(o,l,d)=>{(v(),S)[o>>>2>>>0]=l,(v(),S)[o+4>>>2>>>0]=d},Na=o=>{var l=(v(),S)[o>>>2>>>0];return o=(v(),S)[o+4>>>2>>>0],Bt(l,o)},ut=o=>{var l=(v(),S)[o>>>2>>>0];return o=(v(),S)[o+4>>>2>>>0],l?Bt(l,o):o===0?"":void 0},Mu=o=>{var l=ut(o+4),d=(d=(v(),S)[o+12>>>2>>>0])?W(d):"auto";if(o+=16){var f=W((v(),S)[o+4>>>2>>>0]),g=(v(),S)[o+16>>>2>>>0],y=(v(),S)[o+20>>>2>>>0];if(g){for(var x={},k=0;k>>3>>>0]}g=x}else g=void 0;o={module:f,constants:g,entryPoint:ut(o+8)}}else o=void 0;return{label:l,layout:d,compute:o}},Ba=(o,l)=>{function d(f,g){f=o[f],(v(),S)[l+g>>>2>>>0]=f}d("maxTextureDimension1D",4),d("maxTextureDimension2D",8),d("maxTextureDimension3D",12),d("maxTextureArrayLayers",16),d("maxBindGroups",20),d("maxBindGroupsPlusVertexBuffers",24),d("maxBindingsPerBindGroup",28),d("maxDynamicUniformBuffersPerPipelineLayout",32),d("maxDynamicStorageBuffersPerPipelineLayout",36),d("maxSampledTexturesPerShaderStage",40),d("maxSamplersPerShaderStage",44),d("maxStorageBuffersPerShaderStage",48),d("maxStorageTexturesPerShaderStage",52),d("maxUniformBuffersPerShaderStage",56),d("minUniformBufferOffsetAlignment",80),d("minStorageBufferOffsetAlignment",84),Mn(l+64,o.maxUniformBufferBindingSize),Mn(l+72,o.maxStorageBufferBindingSize),d("maxVertexBuffers",88),Mn(l+96,o.maxBufferSize),d("maxVertexAttributes",104),d("maxVertexBufferArrayStride",108),d("maxInterStageShaderVariables",112),d("maxColorAttachments",116),d("maxColorAttachmentBytesPerSample",120),d("maxComputeWorkgroupStorageSize",124),d("maxComputeInvocationsPerWorkgroup",128),d("maxComputeWorkgroupSizeX",132),d("maxComputeWorkgroupSizeY",136),d("maxComputeWorkgroupSizeZ",140),d("maxComputeWorkgroupsPerDimension",144),o.ze!==void 0&&d("maxImmediateSize",148)},xu=[,"validation","out-of-memory","internal"],Tu=[,"compatibility","core"],$a={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},Eu=[,"low-power","high-performance"],ku=[,"occlusion","timestamp"],Cu={undefined:1,unknown:1,destroyed:2};function Au(o,l,d,f,g,y){l=Ce(l),d=Ce(d),f>>>=0,g>>>=0,y>>>=0;var x=W(o>>>0);if(o={},y){var k=(v(),S)[y+12>>>2>>>0];if(k){var L=(v(),S)[y+16>>>2>>>0];o.requiredFeatures=Array.from((v(),S).subarray(L>>>2>>>0,L+4*k>>>2>>>0),R=>$a[R])}var B=(v(),S)[y+20>>>2>>>0];if(B){let R=function(ce,Me,cr=!1){Me=B+Me,(Me=(v(),S)[Me>>>2>>>0])==4294967295||cr&&Me==0||(re[ce]=Me)},ee=function(ce,Me){Me=B+Me;var cr=(v(),S)[Me>>>2>>>0],$n=(v(),S)[Me+4>>>2>>>0];cr==4294967295&&$n==4294967295||(re[ce]=or(Me))};var re={};R("maxTextureDimension1D",4),R("maxTextureDimension2D",8),R("maxTextureDimension3D",12),R("maxTextureArrayLayers",16),R("maxBindGroups",20),R("maxBindGroupsPlusVertexBuffers",24),R("maxDynamicUniformBuffersPerPipelineLayout",32),R("maxDynamicStorageBuffersPerPipelineLayout",36),R("maxSampledTexturesPerShaderStage",40),R("maxSamplersPerShaderStage",44),R("maxStorageBuffersPerShaderStage",48),R("maxStorageTexturesPerShaderStage",52),R("maxUniformBuffersPerShaderStage",56),R("minUniformBufferOffsetAlignment",80),R("minStorageBufferOffsetAlignment",84),ee("maxUniformBufferBindingSize",64),ee("maxStorageBufferBindingSize",72),R("maxVertexBuffers",88),ee("maxBufferSize",96),R("maxVertexAttributes",104),R("maxVertexBufferArrayStride",108),R("maxInterStageShaderVariables",112),R("maxColorAttachments",116),R("maxColorAttachmentBytesPerSample",120),R("maxComputeWorkgroupStorageSize",124),R("maxComputeInvocationsPerWorkgroup",128),R("maxComputeWorkgroupSizeX",132),R("maxComputeWorkgroupSizeY",136),R("maxComputeWorkgroupSizeZ",140),R("maxComputeWorkgroupsPerDimension",144),R("maxImmediateSize",148,!0),o.requiredLimits=re}(k=(v(),S)[y+24>>>2>>>0])&&(k={label:ut(k+4)},o.defaultQueue=k),o.label=ut(y+4)}ie+=1,Dt(l,x.requestDevice(o).then(R=>{--ie,Le(()=>{Ae[g>>>0]=R.queue,Ae[f>>>0]=R,ie+=1,Dt(d,R.lost.then(ee=>{Le(()=>{R.onuncapturederror=()=>{};var ce=J(),Me=rt(ee.message);Cn(d,Cu[ee.reason],Me),X(ce)}),--ie})),R.onuncapturederror=ee=>{var ce=5;ee.error instanceof GPUValidationError?ce=2:ee.error instanceof GPUOutOfMemoryError?ce=3:ee.error instanceof GPUInternalError&&(ce=4);var Me=J();ee=rt(ee.error.message),so(f,ce,ee),X(Me)},"adapterInfo"in R||(R.adapterInfo=x.info),Pn(l,1,f,0)})},R=>{--ie,Le(()=>{var ee=J(),ce=rt(R.message);Pn(l,3,f,ce),d&&Cn(d,4,ce),X(ee)})}))}function Su(o){var l=W(o>>>=0),d=ct[o];if(d){for(var f=0;f>>=0;var f=W(o>>>=0);d==4294967295&&(d=void 0);try{var g=f.getMappedRange(l>>>0,d)}catch{return 0}var y=Ln(16,g.byteLength);return(v(),q).set(new Uint8Array(g),y>>>0),ct[o].push(()=>Je(y)),y}function Fu(o,l,d){d>>>=0;var f=W(o>>>=0);d==4294967295&&(d=void 0);try{var g=f.getMappedRange(l>>>0,d)}catch{return 0}var y=Ln(16,g.byteLength);return(v(),q).fill(0,y,g.byteLength),ct[o].push(()=>{new Uint8Array(g).set((v(),q).subarray(y>>>0,y+g.byteLength>>>0)),Je(y)}),y}function Iu(o,l,d,f,g){o>>>=0,l=Ce(l),d=Ce(d),g>>>=0;var y=W(o);ct[o]=[],g==4294967295&&(g=void 0),ie+=1,Dt(l,y.mapAsync(d,f>>>0,g).then(()=>{--ie,Le(()=>{An(l,1,0)})},x=>{--ie,Le(()=>{J();var k=rt(x.message);An(l,x.name==="AbortError"?4:x.name==="OperationError"?3:0,k),delete ct[o]})}))}function Lu(o){var l=W(o>>>=0),d=ct[o];if(d){for(var f=0;f>>0]}function Nu(o,l,d){o>>>=0,l>>>=0,d>>>=0;var f=!!(v(),S)[l+32>>>2>>>0];l={label:ut(l+4),usage:(v(),S)[l+16>>>2>>>0],size:or(l+24),mappedAtCreation:f},o=W(o);try{var g=o.createBuffer(l)}catch{return!1}return Ae[d>>>0]=g,f&&(ct[d]=[]),!0}function Bu(o,l,d,f){o>>>=0,l=Ce(l),f>>>=0,d=Mu(d>>>0),o=W(o),ie+=1,Dt(l,o.createComputePipelineAsync(d).then(g=>{--ie,Le(()=>{Ae[f>>>0]=g,kn(l,1,f,0)})},g=>{--ie,Le(()=>{var y=J(),x=rt(g.message);kn(l,g.reason==="validation"?3:g.reason==="internal"?4:0,f,x),X(y)})}))}function $u(o,l,d){o>>>=0,l>>>=0,d>>>=0;var f=(v(),S)[l>>>2>>>0],g=(v(),I)[f+4>>>2>>>0];l={label:ut(l+4),code:""},g===2&&(l.code=Na(f+8)),o=W(o).createShaderModule(l),Ae[d>>>0]=o}var Du=o=>{(o=W(o)).onuncapturederror=null,o.destroy()};function Ru(o,l){l=Ce(l),o=W(o>>>0),ie+=1,Dt(l,o.popErrorScope().then(d=>{--ie,Le(()=>{var f=5;d?d instanceof GPUValidationError?f=2:d instanceof GPUOutOfMemoryError?f=3:d instanceof GPUInternalError&&(f=4):f=1;var g=J(),y=d?rt(d.message):0;Sn(l,1,f,y),X(g)})},d=>{--ie,Le(()=>{var f=J(),g=rt(d.message);Sn(l,1,5,g),X(f)})}))}function zu(o,l,d,f){if(l=Ce(l),f>>>=0,d>>>=0){var g={featureLevel:Tu[(v(),I)[d+4>>>2>>>0]],powerPreference:Eu[(v(),I)[d+8>>>2>>>0]],forceFallbackAdapter:!!(v(),S)[d+12>>>2>>>0]};(o=(v(),S)[d>>>2>>>0])!==0&&(v(),g.Ee=!!(v(),S)[o+8>>>2>>>0])}"gpu"in navigator?(ie+=1,Dt(l,navigator.gpu.requestAdapter(g).then(y=>{--ie,Le(()=>{if(y)Ae[f>>>0]=y,ir(l,1,f,0);else{var x=J(),k=rt("WebGPU not available on this browser (requestAdapter returned null)");ir(l,3,f,k),X(x)}})},y=>{--ie,Le(()=>{var x=J(),k=rt(y.message);ir(l,4,f,k),X(x)})}))):(g=J(),o=rt("WebGPU not available on this browser (navigator.gpu is not available)"),ir(l,3,f,o),X(g))}function Gu(o,l,d){return o>>>=0,l>>>=0,d>>>=0,ka(async()=>{var f=[];if(d){var g=(v(),I)[d>>>2>>>0];f.length=l+1,f[l]=new Promise(k=>setTimeout(k,g,0))}else f.length=l;for(var y=0;y{if(!xn){var o,l={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(o in Tn)Tn[o]===void 0?delete l[o]:l[o]=Tn[o];var d=[];for(o in l)d.push(`${o}=${l[o]}`);xn=d}return xn};function Ra(o,l){if(s)return le(19,1,o,l);o>>>=0,l>>>=0;var d,f=0,g=0;for(d of Da()){var y=l+f;(v(),S)[o+g>>>2>>>0]=y,f+=it(d,y,1/0)+1,g+=4}return 0}function za(o,l){if(s)return le(20,1,o,l);o>>>=0,l>>>=0;var d=Da();for(var f of((v(),S)[o>>>2>>>0]=d.length,o=0,d))o+=lt(f)+1;return(v(),S)[l>>>2>>>0]=o,0}function Ga(o){return s?le(21,1,o):52}function Ua(o,l,d,f){return s?le(22,1,o,l,d,f):52}function Va(o,l,d,f){return s?le(23,1,o,l,d,f):70}var Uu=[null,[],[]];function Wa(o,l,d,f){if(s)return le(24,1,o,l,d,f);l>>>=0,d>>>=0,f>>>=0;for(var g=0,y=0;y>>2>>>0],k=(v(),S)[l+4>>>2>>>0];l+=8;for(var L=0;L>>0],R=Uu[B];re===0||re===10?((B===1?P:A)(oa(R)),R.length=0):R.push(re)}g+=k}return(v(),S)[f>>>2>>>0]=g,0}function Vu(o){return o>>>0}function Wu(o,l){return Ba(W(o>>>0).limits,l>>>0),1}function ju(o,l){return W(o>>>0).features.has($a[l])}function qu(o){return BigInt(W(o>>>0).size)}function Hu(o){return BigInt(W(o>>>0).usage)}function Qu(o,l){if(o>>>=0,l>>>=0){var d=ut(l+4);d={label:d,timestampWrites:l=(l=(v(),S)[l+12>>>2>>>0])!==0?{querySet:W((v(),S)[l+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),S)[l+8>>>2>>>0],endOfPassWriteIndex:(v(),S)[l+12>>>2>>>0]}:void 0}}return l=W(o),o=Za(0),d=l.beginComputePass(d),Ae[o>>>0]=d,o}function Yu(o,l,d,f){d=Ce(d),(f=Ce(f))==-1&&(f=void 0),(o=W(o>>>0)).clearBuffer(W(l>>>0),d,f)}function Xu(o,l,d,f,g,y){d=Ce(d),g=Ce(g),y=Ce(y),W(o>>>0).copyBufferToBuffer(W(l>>>0),d,W(f>>>0),g,y)}function Ju(o){var l=W(o>>>0);return o=Ja(0),l=l.finish(),Ae[o>>>0]=l,o}function Ku(o,l,d,f,g,y){y=Ce(y),W(o>>>0).resolveQuerySet(W(l>>>0),d,f,W(g>>>0),y)}function Zu(o,l,d,f){W(o>>>0).dispatchWorkgroups(l,d,f)}function ed(o,l,d){d=Ce(d),W(o>>>0).dispatchWorkgroupsIndirect(W(l>>>0),d)}function td(o){W(o>>>0).end()}function rd(o,l,d,f,g){f>>>=0,g>>>=0,o=W(o>>>0),d=W(d>>>0),f==0?o.setBindGroup(l,d):o.setBindGroup(l,d,(v(),S),g>>>2,f)}function nd(o,l){W(o>>>0).setPipeline(W(l>>>0))}function sd(o,l,d){W(o>>>0).De(W(l>>>0),d)}function ad(o,l){var d=W(o>>>0);return o=Xa(0),l=d.getBindGroupLayout(l),Ae[o>>>0]=l,o}function od(o,l){function d(g){var y=(v(),S)[g+8>>>2>>>0],x=(v(),S)[g+32>>>2>>>0],k=(v(),S)[g+36>>>2>>>0],L=0;return bu(g,{327681:B=>{L=(v(),S)[B+8>>>2>>>0]}}),y?((x=or(g+24))==-1&&(x=void 0),y={buffer:W(y),offset:or(g+16),size:x}):y=W(x||k||L),{binding:(v(),S)[g+4>>>2>>>0],resource:y}}o>>>=0,l={label:ut(4+(l>>>=0)),layout:W((v(),S)[l+12>>>2>>>0]),entries:(function(g,y){for(var x=[],k=0;k>>2>>>0],(v(),S)[l+20>>>2>>>0])},o=W(o);var f=Ya(0);return vu(f,o.createBindGroup(l)),f}function id(o,l){var d;return o>>>=0,(l>>>=0)&&(d={label:ut(l+4)}),l=W(o),o=Ka(0),d=l.createCommandEncoder(d),Ae[o>>>0]=d,o}function ld(o,l){o>>>=0,l>>>=0,l={type:ku[(v(),I)[l+12>>>2>>>0]],count:(v(),S)[l+16>>>2>>>0]};var d=W(o);return o=eo(0),l=d.createQuerySet(l),Ae[o>>>0]=l,o}function cd(o,l){o=W(o>>>0).adapterInfo,l>>>=0,(v(),S)[l+52>>>2>>>0]=o.subgroupMinSize,(v(),S)[l+56>>>2>>>0]=o.subgroupMaxSize;var d=o.vendor+o.architecture+o.device+o.description,f=lt(d)+1,g=Rt(f);return g&&it(d,g,f),d=g,f=lt(o.vendor),Br(l+4,d,f),d+=f,f=lt(o.architecture),Br(l+12,d,f),d+=f,f=lt(o.device),Br(l+20,d,f),Br(l+28,d+f,lt(o.description)),(v(),I)[l+36>>>2>>>0]=2,o=o.isFallbackAdapter?3:4,(v(),I)[l+40>>>2>>>0]=o,(v(),S)[l+44>>>2>>>0]=0,(v(),S)[l+48>>>2>>>0]=0,1}var ud={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function dd(o,l){l>>>=0;var d=W(o>>>0);o=Rt(4*d.features.size);var f=0,g=0;for(let y of d.features)0<=(d=ud[y])&&((v(),I)[o+f>>>2>>>0]=d,f+=4,g++);(v(),S)[l+4>>>2>>>0]=o,(v(),S)[l>>>2>>>0]=g}function fd(o,l){return Ba(W(o>>>0).limits,l>>>0),1}function hd(o,l){W(o>>>0).pushErrorScope(xu[l])}function pd(o,l,d){l>>>=0,d>>>=0,o=W(o>>>0),l=Array.from((v(),I).subarray(d>>>2>>>0,d+4*l>>>2>>>0),f=>W(f)),o.submit(l)}function _d(o,l,d,f,g){d=Ce(d),f>>>=0,g>>>=0,o=W(o>>>0),l=W(l>>>0),f=(v(),q).subarray(f>>>0,f+g>>>0),o.writeBuffer(l,d,f,0,g)}s||(function(){for(var o=t.numThreads-1;o--;)Zs();qe.push(async()=>{var l=(async function(){if(!s)return Promise.all(vt.map(Ks))})();ue++,await l,--ue==0&&oe&&(l=oe,oe=null,l())})})(),s||(bt=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Q()),t.wasmBinary&&(_=t.wasmBinary),t.stackSave=()=>J(),t.stackRestore=o=>X(o),t.stackAlloc=o=>Dr(o),t.setValue=function(o,l,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":(v(),U)[o>>>0]=l;break;case"i16":(v(),ne)[o>>>1>>>0]=l;break;case"i32":(v(),I)[o>>>2>>>0]=l;break;case"i64":(v(),se)[o>>>3>>>0]=BigInt(l);break;case"float":(v(),D)[o>>>2>>>0]=l;break;case"double":(v(),Y)[o>>>3>>>0]=l;break;case"*":(v(),S)[o>>>2>>>0]=l;break;default:me(`invalid type for setValue: ${d}`)}},t.getValue=function(o,l="i8"){switch(l.endsWith("*")&&(l="*"),l){case"i1":case"i8":return(v(),U)[o>>>0];case"i16":return(v(),ne)[o>>>1>>>0];case"i32":return(v(),I)[o>>>2>>>0];case"i64":return(v(),se)[o>>>3>>>0];case"float":return(v(),D)[o>>>2>>>0];case"double":return(v(),Y)[o>>>3>>>0];case"*":return(v(),S)[o>>>2>>>0];default:me(`invalid type for getValue: ${l}`)}},t.UTF8ToString=Bt,t.stringToUTF8=it,t.lengthBytesUTF8=lt;var ja,qa,En,$r,Je,Rt,Ha,Qa,Ya,Xa,Ja,Ka,Za,eo,to,ro,no,kn,Cn,An,Sn,ir,Pn,so,Fn,ao,oo,io,In,lo,co,Ln,te,lr,uo,X,Dr,J,fo,On,ho,po,_o,Nn,mo,go,wo,yo,vo,bo,Mo,xo,To,Eo,ko,Co,Ao,So,Po,Fo,Io,Lo,Oo,No,Bo,$o,Do,Ro,zo,Go,Uo,Vo,Wo,jo,qo,Ho,Qo,Yo,Xo,Jo,Ko,Zo,dt,md=[gr,Hr,ra,ia,la,ca,ua,da,fa,ha,pa,_a,ma,ga,wa,ya,Fa,Ia,La,Ra,za,Ga,Ua,Va,Wa],Bn={963948:(o,l,d,f,g)=>{if(t===void 0||!t.Uc)return 1;if((o=Bt(Number(o>>>0))).startsWith("./")&&(o=o.substring(2)),!(o=t.Uc.get(o)))return 2;if(l=Number(l>>>0),d=Number(d>>>0),f=Number(f>>>0),l+d>o.byteLength)return 3;try{let y=o.subarray(l,l+d);switch(g){case 0:(v(),q).set(y,f>>>0);break;case 1:t.ad?t.ad(f,y):t.ne(f,y);break;default:return 4}return 0}catch{return 4}},964772:(o,l,d)=>{t.Sd(o,(v(),q).subarray(l>>>0,l+d>>>0))},964836:()=>t.le(),964878:o=>{t.jd(o)},964915:()=>typeof wasmOffsetConverter<"u"};function gd(o,l,d,f){var g=J();try{return xo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function wd(o,l,d){var f=J();try{return vo(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function yd(o){var l=J();try{mo(o)}catch(d){if(X(l),d!==d+0)throw d;te(1,0)}}function vd(o,l){var d=J();try{return Nn(o,l)}catch(f){if(X(d),f!==f+0)throw f;te(1,0)}}function bd(o,l,d){var f=J();try{_o(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Md(o,l){var d=J();try{To(o,l)}catch(f){if(X(d),f!==f+0)throw f;te(1,0)}}function xd(o,l,d,f,g,y,x){var k=J();try{return yo(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Td(o,l,d,f,g,y){var x=J();try{go(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Ed(o,l,d,f){var g=J();try{Mo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function kd(o,l,d,f,g,y,x){var k=J();try{ko(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Cd(o,l,d,f,g,y,x){var k=J();try{Co(o,l,d,f,g,y,x)}catch(L){if(X(k),L!==L+0)throw L;te(1,0)}}function Ad(o,l,d,f,g,y,x,k){var L=J();try{Bo(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Sd(o,l,d,f,g,y,x,k,L,B,re,R){var ee=J();try{Ao(o,l,d,f,g,y,x,k,L,B,re,R)}catch(ce){if(X(ee),ce!==ce+0)throw ce;te(1,0)}}function Pd(o,l,d,f,g){var y=J();try{return Eo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Fd(o,l,d,f,g){var y=J();try{wo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Id(o,l,d,f,g,y,x,k){var L=J();try{bo(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Ld(o){var l=J();try{return $o(o)}catch(d){if(X(l),d!==d+0)throw d;te(1,0)}}function Od(o,l,d){var f=J();try{return Do(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Nd(o,l){var d=J();try{return Yo(o,l)}catch(f){if(X(d),f!==f+0)throw f;return te(1,0),0n}}function Bd(o){var l=J();try{return So(o)}catch(d){if(X(l),d!==d+0)throw d;return te(1,0),0n}}function $d(o,l,d,f){var g=J();try{return Ro(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function Dd(o,l,d,f,g){var y=J();try{return zo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;te(1,0)}}function Rd(o,l,d,f,g,y){var x=J();try{return Go(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function zd(o,l,d,f,g,y){var x=J();try{return Oo(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Gd(o,l,d,f,g,y){var x=J();try{return Uo(o,l,d,f,g,y)}catch(k){if(X(x),k!==k+0)throw k;te(1,0)}}function Ud(o,l,d,f,g,y,x,k){var L=J();try{return No(o,l,d,f,g,y,x,k)}catch(B){if(X(L),B!==B+0)throw B;te(1,0)}}function Vd(o,l,d,f,g){var y=J();try{return Vo(o,l,d,f,g)}catch(x){if(X(y),x!==x+0)throw x;return te(1,0),0n}}function Wd(o,l,d,f){var g=J();try{return Wo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function jd(o,l,d,f){var g=J();try{return jo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function qd(o,l,d,f,g,y,x,k,L,B,re,R){var ee=J();try{return qo(o,l,d,f,g,y,x,k,L,B,re,R)}catch(ce){if(X(ee),ce!==ce+0)throw ce;te(1,0)}}function Hd(o,l,d,f,g,y,x,k,L,B,re){var R=J();try{Ho(o,l,d,f,g,y,x,k,L,B,re)}catch(ee){if(X(R),ee!==ee+0)throw ee;te(1,0)}}function Qd(o,l,d,f,g,y,x,k,L,B,re,R,ee,ce,Me,cr){var $n=J();try{Qo(o,l,d,f,g,y,x,k,L,B,re,R,ee,ce,Me,cr)}catch(Dn){if(X($n),Dn!==Dn+0)throw Dn;te(1,0)}}function Yd(o,l,d){var f=J();try{return Fo(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;return te(1,0),0n}}function Xd(o,l,d){var f=J();try{return Po(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Jd(o,l,d){var f=J();try{return Io(o,l,d)}catch(g){if(X(f),g!==g+0)throw g;te(1,0)}}function Kd(o,l,d,f){var g=J();try{Lo(o,l,d,f)}catch(y){if(X(g),y!==y+0)throw y;te(1,0)}}function Rr(){if(0{let l=new WeakMap,d,f,g=1;t.webgpuRegisterDevice=k=>{if(f!==void 0)throw Error("another WebGPU EP inference session is being created.");if(k){var L=l.get(k);if(!L){let B=((re,R=0)=>{var ee=no(R);return R=ro(R,ee),Ae[ee>>>0]=re.queue,Ae[R>>>0]=re,R})(k,L=Qa(0));L=[g++,L,B],l.set(k,L)}return d=k,f=L[0],L}d=void 0,f=0};let y=new Map;t.webgpuOnCreateSession=k=>{if(f!==void 0){var L=f;if(f=void 0,k){let B=En(L);y.set(k,B),L===0&&o(d??W(B))}d=void 0}},t.webgpuOnReleaseSession=k=>{y.delete(k)};let x=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(k,L,B)=>{if(B)return k[x]=[B,NaN],B;if(B=k[x])return B[1]++,B[0];if((L=y.get(L))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return L=((re,R=0)=>(re.mapState==="unmapped"||me(),R=to(R),Ae[R>>>0]=re,R))(k,L),k[x]=[L,1],L},t.webgpuUnregisterBuffer=k=>{let L=k[x];if(!L)throw Error("Buffer is not registered");L[1]--,L[1]===0&&(Ha(L[0]),delete k[x])},t.webgpuGetBuffer=k=>W(k),t.webgpuCreateDownloader=(k,L,B)=>{if((B=y.get(B))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let re=W(B),R=16*Math.ceil(Number(L)/16);return async()=>{let ee=re.createBuffer({size:R,usage:9});try{let ce=re.createCommandEncoder();return ce.copyBufferToBuffer(k,0,ee,0,R),re.queue.submit([ce.finish()]),await ee.mapAsync(GPUMapMode.READ),ee.getMappedRange().slice(0,L)}finally{ee.destroy()}}},t.ad=(k,L)=>{var B=L.buffer;let re=L.byteOffset,R=L.byteLength;if(L=16*Math.ceil(Number(R)/16),k=W(k),!d){var ee=En(f);d=W(ee)}let ce=(ee=d.createBuffer({mappedAtCreation:!0,size:L,usage:6})).getMappedRange();new Uint8Array(ce).set(new Uint8Array(B,re,R)),ee.unmap(),(B=d.createCommandEncoder()).copyBufferToBuffer(ee,0,k,0,L),d.queue.submit([B.finish()]),ee.destroy()}},t.webnnInit=o=>{let l=o[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=o.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=d=>l.onRunStart(d),t.webnnOnRunEnd=l.onRunEnd.bind(l),t.webnnOnReleaseSession=d=>{l.onReleaseSession(d)},t.webnnCreateMLTensorDownloader=(d,f)=>l.createMLTensorDownloader(d,f),t.webnnRegisterMLTensor=(d,f,g,y)=>l.registerMLTensor(d,f,g,y),t.webnnCreateMLContext=d=>l.createMLContext(d),t.webnnRegisterMLConstant=(d,f,g,y,x,k)=>l.registerMLConstant(d,f,g,y,x,t.Uc,k),t.webnnRegisterGraphInput=l.registerGraphInput.bind(l),t.webnnIsGraphInput=l.isGraphInput.bind(l),t.webnnRegisterGraphOutput=l.registerGraphOutput.bind(l),t.webnnIsGraphOutput=l.isGraphOutput.bind(l),t.webnnCreateTemporaryTensor=l.createTemporaryTensor.bind(l),t.webnnIsGraphInputOutputTypeSupported=l.isGraphInputOutputTypeSupported.bind(l)},z?t:new Promise((o,l)=>{b=o,M=l})}var kM,ow,iB=Ee(()=>{kM=aw,ow=globalThis.self?.name?.startsWith("em-pthread"),ow&&aw()}),Df,wh,iw,Ut,CM,Xi,lw,cw,Rf,uw,zf,AM,Gf,SM,vm=Ee(()=>{ym(),Df=typeof location>"u"?void 0:location.origin,wh=import.meta.url>"file:"&&import.meta.url<"file;",iw=()=>{{if(wh){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,Df).href}return import.meta.url}},Ut=iw(),CM=()=>{if(Ut&&!Ut.startsWith("blob:"))return Ut.substring(0,Ut.lastIndexOf("/")+1)},Xi=(e,t)=>{try{let r=t??Ut;return(r?new URL(e,r):new URL(e)).origin===Df}catch{return!1}},lw=(e,t)=>{let r=t??Ut;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},cw=(e,t)=>`${t??"./"}${e}`,Rf=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},uw=async e=>(await import(e)).default,zf=(oB(),bl(xM)).default,AM=async()=>{if(!Ut)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Xi(Ut))return[void 0,zf()];let e=await Rf(Ut);return[e,zf(e)]},Gf=(iB(),bl(EM)).default,SM=async(e,t,r,n)=>{let s=Gf&&!(e||t);if(s)if(Ut)s=Xi(Ut)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,Gf];{let a="ort-wasm-simd-threaded.asyncify.mjs",i=e??lw(a,t),c=r&&i&&!Xi(i,t),u=c?await Rf(i):i??cw(a,t);return[c?u:void 0,await uw(u)]}}}),Uf,Ji,li,Vf,dw,fw,hw,bm,Ge,ls=Ee(()=>{vm(),Ji=!1,li=!1,Vf=!1,dw=()=>{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}},fw=()=>{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}},hw=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},bm=async e=>{if(Ji)return Promise.resolve();if(li)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Vf)throw new Error("previous call to 'initializeWebAssembly()' failed.");li=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!hw())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fw())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=dw();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", 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=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s?.mjs,c=i?.href??i,u=s?.wasm,h=u?.href??u,p=e.wasmBinary,[_,m]=await SM(c,a,r>1,!!p||!!h),w=!1,b=[];if(t>0&&b.push(new Promise(M=>{setTimeout(()=>{w=!0,M()},t)})),b.push(new Promise((M,E)=>{let T={numThreads:r};if(p)T.wasmBinary=p,T.locateFile=C=>C;else if(h||a)T.locateFile=C=>h??a+C;else if(c&&c.indexOf("blob:")!==0)T.locateFile=C=>new URL(C,c).href;else if(_){let C=CM();C&&(T.locateFile=P=>C+P)}m(T).then(C=>{li=!1,Ji=!0,Uf=C,M(),_&&URL.revokeObjectURL(_)},C=>{li=!1,Vf=!0,E(C)})})),await Promise.race(b),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ge=()=>{if(Ji&&Uf)return Uf;throw new Error("WebAssembly is not initialized yet.")}}),Wt,Ml,Ie,Mm=Ee(()=>{ls(),Wt=(e,t)=>{let r=Ge(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ml=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")Ml(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Ie=e=>{let t=Ge(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),i=t.getValue(s+n,"*"),c=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(r)}}}),PM,lB=Ee(()=>{ls(),Mm(),PM=e=>{let t=Ge(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Wt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Ie("Can't create run options."),e?.extra!==void 0&&Ml(e.extra,"",new WeakSet,(i,c)=>{let u=Wt(i,n),h=Wt(c,n);t._OrtAddRunConfigEntry(r,u,h)!==0&&Ie(`Can't set a run config entry: ${i} - ${c}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),pw,_w,mw,Ki,en,gw,FM,cB=Ee(()=>{ls(),Mm(),pw=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},_w=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},mw=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ki=(e,t,r,n)=>{let s=Wt(t,n),a=Wt(r,n);Ge()._OrtAddSessionConfigEntry(e,s,a)!==0&&Ie(`Can't set a session config entry: ${t} - ${r}.`)},en=(e,t,r,n)=>{let s=Wt(t,n),a=Wt(r,n);e.push([s,a])},gw=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,i=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let _=s?.deviceType;_&&Ki(e,"deviceType",_,r)}break;case"webgpu":{a="WebGPU";let _;if(typeof s!="string"){let w=s;if(w.device)if(typeof GPUDevice<"u"&&w.device instanceof GPUDevice)_=w.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:b}=t;if(typeof b=="boolean"&&b&&en(i,"enableGraphCapture","1",r),typeof w.preferredLayout=="string"&&en(i,"preferredLayout",w.preferredLayout,r),w.forceCpuNodeNames){let M=Array.isArray(w.forceCpuNodeNames)?w.forceCpuNodeNames:[w.forceCpuNodeNames];en(i,"forceCpuNodeNames",M.join(` `),r)}w.validationMode&&en(i,"validationMode",w.validationMode,r)}let m=Ge().webgpuRegisterDevice(_);if(m){let[w,b,M]=m;en(i,"deviceId",w.toString(),r),en(i,"webgpuInstance",b.toString(),r),en(i,"webgpuDevice",M.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let c=Wt(a,r),u=i.length,h=0,p=0;if(u>0){h=Ge()._malloc(u*Ge().PTR_SIZE),r.push(h),p=Ge()._malloc(u*Ge().PTR_SIZE),r.push(p);for(let _=0;_{let t=Ge(),r=0,n=[],s=e||{};mw(s);try{let a=pw(s.graphOptimizationLevel??"all"),i=_w(s.executionMode??"sequential"),c=typeof s.logId=="string"?Wt(s.logId,n):0,u=s.logSeverityLevel??2;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log severity level is not valid: ${u}`);let h=s.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let p=typeof s.optimizedModelFilePath=="string"?Wt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,c,u,h,p),r===0&&Ie("Can't create session options."),s.executionProviders&&await gw(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Ki(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[_,m]of Object.entries(s.freeDimensionOverrides)){if(typeof _!="string")throw new Error(`free dimension override name must be a string: ${_}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let w=Wt(_,n);t._OrtAddFreeDimensionOverride(r,w,m)!==0&&Ie(`Can't set a free dimension override: ${_} - ${m}.`)}return s.extra!==void 0&&Ml(s.extra,"",new WeakSet,(_,m)=>{Ki(r,_,m,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Ie("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Xn,al,gs,vi,xl,xm,Tm,yh,Hs=Ee(()=>{Xn=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}`)}},al=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}`)}},gs=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},vi=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}`)}},xl=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}`)}},xm=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Tm=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",yh=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}`)}}}),Em,IM=Ee(()=>{ym(),Em=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(c){if(c instanceof RangeError){let u=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:u,maximum:u}).buffer}else throw c}let i=0;for(;;){let{done:c,value:u}=await s.read();if(c)break;let h=u.byteLength;new Uint8Array(a,i,h).set(u),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),LM,uB=Ee(()=>{Hs(),LM=(e,t)=>new(vi(t))(e)}),ww,yw,vw,bw,OM,Mw,Ct,NM=Ee(()=>{Hs(),ww=["V","I","W","E","F"],yw=(e,t)=>{console.log(`[${ww[e]},${new Date().toISOString()}]${t}`)},OM=(e,t)=>{vw=e,bw=t},Mw=(e,t)=>{let r=xl(e),n=xl(vw);r>=n&&yw(r,typeof t=="function"?t():t)},Ct=(...e)=>{bw&&Mw(...e)}}),Wf,vh,jf,xw,qf,Tw,Hf,Qf,Yf,Ew,BM,dB=Ee(()=>{Hs(),NM(),Wf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),vh=(e,t)=>{if(t==="int32")return e;let r=Wf.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let n=r/8;if(e.byteLength%n!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(vi(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let i=new Int32Array(s);for(let c=0;c2147483647n||u<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");i[c]=Number(u)}return new Uint8Array(i.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let i=Int32Array.from(a,Number);return new Uint8Array(i.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},jf=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},xw=1,qf=()=>xw++,Tw=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Hf=(e,t)=>{let r=Wf.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},Qf=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:i}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Hf(this.dataType,this.tensorShape)}destroy(){Ct("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=jf(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},Yf=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),i;if(!a?.input.dataTypes.includes(t)){if(i=Tw.get(t),!i||a?.input.dataTypes.includes(i))throw new Error(`WebNN backend does not support data type: ${t}`);Ct("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${i}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Hf(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,c,!0,!0,i),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=vh(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ct("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?jf(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Ew=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=qf();return this.tensorTrackersById.set(e,new Yf(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n,s){Ct("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){Ct("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let s=this.getMLContext(e),a=qf(),i=new Qf({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new Yf(this,i)),this.externalTensors.add(i),a}async getCachedTensor(e,t,r,n,s,a,i){let c=this.getMLContext(e);for(let[h,p]of this.freeTensors.entries())if(p.canReuseTensor(c,t,r)){Ct("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}`);let _=this.freeTensors.splice(h,1)[0];return _.sessionId=e,_}Ct("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${i?`fallbackDataType: ${i},`:""} shape: ${r}}`);let u=await c.createTensor({dataType:i??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new Qf({sessionId:e,context:c,tensor:u,dataType:t,shape:r,fallbackDataType:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},BM=(...e)=>new Ew(...e)}),$M={};Li($M,{WebNNBackend:()=>DM});var ci,kw,DM,fB=Ee(()=>{Hs(),ls(),uB(),dB(),NM(),ci=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),kw=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},DM=class{constructor(e){this.tensorManager=BM(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,OM(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ct("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ct("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)Ct("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>kw(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ct("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=ci.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){Ct("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=ci.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!Ge().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ct("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return LM(r,t)}}registerMLTensor(e,t,r,n){let s=ci.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return Ct("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,i=!1){if(!a)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let u=a.get(c);if(!u)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+r>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let h=u.slice(t,t+r).buffer,p;switch(s.dataType){case"float32":p=new Float32Array(h);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(h):new Uint16Array(h);break;case"int32":p=new Int32Array(h);break;case"uint32":p=new Uint32Array(h);break;case"int64":if(i){let _=vh(new Uint8Array(h),"int64");p=new Int32Array(_.buffer),s.dataType="int32"}else p=new BigInt64Array(h);break;case"uint64":p=new BigUint64Array(h);break;case"int8":p=new Int8Array(h);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(h);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return Ct("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=ci.get(Xn(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),Cw,km,Cm,tn,Aw,Xf,Tl,Am,Sm,Jf,Pm,Fm,Im,RM=Ee(()=>{is(),lB(),cB(),Hs(),ls(),Mm(),IM(),Cw=(e,t)=>{Ge()._OrtInit(e,t)!==0&&Ie("Can't initialize onnxruntime.")},km=async e=>{Cw(e.wasm.numThreads,xl(e.logLevel))},Cm=async(e,t)=>{Ge().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Ge().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(fB(),bl($M)).WebNNBackend(e);Ge().webnnInit([n,()=>n.reserveTensorId(),s=>n.releaseTensorId(s),async(s,a,i,c,u)=>n.ensureTensor(s,a,i,c,u),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},tn=new Map,Aw=e=>{let t=Ge(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&Ie("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},Xf=(e,t)=>{let r=Ge(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,i=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,i,i+a)!==0&&Ie("Can't get session input/output metadata.");let c=Number(r.getValue(i,"*"));s=Number(r.getValue(i+a,"*"));let u=r.HEAP32[s/4];if(u===0)return[c,0];let h=r.HEAPU32[s/4+1],p=[];for(let _=0;_{let t=Ge(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Am=async(e,t)=>{let r,n,s=Ge();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Tl(e);let a=0,i=0,c=0,u=[],h=[],p=[];try{if([i,u]=await FM(t),t?.externalData&&s.mountExternalData){let A=[];for(let F of t.externalData){let G=typeof F=="string"?F:F.path;A.push(Em(typeof F=="string"?F:F.data).then(v=>{s.mountExternalData(G,v)}))}await Promise.all(A)}for(let A of t?.executionProviders??[])if((typeof A=="string"?A:A.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof A!="string"){let F=A,G=F?.context,v=F?.gpuDevice,j=F?.deviceType,U=F?.powerPreference;G?s.currentContext=G:v?s.currentContext=await s.webnnCreateMLContext(v):s.currentContext=await s.webnnCreateMLContext({deviceType:j,powerPreference:U})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,i),s.webgpuOnCreateSession?.(a),a===0&&Ie("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[_,m]=Aw(a),w=!!t?.enableGraphCapture,b=[],M=[],E=[],T=[],C=[];for(let A=0;A<_;A++){let[F,G,v]=Xf(a,A);F===0&&Ie("Can't get an input name."),h.push(F);let j=s.UTF8ToString(F);b.push(j),E.push(G===0?{name:j,isTensor:!1}:{name:j,isTensor:!0,type:al(G),shape:v})}for(let A=0;AA==="gpu-buffer"||A==="ml-tensor"||A==="ml-tensor-cpu-output")&&(c=s._OrtCreateBinding(a),c===0&&Ie("Can't create IO binding."),P={handle:c,outputPreferredLocations:C,outputPreferredLocationsEncoded:C.map(A=>A==="ml-tensor-cpu-output"?"ml-tensor":A).map(A=>yh(A))}),tn.set(a,[a,h,p,P,w,!1]),[a,b,M,E,T]}catch(_){throw h.forEach(m=>s._OrtFree(m)),p.forEach(m=>s._OrtFree(m)),c!==0&&s._OrtReleaseBinding(c)!==0&&Ie("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&Ie("Can't release session."),_}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i)!==0&&Ie("Can't release session options."),u.forEach(_=>s._free(_)),s.unmountExternalData?.()}},Sm=e=>{let t=Ge(),r=tn.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,c]=r;i&&(c&&t._OrtClearBoundOutputs(i.handle)!==0&&Ie("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&Ie("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach(u=>t._OrtFree(u)),a.forEach(u=>t._OrtFree(u)),t._OrtReleaseSession(n)!==0&&Ie("Can't release session."),tn.delete(e)},Jf=async(e,t,r,n,s,a,i=!1)=>{if(!e){t.push(0);return}let c=Ge(),u=c.PTR_SIZE,h=e[0],p=e[1],_=e[3],m=_,w,b;if(h==="string"&&(_==="gpu-buffer"||_==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&_!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(_==="gpu-buffer"){let T=e[2].gpuBuffer;b=gs(Xn(h),p);{let C=c.webgpuRegisterBuffer;if(!C)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');w=C(T,n)}}else if(_==="ml-tensor"){let T=e[2].mlTensor;b=gs(Xn(h),p);let C=c.webnnRegisterMLTensor;if(!C)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');w=C(n,T,Xn(h),p)}else{let T=e[2];if(Array.isArray(T)){b=u*T.length,w=c._malloc(b),r.push(w);for(let C=0;Cc.setValue(E+P*u,C,u===4?"i32":"i64"));let T=c._OrtCreateTensor(Xn(h),w,b,E,p.length,yh(m));T===0&&Ie(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(T)}finally{c.stackRestore(M)}},Pm=async(e,t,r,n,s,a)=>{let i=Ge(),c=i.PTR_SIZE,u=tn.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=u[0],p=u[1],_=u[2],m=u[3],w=u[4],b=u[5],M=t.length,E=n.length,T=0,C=[],P=[],A=[],F=[],G=[],v=i.stackSave(),j=i.stackAlloc(M*c),U=i.stackAlloc(M*c),q=i.stackAlloc(E*c),ne=i.stackAlloc(E*c);try{[T,C]=PM(a),Zn("wasm prepareInputOutputTensor");for(let D=0;Due*oe,1);z=al(me);let qe=m?.outputPreferredLocations[n[D]];if(z==="string"){if(qe==="gpu-buffer"||qe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ue=[];for(let oe=0;oe<$e;oe++){let Re=i.getValue(Q+oe*c,"*"),ie=i.getValue(Q+(oe+1)*c,"*"),le=oe===$e-1?void 0:ie-Re;ue.push(i.UTF8ToString(Re,le))}I.push([z,ye,ue,"cpu"])}else if(qe==="gpu-buffer"&&$e>0){let ue=i.webgpuGetBuffer;if(!ue)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let oe=ue(Q),Re=gs(me,$e);if(Re===void 0||!xm(z))throw new Error(`Unsupported data type: ${z}`);$=!0;{i.webgpuRegisterBuffer(oe,e,Q);let ie=i.webgpuCreateDownloader(oe,Re,e);I.push([z,ye,{gpuBuffer:oe,download:async()=>{let le=await ie();return new(vi(z))(le)},dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}}else if(qe==="ml-tensor"&&$e>0){let ue=i.webnnEnsureTensor,oe=i.webnnIsGraphInputOutputTypeSupported;if(!ue||!oe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(gs(me,$e)===void 0||!Tm(z))throw new Error(`Unsupported data type: ${z}`);if(!oe(e,z,!1))throw new Error(`preferredLocation "ml-tensor" for ${z} output is not supported by current WebNN Context.`);let Re=await ue(e,Q,me,ye,!1);$=!0,I.push([z,ye,{mlTensor:Re,download:i.webnnCreateMLTensorDownloader(Q,z),dispose:()=>{i.webnnReleaseTensorId(Q),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else if(qe==="ml-tensor-cpu-output"&&$e>0){let ue=i.webnnCreateMLTensorDownloader(Q,z)(),oe=I.length;$=!0,S.push((async()=>{let Re=[oe,await ue];return i.webnnReleaseTensorId(Q),i._OrtReleaseTensor(Y),Re})()),I.push([z,ye,[],"cpu"])}else{let ue=vi(z),oe=new ue($e);new Uint8Array(oe.buffer,oe.byteOffset,oe.byteLength).set(i.HEAPU8.subarray(Q,Q+oe.byteLength)),I.push([z,ye,oe,"cpu"])}}finally{i.stackRestore(se),z==="string"&&Q&&i._free(Q),$||i._OrtReleaseTensor(Y)}}m&&!w&&(i._OrtClearBoundOutputs(m.handle)!==0&&Ie("Can't clear bound outputs."),tn.set(e,[h,p,_,m,w,!1]));for(let[D,Y]of await Promise.all(S))I[D][2]=Y;return es("wasm ProcessOutputTensor"),I}finally{i.webnnOnRunEnd?.(h),i.stackRestore(v),r.forEach(H=>{H&&H[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(H[2].gpuBuffer)}),s.forEach(H=>{H&&H[3]==="gpu-buffer"&&i.webgpuUnregisterBuffer(H[2].gpuBuffer)}),P.forEach(H=>i._OrtReleaseTensor(H)),A.forEach(H=>i._OrtReleaseTensor(H)),F.forEach(H=>i._free(H)),T!==0&&i._OrtReleaseRunOptions(T),C.forEach(H=>i._free(H))}},Fm=e=>{let t=Ge(),r=tn.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Ie("Can't get an profile file name."),t._OrtFree(s)},Im=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),rn,Kt,ps,ui,di,Zi,Kf,el,Un,Vn,Sw,zM,GM,UM,VM,WM,jM,qM,HM=Ee(()=>{is(),RM(),ls(),vm(),rn=()=>!!Qe.wasm.proxy&&typeof document<"u",ps=!1,ui=!1,di=!1,el=new Map,Un=(e,t)=>{let r=el.get(e);r?r.push(t):el.set(e,[t])},Vn=()=>{if(ps||!ui||di||!Kt)throw new Error("worker not ready")},Sw=e=>{switch(e.data.type){case"init-wasm":ps=!1,e.data.err?(di=!0,Kf[1](e.data.err)):(ui=!0,Kf[0]()),Zi&&(URL.revokeObjectURL(Zi),Zi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=el.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},zM=async()=>{if(!ui){if(ps)throw new Error("multiple calls to 'initWasm()' detected.");if(di)throw new Error("previous call to 'initWasm()' failed.");if(ps=!0,rn())return new Promise((e,t)=>{Kt?.terminate(),AM().then(([r,n])=>{try{Kt=n,Kt.onerror=a=>t(a),Kt.onmessage=Sw,Kf=[e,t];let s={type:"init-wasm",in:Qe};!s.in.wasm.wasmPaths&&(r||wh)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-C7SQPqnH.wasm",import.meta.url).href}),Kt.postMessage(s),Zi=r}catch(s){t(s)}},t)});try{await bm(Qe.wasm),await km(Qe),ui=!0}catch(e){throw di=!0,e}finally{ps=!1}}},GM=async e=>{if(rn())return Vn(),new Promise((t,r)=>{Un("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:Qe}};Kt.postMessage(n)});await Cm(Qe,e)},UM=async e=>rn()?(Vn(),new Promise((t,r)=>{Un("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Kt.postMessage(n,[e.buffer])})):Tl(e),VM=async(e,t)=>{if(rn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Vn(),new Promise((r,n)=>{Un("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Kt.postMessage(s,a)})}else return Am(e,t)},WM=async e=>{if(rn())return Vn(),new Promise((t,r)=>{Un("release",[t,r]);let n={type:"release",in:e};Kt.postMessage(n)});Sm(e)},jM=async(e,t,r,n,s,a)=>{if(rn()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Vn(),new Promise((i,c)=>{Un("run",[i,c]);let u=r,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:u,outputIndices:n,options:a}};Kt.postMessage(h,Im(u))})}else return Pm(e,t,r,n,s,a)},qM=async e=>{if(rn())return Vn(),new Promise((t,r)=>{Un("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Kt.postMessage(n)});Fm(e)}}),Zf,Pw,QM,hB=Ee(()=>{is(),HM(),Hs(),ym(),IM(),Zf=(e,t)=>{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 ${t()}`)}},Pw=e=>{switch(e[3]){case"cpu":return new Qt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!xm(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Qt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!Tm(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Qt.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},QM=class{async fetchModelAndCopyToWasmMemory(e){return UM(await Em(e))}async loadModel(e,t){ks();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await VM(r,t),Cs()}async dispose(){return WM(this.sessionId)}async run(e,t,r){ks();let n=[],s=[];Object.entries(e).forEach(_=>{let m=_[0],w=_[1],b=this.inputNames.indexOf(m);if(b===-1)throw new Error(`invalid input '${m}'`);n.push(w),s.push(b)});let a=[],i=[];Object.entries(t).forEach(_=>{let m=_[0],w=_[1],b=this.outputNames.indexOf(m);if(b===-1)throw new Error(`invalid output '${m}'`);a.push(w),i.push(b)});let c=n.map((_,m)=>Zf(_,()=>`input "${this.inputNames[s[m]]}"`)),u=a.map((_,m)=>_?Zf(_,()=>`output "${this.outputNames[i[m]]}"`):null),h=await jM(this.sessionId,s,c,i,u,r),p={};for(let _=0;_Mh,initializeFlags:()=>bh,wasmBackend:()=>XM});var bh,Mh,XM,pB=Ee(()=>{is(),HM(),hB(),bh=()=>{(typeof Qe.wasm.initTimeout!="number"||Qe.wasm.initTimeout<0)&&(Qe.wasm.initTimeout=0);let e=Qe.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Qe.wasm.simd=!1),typeof Qe.wasm.proxy!="boolean"&&(Qe.wasm.proxy=!1),typeof Qe.wasm.trace!="boolean"&&(Qe.wasm.trace=!1),typeof Qe.wasm.numThreads!="number"||!Number.isInteger(Qe.wasm.numThreads)||Qe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Qe.wasm.numThreads=1;else{let t=typeof navigator>"u"?W4("node:os").cpus().length:navigator.hardwareConcurrency;Qe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Mh=class{async init(e){bh(),await zM(),await GM(e)}async createInferenceSessionHandler(e,t){let r=new QM;return await r.loadModel(e,t),r}},XM=new Mh});is();is();is();var _B="1.25.1";{let e=(pB(),bl(YM)).wasmBackend;bs("webgpu",e,5),bs("webnn",e,5),bs("cpu",e,10),bs("wasm",e,10)}Object.defineProperty(Qe.versions,"web",{value:_B,enumerable:!0});Qe.wasm.wasmPaths="/ort-wasm/";let xh=!1;try{const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGPU is not supported (no adapter found)");xh=e.features.has("shader-f16"),self.postMessage({status:"feature-success",fp16:xh})}catch(e){throw self.postMessage({status:"feature-error",data:e.toString()}),e}const mB=128009,JM=128257,El=128258,gB=128259,wB=128260,yB=128261,br=128266,KM=br+7*4096,eh=4,vB=2048,bB=4096,ZM=24e3,e1="shreyask/svara-tts-v1-ONNX",MB="onnx-community/snac_24khz-ONNX",xB=new Set(["q4f16","q8"]);let TB=null;function Fw(){return TB??=Oe.from_pretrained(e1)}let EB=null;function Th(){return EB??=(async()=>{const e=`https://huggingface.co/${MB}/resolve/main/onnx/decoder_model${xh?"_fp16":""}.onnx`;return wm.create(e,{executionProviders:["webgpu"]})})()}const th=new Map;function Iw(e){return th.has(e)||th.set(e,z4.from_pretrained(e1,{dtype:e,device:"webgpu",use_external_data_format:e==="q8"?3:!0})),th.get(e)}class kB extends nr{constructor(t){super(),this.promptLength=t}_call(t,r){for(let n=0;nc).filter(c=>/\S/u.test(c)).length,n=Array.from(t.matchAll(/[.,!?;:।॥…\-—]+/gu)).length,s=t.split(/\s+/u).filter(Boolean).length,a=r*12+s*20+n*28+84,i=Math.max(224,Math.min(1120,a));return Math.ceil(i/7)*7}function Oi(e){return e.match(/\s*(<[^>]+>)\s*$/u)?.[1]??""}function Qs(e){return e.replace(/\s*<[^>]+>\s*$/u,"").trim()}function ec(e){return e.replace(/\.{2,}/gu,",").replace(/…+/gu,",").replace(/[—–]+/gu,",").replace(/\s+/gu," ").replace(/\s*([,.;!?।॥])\s*/gu,"$1 ").trim()}function Lm(e){return Array.from(new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e),({segment:t})=>t).filter(t=>/\S/u.test(t)).length}function tc(e){return e.split(/\s+/u).filter(Boolean).length}function SB(e){const t=Lm(e),r=tc(e);if(t<=28||r<=5)return[e];const n=e.split(/\s*,\s*/u).map(s=>s.trim()).filter(Boolean);return n.length>1?n:[e]}function PB(e){const t=[];for(const r of e){const n=Lm(r),s=tc(r);if(t.length>0&&!/[.!?।॥]$/u.test(t.at(-1))&&(n<10||s<3)){t[t.length-1]=`${t.at(-1)}, ${r}`;continue}t.push(r)}return t}function FB(e){const t=Oi(e),r=ec(Qs(e));if(!r)return[];const n=PB(r.match(/[^.!?।॥]+[.!?।॥]?/gu)?.map(s=>s.trim()).filter(Boolean).flatMap(SB)??[]);return t?n.map((s,a)=>a===n.length-1?`${s} ${t}`:s):n}function t1(e){const t=[];for(let r=0;r0){t[t.length-1]=`${t.at(-1)}, ${n}`;continue}}t.push(n)}return t}function Lw(e){const t=Oi(e),r=ec(Qs(e));if(!r)return[];const n=r.match(/[^.!?।॥]+[.!?।॥]?/gu)?.map(s=>s.trim()).filter(Boolean).flatMap(s=>{const a=s.split(/\s*,\s*/u).map(i=>i.trim()).filter(Boolean);return t1(a)})??[];return t?n.map((s,a)=>a===n.length-1?`${s} ${t}`:s):n}function IB(e){const t=Oi(e),r=ec(Qs(e));if(!r)return[];const n=t1(r.split(/\s*,\s*/u).map(s=>s.trim()).filter(Boolean));return t?n.map((s,a)=>a===n.length-1?`${s} ${t}`:s):n}function LB(e){const t=e.trim(),r=ec(Qs(e));if(!t&&!r)return[];const n=t?[[t]]:[];n.push(FB(e),Lw(e),IB(e)),Oi(e)&&(n.push([r]),n.push(Lw(r)));const s=new Set;return n.filter(a=>{if(a.length===0)return!1;const i=a.join("␞");return s.has(i)?!1:(s.add(i),!0)})}function OB(e,t){if(t)return 0;const r=e.trim();return/[!?]$/u.test(r)?.26:/[.]$/u.test(r)?.3:.18}function NB(e){const t=e.reduce((s,a)=>s+a.length,0),r=new Float32Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}function BB(e){let t=0,r=0;for(let s=0;st&&(t=a),r+=a*a}const n=e.length>0?Math.sqrt(r/e.length):0;return{peak:t,rms:n}}function $B(e){const{peak:t,rms:r}=BB(e);return t<.006&&r<.0015}function DB(e){const t=Qs(e),r=tc(t),n=Array.from(t.matchAll(/[.,!?;:।॥…\-—]+/gu)).length;return n>=3||r>=8||Oi(e)&&n>=1&&r>=5}async function RB(e,t,r,n,s){const a=[];for(let i=0;iNumber(E)),w=VB(m,u.length);if(w.length===0)throw new Error(`LM produced no audio tokens for chunk ${i+1}/${n.length}.`);const b=await GB(w);a.push(b);const M=OB(c,i===n.length-1);M>0&&a.push(new Float32Array(Math.round(ZM*M)))}return NB(a)}function zB(e){const t=Math.floor(e.length/7),r=new BigInt64Array(t),n=new BigInt64Array(t*2),s=new BigInt64Array(t*4);for(let a=0;a=br&&a{for(let u=0;u{const{type:t,text:r,speaker_id:n,dtype:s}=e.data,a=xB.has(s)?s:"q4f16";try{if(t==="preload"){self.postMessage({status:"loading",dtype:a}),await Promise.all([Fw(),Th(),Iw(a)]),self.postMessage({status:"ready",dtype:a});return}self.postMessage({status:"loading",dtype:a});const[i,c]=await Promise.all([Fw(),Iw(a)]);await Th();const u=LB(r);if(u.length===0)throw new Error("No speakable text found after normalization.");const h=qB(a,r);let p=null,_=null;for(const b of h){for(const M of u)try{const E=await RB(i,c,n,M,b);if($B(E)){_=new Error("Generated near-silent audio.");continue}p=E;break}catch(E){_=E}if(p)break}if(!p)throw _??new Error("Synthesis failed for all prompt variants.");const m=WB(p,ZM),w=new Blob([m],{type:"audio/wav"});self.postMessage({status:"complete",audio:URL.createObjectURL(w),text:r,voice:n,dtype:a})}catch(i){self.postMessage({status:"error",data:String(i),dtype:a}),console.error(i)}});