diff --git "a/assets/reference-CfIaZkZf.js" "b/assets/reference-CfIaZkZf.js" new file mode 100644--- /dev/null +++ "b/assets/reference-CfIaZkZf.js" @@ -0,0 +1,37 @@ +import{o as Oy}from"./preload-helper-BSrbm-kb.js";var Wo=Object.defineProperty,Ny=Object.getOwnPropertyDescriptor,Dy=Object.getOwnPropertyNames,zy=Object.prototype.hasOwnProperty,By=(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')}),me=(e,t)=>()=>(e&&(t=e(e=0)),t),Wn=(e,t)=>{for(var r in t)Wo(e,r,{get:t[r],enumerable:!0})},Ry=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Dy(t))!zy.call(e,s)&&s!==r&&Wo(e,s,{get:()=>t[s],enumerable:!(n=Ny(t,s))||n.enumerable});return e},Is=e=>Ry(Wo({},"__esModule",{value:!0}),e),Ln,cr,Pr,$d,ff,_f=me(()=>{Ln=new Map,cr=[],Pr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=Ln.get(e);if(n===void 0)Ln.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=cr.indexOf(e);s!==-1&&cr.splice(s,1);for(let a=0;a{let t=Ln.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}}},ff=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?cr:r,s,a=[],o=new Set;for(let l of n){let u=await $d(l);typeof u=="string"?a.push({name:l,err:u}):(s||(s=u),s===u&&o.add(l))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),Gy=me(()=>{_f()}),pf,$y=me(()=>{pf="1.24.0-dev.20251116-b39e144322"}),Ya,Xe,mf=me(()=>{$y(),Ya="warning",Xe={wasm:{},webgl:{},webgpu:{},versions:{common:pf},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}`);Ya=e}},get logLevel(){return Ya}},Object.defineProperty(Xe,"logLevel",{enumerable:!0})}),De,Vy=me(()=>{mf(),De=Xe}),gf,wf,Uy=me(()=>{gf=(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 o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let d=a*s,f=0,_=d,g=d*2,w=-1;o==="RGBA"?(f=0,_=d,g=d*2,w=d*3):o==="RGB"?(f=0,_=d,g=d*2):o==="RBG"&&(f=0,g=d,_=d*2);for(let v=0;v{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,u,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,g=0,w=1,v=2,x=3,b=0,k=f,C=f*2,E=-1;i==="RGBA"?(b=0,k=f,C=f*2,E=f*3):i==="RGB"?(b=0,k=f,C=f*2):i==="RBG"&&(b=0,C=f,k=f*2),n=r.createImageData(s,a);for(let P=0;P{Ho(),ps=(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,o;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"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=r*n,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,_=0,g=1,w=2,v=3,x=0,b=u,k=u*2,C=-1;i==="RGB"&&(f=3,_=0,g=1,w=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?(x=0,k=u,b=u*2):l==="BGR"&&(k=0,b=u,x=u*2);for(let E=0;E{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",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let f=u(d);if(f!=null){let _=e.height,g=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,g=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=g}else i.tensorFormat="RGBA",i.height=_,i.width=g;f.drawImage(e,0,0),o=f.getImageData(0,0,g,_).data}else throw new Error("Can not access image data")}else if(n){let d,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,f=t.resizedWidth):(d=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=f,t!==void 0){let _=l();_.width=f,_.height=d;let g=u(_);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,f,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let f=u(d);if(f!=null){let _=e.height,g=e.width;return f.drawImage(e,0,0,g,_),o=f.getImageData(0,0,g,_).data,i.height=_,i.width=g,ps(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,f)=>{let _=l(),g=u(_);if(!e||!g)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,g.drawImage(w,0,0,_.width,_.height);let v=g.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(ps(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ps(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},yf=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new pt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},Mf=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new pt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},bf=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new pt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},xf=(e,t,r)=>new pt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Cr,Rn,Ja,Tf,qy=me(()=>{Cr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ja=!1,Tf=()=>{if(!Ja){Ja=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Cr.set("int64",BigInt64Array),Rn.set(BigInt64Array,"int64")),t&&(Cr.set("uint64",BigUint64Array),Rn.set(BigUint64Array,"uint64")),n?(Cr.set("float16",r),Rn.set(r,"float16")):Cr.set("float16",Uint16Array)}}}),kf,Ef,Wy=me(()=>{Ho(),kf=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new pt(e.type,e.data,t);case"cpu-pinned":return new pt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new pt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new pt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new pt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),pt,Ho=me(()=>{Uy(),jy(),qy(),Wy(),pt=class{constructor(e,t,r){Tf();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 o=Cr.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.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 o,i;if(typeof e=="string")if(n=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Cr.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",o=e;else if(l==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let l=Rn.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");s=i,this.cpuData=o,this.dataLocation="cpu"}let a=kf(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 vf(e,t)}static fromTexture(e,t){return yf(e,t)}static fromGpuBuffer(e,t){return Mf(e,t)}static fromMLTensor(e,t){return bf(e,t)}static fromPinnedBuffer(e,t,r){return xf(e,t,r)}toDataURL(e){return gf(this,e)}toImageData(e){return wf(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 Ef(this,e)}}}),Ct,Cf=me(()=>{Ho(),Ct=pt}),Os,Ka,Lr,Ir,mr,gr,Af=me(()=>{mf(),Os=(e,t)=>{(typeof Xe.trace>"u"?!Xe.wasm.trace:!Xe.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ka=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s{(typeof Xe.trace>"u"?!Xe.wasm.trace:!Xe.trace)||Ka("BEGIN",e)},Ir=e=>{(typeof Xe.trace>"u"?!Xe.wasm.trace:!Xe.trace)||Ka("END",e)},mr=e=>{(typeof Xe.trace>"u"?!Xe.wasm.trace:!Xe.trace)||console.time(`ORT::${e}`)},gr=e=>{(typeof Xe.trace>"u"?!Xe.wasm.trace:!Xe.trace)||console.timeEnd(`ORT::${e}`)}}),Sf,Hy=me(()=>{_f(),Cf(),Af(),Sf=class Pf{constructor(t){this.handler=t}async run(t,r,n){Lr(),mr("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Ct||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Ct)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.");o=!1;for(let u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);s[u]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(d.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof Ct)&&(u=!0,o=!1,s[f]=_)}if(u){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 u of this.inputNames)if(typeof t[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(o)for(let u of this.outputNames)s[u]=null;let i=await this.handler.run(t,s,a),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let d=i[u];d instanceof Ct?l[u]=d:l[u]=new Ct(d.type,d.data,d.dims)}return gr("InferenceSession.run"),Ir(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Lr(),mr("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=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)o=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 d=t,f=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-f,typeof n=="number"){if(_=n,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-f}].`);if(typeof s=="object"&&s!==null)o=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(d,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await ff(o),u=await i.createInferenceSessionHandler(a,l);return gr("InferenceSession.create"),Ir(),new Pf(u)}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}}}),Qo,Qy=me(()=>{Hy(),Qo=Sf}),Xy=me(()=>{}),Yy=me(()=>{}),Jy=me(()=>{}),Ky=me(()=>{}),Ff={};Wn(Ff,{InferenceSession:()=>Qo,TRACE:()=>Os,TRACE_EVENT_BEGIN:()=>mr,TRACE_EVENT_END:()=>gr,TRACE_FUNC_BEGIN:()=>Lr,TRACE_FUNC_END:()=>Ir,Tensor:()=>Ct,env:()=>De,registerBackend:()=>Pr});var Or=me(()=>{Gy(),Vy(),Qy(),Cf(),Xy(),Yy(),Af(),Jy(),Ky()}),Xo=me(()=>{}),Lf={};Wn(Lf,{default:()=>If});var Za,eo,If,Zy=me(()=>{Qf(),Nr(),Yo(),Za="ort-wasm-proxy-worker",eo=globalThis.self?.name===Za,eo&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Jo(r.wasm).then(()=>{ri(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;ni(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=zs(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;si(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":ai(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;oi(n,s,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},li([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":ii(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),If=eo?null:e=>new Worker(e??ft,{type:"module",name:Za})}),Of={};Wn(Of,{default:()=>Nf});async function Vd(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(c,h)=>{c.startsWith("./")&&(c=c.substring(2)),(t.Uc||(t.Uc=new Map)).set(c,h)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let c=h=>(...p)=>{let m=Dt;return p=h(...p),Dt!=m?new Promise((y,T)=>{Pa={resolve:y,reject:T}}):p};(()=>{for(let h of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[h]=c(t[h])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,i,l=(c,h)=>{throw h},u=import.meta.url,d="";if(r||n){try{d=new URL(".",u).href}catch{}n&&(i=c=>{var h=new XMLHttpRequest;return h.open("GET",c,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),o=async c=>{if(z(c))return new Promise((p,m)=>{var y=new XMLHttpRequest;y.open("GET",c,!0),y.responseType="arraybuffer",y.onload=()=>{y.status==200||y.status==0&&y.response?p(y.response):m(y.status)},y.onerror=m,y.send(null)});var h=await fetch(c,{credentials:"same-origin"});if(h.ok)return h.arrayBuffer();throw Error(h.status+" : "+h.url)}}var f,_,g,w,v,x,b=console.log.bind(console),k=console.error.bind(console),C=b,E=k,P=!1,z=c=>c.startsWith("file://");function M(){ir.buffer!=R.buffer&&W()}if(s){let c=function(h){try{var p=h.data,m=p.Oc;if(m==="load"){let y=[];self.onmessage=T=>y.push(T),x=()=>{postMessage({Oc:"loaded"});for(let T of y)c(T);self.onmessage=c};for(let T of p.ce)t[T]&&!t[T].proxy||(t[T]=(...S)=>{postMessage({Oc:"callHandler",be:T,args:S})},T=="print"&&(C=t[T]),T=="printErr"&&(E=t[T]));ir=p.ie,W(),_=p.je,lt(),_s()}else if(m==="run"){(function(y){var T=(M(),I)[y+52>>>2>>>0];y=(M(),I)[y+56>>>2>>>0],Ku(T,T-y),te(T)})(p.Nc),Va(p.Nc,0,0,1,0,0),Rc(),Ca(p.Nc),V||(Ou(),V=!0);try{zg(p.ge,p.Wc)}catch(y){if(y!="unwind")throw y}}else p.target!=="setimmediate"&&(m==="checkMailbox"?V&&os():m&&(E(`worker: received unknown command ${m}`),E(p)))}catch(y){throw Hu(),y}};var V=!1;self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=c}var R,q,K,Q,O,I,$,H,ee,L,N,B=!1;function W(){var c=ir.buffer;t.HEAP8=R=new Int8Array(c),K=new Int16Array(c),t.HEAPU8=q=new Uint8Array(c),Q=new Uint16Array(c),t.HEAP32=O=new Int32Array(c),t.HEAPU32=I=new Uint32Array(c),$=new Float32Array(c),H=new Float64Array(c),ee=new BigInt64Array(c),L=new BigUint64Array(c)}function he(){B=!0,s?x():Kt._b()}function Te(c){throw E(c="Aborted("+c+")"),P=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),v?.(c),c}function oe(){return{a:{f:Bg,J:Rg,k:Gg,p:$g,l:Vg,sa:Ug,b:jg,ca:qg,Ja:qc,q:Wg,da:Xc,Za:Yc,Fa:Jc,Ha:Kc,_a:Zc,Xa:eu,Qa:tu,Wa:ru,oa:nu,Ga:su,Xb:au,Ya:ou,Yb:iu,db:Hg,Da:Qg,Sb:Xg,Qb:Jg,Ca:Zg,M:ew,I:tw,Rb:rw,ja:cw,Tb:uw,Ta:dw,Vb:fw,Ka:_w,Ob:pw,ka:mw,Sa:Ca,ab:gw,U:Mw,n:Ew,c:ka,rb:Cw,w:Aw,L:Sw,z:Pw,j:Fw,o:pu,sb:Lw,G:Iw,T:Ow,h:Nw,u:Dw,m:zw,i:Bw,Na:Rw,Oa:Gw,Pa:$w,La:vu,Ma:yu,Pb:Mu,eb:Uw,cb:qw,Y:Ww,qb:Hw,la:Qw,bb:jw,fb:Xw,$a:Yw,Wb:Jw,N:Vw,gb:Kw,X:Zw,Ub:ev,nb:cv,C:uv,ra:dv,qa:hv,pb:fv,W:_v,v:pv,mb:mv,lb:gv,kb:wv,ob:vv,jb:yv,ib:Mv,hb:bv,Ua:Cu,Va:Au,Ia:Rr,V:Su,na:Pu,Ra:Fu,ma:Lu,Cb:Ly,xa:Ey,Db:Fy,ya:ky,F:_y,e:ty,s:Zv,x:Kv,B:dy,Fb:by,ba:My,D:sy,za:xy,$:Cy,ga:yy,Gb:vy,Hb:wy,Ba:py,Aa:gy,Ib:my,wa:Py,aa:Ty,d:ey,A:ny,r:ry,Bb:Iy,t:oy,y:hy,H:ay,E:iy,K:fy,R:Ay,ia:uy,_:Sy,Jb:cy,Kb:ly,g:Tv,a:ir,Nb:Br,Eb:kv,ha:Ev,O:Cv,pa:Av,Lb:Sv,ta:Pv,Q:Fv,yb:Lv,zb:Iv,ua:Ov,ea:Nv,P:Dv,Ea:zv,va:Bv,Z:Rv,wb:Gv,Zb:$v,S:Vv,Ab:Uv,tb:jv,ub:Wv,vb:Hv,fa:Qv,xb:Xv,Mb:Yv}}}async function lt(){function c(m,y){var T=Kt=m.exports;m={};for(let[S,F]of Object.entries(T))typeof F=="function"?(T=ww(F),m[S]=T):m[S]=F;return Kt=m,Kt=(function(){var S=Kt,F=X=>ge=>X(ge)>>>0,G=X=>()=>X()>>>0;return(S=Object.assign({},S)).$b=F(S.$b),S.Cc=G(S.Cc),S.Ec=F(S.Ec),S.rd=(X=>(ge,Y)=>X(ge,Y)>>>0)(S.rd),S.wd=F(S.wd),S.xd=G(S.xd),S.Bd=F(S.Bd),S})(),zc.push(Kt.id),Iu=(m=Kt).$b,Ou=m.ac,t._OrtInit=m.bc,t._OrtGetLastError=m.cc,t._OrtCreateSessionOptions=m.dc,t._OrtAppendExecutionProvider=m.ec,t._OrtAddFreeDimensionOverride=m.fc,t._OrtAddSessionConfigEntry=m.gc,t._OrtReleaseSessionOptions=m.hc,t._OrtCreateSession=m.ic,t._OrtReleaseSession=m.jc,t._OrtGetInputOutputCount=m.kc,t._OrtGetInputOutputMetadata=m.lc,t._OrtFree=m.mc,t._OrtCreateTensor=m.nc,t._OrtGetTensorData=m.oc,t._OrtReleaseTensor=m.pc,t._OrtCreateRunOptions=m.qc,t._OrtAddRunConfigEntry=m.rc,t._OrtReleaseRunOptions=m.sc,t._OrtCreateBinding=m.tc,t._OrtBindInput=m.uc,t._OrtBindOutput=m.vc,t._OrtClearBoundOutputs=m.wc,t._OrtReleaseBinding=m.xc,t._OrtRunWithBinding=m.yc,t._OrtRun=m.zc,t._OrtEndProfiling=m.Ac,Da=t._OrtGetWebGpuDevice=m.Bc,hs=m.Cc,Et=t._free=m.Dc,jr=t._malloc=m.Ec,Nu=t._wgpuBufferRelease=m.Fc,Du=t._wgpuCreateInstance=m.Gc,zu=m.Hc,Bu=m.Ic,Ru=m.Jc,Gu=m.Kc,$u=m.Lc,Vu=m.Pc,Uu=m.Zc,ju=m._c,qu=m.$c,za=m.bd,Ba=m.cd,Ra=m.dd,Ga=m.ed,Sn=m.fd,$a=m.gd,Wu=m.hd,Va=m.kd,Hu=m.ld,Qu=m.md,Xu=m.nd,Ua=m.od,Yu=m.pd,Ju=m.qd,ja=m.rd,fe=m.sd,Pn=m.td,Ku=m.ud,te=m.vd,fs=m.wd,re=m.xd,Zu=m.yd,qa=m.zd,ed=m.Ad,td=m.Bd,rd=m.Cd,Wa=m.Dd,nd=m.Ed,sd=m.Fd,ad=m.Gd,od=m.Hd,id=m.Id,ld=m.Jd,cd=m.Kd,ud=m.Ld,dd=m.Md,hd=m.Nd,fd=m.Od,_d=m.Pd,pd=m.Qd,md=m.Rd,gd=m.Td,wd=m.Ud,vd=m.Vd,yd=m.Wd,Md=m.Yd,bd=m.Zd,xd=m._d,Td=m.$d,kd=m.ae,Ed=m.oe,Cd=m.pe,Ad=m.qe,Sd=m.re,Pd=m.se,Fd=m.te,Ld=m.ue,Id=m.ve,Od=m.we,Nd=m.xe,Dd=m.ye,zd=m.Ye,Bd=m.Ze,Rd=m._e,Gd=m.$e,_=y,Kt}var h,p=oe();return t.instantiateWasm?new Promise(m=>{t.instantiateWasm(p,(y,T)=>{m(c(y,T))})}):s?c(new WebAssembly.Instance(_,oe()),_):(N??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",import.meta.url).href,h=await(async function(m){var y=N;if(!f&&!z(y))try{var T=fetch(y,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,m)}catch(S){E(`wasm streaming compile failed: ${S}`),E("falling back to ArrayBuffer instantiation")}return(async function(S,F){try{var G=await(async function(X){if(!f)try{var ge=await o(X);return new Uint8Array(ge)}catch{}if(X==N&&f)X=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";X=i(X)}return X})(S);return await WebAssembly.instantiate(G,F)}catch(X){E(`failed to asynchronously prepare wasm: ${X}`),Te(X)}})(y,m)})(p),c(h.instance,h.module))}class Le{name="ExitStatus";constructor(h){this.message=`Program terminated with exit(${h})`,this.status=h}}var He=c=>{c.terminate(),c.onmessage=()=>{}},ct=[],Se=0,ve=null,rt=c=>{or.length==0&&($c(),Gc(or[0]));var h=or.pop();if(!h)return 6;En.push(h),yr[c.Nc]=h,h.Nc=c.Nc;var p={Oc:"run",ge:c.fe,Wc:c.Wc,Nc:c.Nc};return h.postMessage(p,c.Yc),0},Me=0,be=(c,h,...p)=>{var m,y=16*p.length,T=re(),S=fs(y),F=S>>>3;for(m of p)typeof m=="bigint"?((M(),ee)[F++>>>0]=1n,(M(),ee)[F++>>>0]=m):((M(),ee)[F++>>>0]=0n,(M(),H)[F++>>>0]=m);return c=Qu(c,0,y,S,h),te(T),c};function Br(c){if(s)return be(0,1,c);if(g=c,!(0{if(g=c,s)throw kn(c),"unwind";Br(c)},or=[],En=[],zc=[],yr={},Bc=c=>{var h=c.Nc;delete yr[h],or.push(c),En.splice(En.indexOf(c),1),c.Nc=0,Xu(h)};function Rc(){zc.forEach(c=>c())}var Gc=c=>new Promise(h=>{c.onmessage=y=>{var T=y.data;if(y=T.Oc,T.Vc&&T.Vc!=hs()){var S=yr[T.Vc];S?S.postMessage(T,T.Yc):E(`Internal error! Worker sent a message "${y}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else y==="checkMailbox"?os():y==="spawnThread"?rt(T):y==="cleanupThread"?ut(()=>{Bc(yr[T.he])}):y==="loaded"?(c.loaded=!0,h(c)):T.target==="setimmediate"?c.postMessage(T):y==="uncaughtException"?c.onerror(T.error):y==="callHandler"?t[T.be](...T.args):y&&E(`worker sent an unknown command ${y}`)},c.onerror=y=>{throw E(`worker sent an error! ${y.filename}:${y.lineno}: ${y.message}`),y};var p,m=[];for(p of[])t.propertyIsEnumerable(p)&&m.push(p);c.postMessage({Oc:"load",ce:m,ie:ir,je:_})});function $c(){var c=new Worker((()=>{let h=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new h("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});or.push(c)}var ir,zg=(c,h)=>{Me=0,c=Wa(c,h),0-9007199254740992>c||9007199254740992>>=0);return(M(),R)[h.Qc+12>>>0]==0&&(Vc(h,!0),as--),Uc(h,!1),ss.push(h),td(c)}var Gr=0,Rg=()=>{fe(0,0);var c=ss.pop();Zu(c.Xc),Gr=0};function Vc(c,h){h=h?1:0,(M(),R)[c.Qc+12>>>0]=h}function Uc(c,h){h=h?1:0,(M(),R)[c.Qc+13>>>0]=h}class Ma{constructor(h){this.Xc=h,this.Qc=h-24}}var ba=c=>{var h=Gr;if(!h)return Pn(0),0;var p=new Ma(h);(M(),I)[p.Qc+16>>>2>>>0]=h;var m=(M(),I)[p.Qc+4>>>2>>>0];if(!m)return Pn(0),h;for(var y of c){if(y===0||y===m)break;if(ed(y,m,p.Qc+16))return Pn(y),h}return Pn(m),h};function Gg(){return ba([])}function $g(c){return ba([c>>>0])}function Vg(c,h,p,m){return ba([c>>>0,h>>>0,p>>>0,m>>>0])}var Ug=()=>{var c=ss.pop();c||Te("no exception to throw");var h=c.Xc;throw(M(),R)[c.Qc+13>>>0]==0&&(ss.push(c),Uc(c,!0),Vc(c,!1),as++),qa(h),Gr=h};function jg(c,h,p){var m=new Ma(c>>>=0);throw h>>>=0,p>>>=0,(M(),I)[m.Qc+16>>>2>>>0]=0,(M(),I)[m.Qc+4>>>2>>>0]=h,(M(),I)[m.Qc+8>>>2>>>0]=p,qa(c),as++,Gr=c}var qg=()=>as;function jc(c,h,p,m){return s?be(2,1,c,h,p,m):qc(c,h,p,m)}function qc(c,h,p,m){if(c>>>=0,h>>>=0,p>>>=0,m>>>=0,!globalThis.SharedArrayBuffer)return 6;var y=[];return s&&y.length===0?jc(c,h,p,m):(c={fe:p,Nc:c,Wc:m,Yc:y},s?(c.Oc="spawnThread",postMessage(c,y),0):rt(c))}function Wg(c){throw Gr||=c>>>0,Gr}var Wc=globalThis.TextDecoder&&new TextDecoder,Hc=(c,h,p,m)=>{if(p=h+p,m)return p;for(;c[h]&&!(h>=p);)++h;return h},Qc=(c,h=0,p,m)=>{if(16<(p=Hc(c,h>>>=0,p,m))-h&&c.buffer&&Wc)return Wc.decode(c.buffer instanceof ArrayBuffer?c.subarray(h,p):c.slice(h,p));for(m="";h(y=(240&y)==224?(15&y)<<12|T<<6|S:(7&y)<<18|T<<12|S<<6|63&c[h++])?m+=String.fromCharCode(y):(y-=65536,m+=String.fromCharCode(55296|y>>10,56320|1023&y))}}else m+=String.fromCharCode(y)}return m},$r=(c,h,p)=>(c>>>=0)?Qc((M(),q),c,h,p):"";function Xc(c,h,p){return s?be(3,1,c,h,p):0}function Yc(c,h){if(s)return be(4,1,c,h)}function Jc(c,h){if(s)return be(5,1,c,h)}function Kc(c,h,p){if(s)return be(6,1,c,h,p)}function Zc(c,h,p){return s?be(7,1,c,h,p):0}function eu(c,h){if(s)return be(8,1,c,h)}function tu(c,h,p){if(s)return be(9,1,c,h,p)}function ru(c,h,p,m){if(s)return be(10,1,c,h,p,m)}function nu(c,h,p,m){if(s)return be(11,1,c,h,p,m)}function su(c,h,p,m){if(s)return be(12,1,c,h,p,m)}function au(c){if(s)return be(13,1,c)}function ou(c,h){if(s)return be(14,1,c,h)}function iu(c,h,p){if(s)return be(15,1,c,h,p)}var Hg=()=>Te(""),Nt=c=>{c>>>=0;for(var h="";;){var p=(M(),q)[c++>>>0];if(!p)return h;h+=String.fromCharCode(p)}},xa={},Ta={},Vr=class extends Error{constructor(c){super(c),this.name="BindingError"}};function Ht(c,h,p={}){return(function(m,y,T={}){var S=y.name;if(!m)throw new Vr(`type "${S}" must have a positive integer typeid pointer`);if(Ta.hasOwnProperty(m)){if(T.de)return;throw new Vr(`Cannot register type '${S}' twice`)}Ta[m]=y,xa.hasOwnProperty(m)&&(y=xa[m],delete xa[m],y.forEach(F=>F()))})(c,h,p)}var lu=(c,h,p)=>{switch(h){case 1:return p?m=>(M(),R)[m>>>0]:m=>(M(),q)[m>>>0];case 2:return p?m=>(M(),K)[m>>>1>>>0]:m=>(M(),Q)[m>>>1>>>0];case 4:return p?m=>(M(),O)[m>>>2>>>0]:m=>(M(),I)[m>>>2>>>0];case 8:return p?m=>(M(),ee)[m>>>3>>>0]:m=>(M(),L)[m>>>3>>>0];default:throw new TypeError(`invalid integer width (${h}): ${c}`)}};function Qg(c,h,p,m,y){c>>>=0,p>>>=0,h=Nt(h>>>0);let T=S=>S;if(m=m===0n){let S=8*p;T=F=>BigInt.asUintN(S,F),y=T(y)}Ht(c,{name:h,Mc:T,Sc:(S,F)=>(typeof F=="number"&&(F=BigInt(F)),F),Rc:lu(h,p,!m),Tc:null})}function Xg(c,h,p,m){Ht(c>>>=0,{name:h=Nt(h>>>0),Mc:function(y){return!!y},Sc:function(y,T){return T?p:m},Rc:function(y){return this.Mc((M(),q)[y>>>0])},Tc:null})}var cu=[],Mr=[0,1,,1,null,1,!0,1,!1,1];function ka(c){9<(c>>>=0)&&--Mr[c+1]==0&&(Mr[c]=void 0,cu.push(c))}var vt=c=>{if(!c)throw new Vr(`Cannot use deleted val. handle = ${c}`);return Mr[c]},kt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=cu.pop()||Mr.length;return Mr[h]=c,Mr[h+1]=1,h}};function Ea(c){return this.Mc((M(),I)[c>>>2>>>0])}var Yg={name:"emscripten::val",Mc:c=>{var h=vt(c);return ka(c),h},Sc:(c,h)=>kt(h),Rc:Ea,Tc:null};function Jg(c){return Ht(c>>>0,Yg)}var Kg=(c,h)=>{switch(h){case 4:return function(p){return this.Mc((M(),$)[p>>>2>>>0])};case 8:return function(p){return this.Mc((M(),H)[p>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${c}`)}};function Zg(c,h,p){p>>>=0,Ht(c>>>=0,{name:h=Nt(h>>>0),Mc:m=>m,Sc:(m,y)=>y,Rc:Kg(h,p),Tc:null})}function ew(c,h,p,m,y){c>>>=0,p>>>=0,h=Nt(h>>>0);let T=F=>F;if(m===0){var S=32-8*p;T=F=>F<>>S,y=T(y)}Ht(c,{name:h,Mc:T,Sc:(F,G)=>G,Rc:lu(h,p,m!==0),Tc:null})}function tw(c,h,p){function m(T){var S=(M(),I)[T>>>2>>>0];return T=(M(),I)[T+4>>>2>>>0],new y((M(),R).buffer,T,S)}var y=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];Ht(c>>>=0,{name:p=Nt(p>>>0),Mc:m,Rc:m},{de:!0})}var Qt=(c,h,p)=>{var m=(M(),q);if(h>>>=0,0=S){if(h>=p)break;m[h++>>>0]=S}else if(2047>=S){if(h+1>=p)break;m[h++>>>0]=192|S>>6,m[h++>>>0]=128|63&S}else if(65535>=S){if(h+2>=p)break;m[h++>>>0]=224|S>>12,m[h++>>>0]=128|S>>6&63,m[h++>>>0]=128|63&S}else{if(h+3>=p)break;m[h++>>>0]=240|S>>18,m[h++>>>0]=128|S>>12&63,m[h++>>>0]=128|S>>6&63,m[h++>>>0]=128|63&S,T++}}m[h>>>0]=0,c=h-y}else c=0;return c},Xt=c=>{for(var h=0,p=0;p=m?h++:2047>=m?h+=2:55296<=m&&57343>=m?(h+=4,++p):h+=3}return h};function rw(c,h){Ht(c>>>=0,{name:h=Nt(h>>>0),Mc(p){var m=(M(),I)[p>>>2>>>0];return m=$r(p+4,m,!0),Et(p),m},Sc(p,m){m instanceof ArrayBuffer&&(m=new Uint8Array(m));var y=typeof m=="string";if(!(y||ArrayBuffer.isView(m)&&m.BYTES_PER_ELEMENT==1))throw new Vr("Cannot pass non-string to std::string");var T=y?Xt(m):m.length,S=jr(4+T+1),F=S+4;return(M(),I)[S>>>2>>>0]=T,y?Qt(m,F,T+1):(M(),q).set(m,F>>>0),p!==null&&p.push(Et,S),S},Rc:Ea,Tc(p){Et(p)}})}var uu=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,nw=(c,h,p)=>{if(c>>>=1,16<(h=Hc((M(),Q),c,h/2,p))-c&&uu)return uu.decode((M(),Q).slice(c,h));for(p="";c>>0];p+=String.fromCharCode(m)}return p},sw=(c,h,p)=>{if(p??=2147483647,2>p)return 0;var m=h;p=(p-=2)<2*c.length?p/2:c.length;for(var y=0;y>>1>>>0]=T,h+=2}return(M(),K)[h>>>1>>>0]=0,h-m},aw=c=>2*c.length,ow=(c,h,p)=>{var m="";c>>>=2;for(var y=0;!(y>=h/4);y++){var T=(M(),I)[c+y>>>0];if(!T&&!p)break;m+=String.fromCodePoint(T)}return m},iw=(c,h,p)=>{if(h>>>=0,p??=2147483647,4>p)return 0;var m=h;p=m+p-4;for(var y=0;y>>2>>>0]=T,(h+=4)+4>p)break}return(M(),O)[h>>>2>>>0]=0,h-m},lw=c=>{for(var h=0,p=0;p>>=0,h>>>=0,p=Nt(p>>>=0),h===2)var m=nw,y=sw,T=aw;else m=ow,y=iw,T=lw;Ht(c,{name:p,Mc:S=>{var F=(M(),I)[S>>>2>>>0];return F=m(S+4,F*h,!0),Et(S),F},Sc:(S,F)=>{if(typeof F!="string")throw new Vr(`Cannot pass non-string to C++ string type ${p}`);var G=T(F),X=jr(4+G+h);return(M(),I)[X>>>2>>>0]=G/h,y(F,X+4,G+h),S!==null&&S.push(Et,X),X},Rc:Ea,Tc(S){Et(S)}})}function uw(c,h){Ht(c>>>=0,{ee:!0,name:h=Nt(h>>>0),Mc:()=>{},Sc:()=>{}})}function dw(c){Va(c>>>0,!n,1,!r,131072,!1),Rc()}var ut=c=>{if(!P)try{if(c(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ca(c){c>>>=0,hw||(Atomics.waitAsync((M(),O),c>>>2,c).value.then(os),c+=128,Atomics.store((M(),O),c>>>2,1))}var os=()=>ut(()=>{var c=hs();c&&(Ca(c),Ju())});function fw(c,h){(c>>>=0)==h>>>0?setTimeout(os):s?postMessage({Vc:c,Oc:"checkMailbox"}):(c=yr[c])&&c.postMessage({Oc:"checkMailbox"})}var Aa=[];function _w(c,h,p,m,y){for(h>>>=0,y>>>=0,Aa.length=0,p=y>>>3,m=y+m>>>3;p>>0]?(M(),ee)[p++>>>0]:(M(),H)[p++>>>0],Aa.push(T)}return(h?Ha[h]:Jv[c])(...Aa)}var pw=()=>{Me=0};function mw(c){c>>>=0,s?postMessage({Oc:"cleanupThread",he:c}):Bc(yr[c])}function gw(c){}var is=c=>{try{c()}catch(h){Te(h)}};function ww(c){var h=(...p)=>{ls.push(c);try{return c(...p)}finally{P||(ls.pop(),Dt&&lr===1&&ls.length===0&&(lr=0,Me+=1,is(Bd),typeof Fibers<"u"&&Fibers.Be()))}};return fu.set(c,h),h}var lr=0,Dt=null,du=0,ls=[],Sa=new Map,hu=new Map,fu=new Map,vw=0,Pa=null,yw=[],_u=c=>(function(h){if(!P){if(lr===0){var p=!1,m=!1;h((y=0)=>{if(!P&&(du=y,p=!0,m)){lr=2,is(()=>Rd(Dt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),y=!1;try{var T=(function(){var G=(M(),O)[Dt+8>>>2>>>0];return G=hu.get(G),G=fu.get(G),--Me,G()})()}catch(G){T=G,y=!0}var S=!1;if(!Dt){var F=Pa;F&&(Pa=null,(y?F.reject:F.resolve)(T),S=!0)}if(y&&!S)throw T}}),m=!0,p||(lr=1,Dt=(function(){var y=jr(65548),T=y+12;if((M(),I)[y>>>2>>>0]=T,(M(),I)[y+4>>>2>>>0]=T+65536,T=ls[0],!Sa.has(T)){var S=vw++;Sa.set(T,S),hu.set(S,T)}return T=Sa.get(T),(M(),O)[y+8>>>2>>>0]=T,y})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),is(()=>zd(Dt)))}else lr===2?(lr=0,is(Gd),Et(Dt),Dt=null,yw.forEach(ut)):Te(`invalid state: ${lr}`);return du}})(h=>{c().then(h)});function Mw(c){return c>>>=0,_u(async()=>{var h=await vt(c);return kt(h)})}var Fa=[],bw=c=>{var h=Fa.length;return Fa.push(c),h},xw=(c,h)=>{for(var p=Array(c),m=0;m>>2>>>0],S=Ta[T];if(S===void 0)throw c=`parameter ${m}`,T=Iu(T),h=Nt(T),Et(T),new Vr(`${c} has unknown type ${h}`);p[y]=S}return p},Tw=(c,h,p)=>{var m=[];return c=c(m,p),m.length&&((M(),I)[h>>>2>>>0]=kt(m)),c},kw={},cs=c=>{var h=kw[c];return h===void 0?Nt(c):h};function Ew(c,h,p){var[m,...y]=xw(c,h>>>0);h=m.Sc.bind(m);var T=y.map(G=>G.Rc.bind(G));c--;var S={toValue:vt};switch(c=T.map((G,X)=>{var ge=`argFromPtr${X}`;return S[ge]=G,`${ge}(args${X?"+"+8*X:""})`}),p){case 0:var F="toValue(handle)";break;case 2:F="new (toValue(handle))";break;case 3:F="";break;case 1:S.getStringOrSymbol=cs,F="toValue(handle)[getStringOrSymbol(methodName)]"}return F+=`(${c})`,m.ee||(S.toReturnWire=h,S.emval_returnValue=Tw,F=`return emval_returnValue(toReturnWire, destructorsRef, ${F})`),F=`return function (handle, methodName, destructorsRef, args) { + ${F} + }`,p=new Function(Object.keys(S),F)(...Object.values(S)),F=`methodCaller<(${y.map(G=>G.name)}) => ${m.name}>`,bw(Object.defineProperty(p,"name",{value:F}))}function Cw(c,h){return h>>>=0,(c=vt(c>>>0))==vt(h)}function Aw(c){return(c>>>=0)?(c=cs(c),kt(globalThis[c])):kt(globalThis)}function Sw(c){return c=cs(c>>>0),kt(t[c])}function Pw(c,h){return h>>>=0,c=vt(c>>>0),h=vt(h),kt(c[h])}function Fw(c){9<(c>>>=0)&&(Mr[c+1]+=1)}function pu(c,h,p,m,y){return Fa[c>>>0](h>>>0,p>>>0,m>>>0,y>>>0)}function Lw(c,h,p,m,y){return pu(c>>>0,h>>>0,p>>>0,m>>>0,y>>>0)}function Iw(){return kt([])}function Ow(c){c=vt(c>>>0);for(var h=Array(c.length),p=0;p>>0))}function Dw(){return kt({})}function zw(c){for(var h=vt(c>>>=0);h.length;){var p=h.pop();h.pop()(p)}ka(c)}function Bw(c,h,p){h>>>=0,p>>>=0,c=vt(c>>>0),h=vt(h),p=vt(p),c[h]=p}function Rw(c,h){c=Je(c),h>>>=0,c=new Date(1e3*c),(M(),O)[h>>>2>>>0]=c.getUTCSeconds(),(M(),O)[h+4>>>2>>>0]=c.getUTCMinutes(),(M(),O)[h+8>>>2>>>0]=c.getUTCHours(),(M(),O)[h+12>>>2>>>0]=c.getUTCDate(),(M(),O)[h+16>>>2>>>0]=c.getUTCMonth(),(M(),O)[h+20>>>2>>>0]=c.getUTCFullYear()-1900,(M(),O)[h+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(M(),O)[h+28>>>2>>>0]=c}var mu=c=>c%4==0&&(c%100!=0||c%400==0),gu=[0,31,60,91,121,152,182,213,244,274,305,335],wu=[0,31,59,90,120,151,181,212,243,273,304,334];function Gw(c,h){c=Je(c),h>>>=0,c=new Date(1e3*c),(M(),O)[h>>>2>>>0]=c.getSeconds(),(M(),O)[h+4>>>2>>>0]=c.getMinutes(),(M(),O)[h+8>>>2>>>0]=c.getHours(),(M(),O)[h+12>>>2>>>0]=c.getDate(),(M(),O)[h+16>>>2>>>0]=c.getMonth(),(M(),O)[h+20>>>2>>>0]=c.getFullYear()-1900,(M(),O)[h+24>>>2>>>0]=c.getDay();var p=(mu(c.getFullYear())?gu:wu)[c.getMonth()]+c.getDate()-1|0;(M(),O)[h+28>>>2>>>0]=p,(M(),O)[h+36>>>2>>>0]=-60*c.getTimezoneOffset(),p=new Date(c.getFullYear(),6,1).getTimezoneOffset();var m=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(p!=m&&c.getTimezoneOffset()==Math.min(m,p)),(M(),O)[h+32>>>2>>>0]=c}function $w(c){c>>>=0;var h=new Date((M(),O)[c+20>>>2>>>0]+1900,(M(),O)[c+16>>>2>>>0],(M(),O)[c+12>>>2>>>0],(M(),O)[c+8>>>2>>>0],(M(),O)[c+4>>>2>>>0],(M(),O)[c>>>2>>>0],0),p=(M(),O)[c+32>>>2>>>0],m=h.getTimezoneOffset(),y=new Date(h.getFullYear(),6,1).getTimezoneOffset(),T=new Date(h.getFullYear(),0,1).getTimezoneOffset(),S=Math.min(T,y);return 0>p?(M(),O)[c+32>>>2>>>0]=+(y!=T&&S==m):0>>2>>>0]=h.getDay(),p=(mu(h.getFullYear())?gu:wu)[h.getMonth()]+h.getDate()-1|0,(M(),O)[c+28>>>2>>>0]=p,(M(),O)[c>>>2>>>0]=h.getSeconds(),(M(),O)[c+4>>>2>>>0]=h.getMinutes(),(M(),O)[c+8>>>2>>>0]=h.getHours(),(M(),O)[c+12>>>2>>>0]=h.getDate(),(M(),O)[c+16>>>2>>>0]=h.getMonth(),(M(),O)[c+20>>>2>>>0]=h.getYear(),c=h.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function vu(c,h,p,m,y,T,S){return s?be(16,1,c,h,p,m,y,T,S):-52}function yu(c,h,p,m,y,T){if(s)return be(17,1,c,h,p,m,y,T)}var Cn={},Vw=()=>performance.timeOrigin+performance.now();function Mu(c,h){if(s)return be(18,1,c,h);if(Cn[c]&&(clearTimeout(Cn[c].id),delete Cn[c]),!h)return 0;var p=setTimeout(()=>{delete Cn[c],ut(()=>Yu(c,performance.timeOrigin+performance.now()))},h);return Cn[c]={id:p,Ae:h},0}function Uw(c,h,p,m){c>>>=0,h>>>=0,p>>>=0,m>>>=0;var y=new Date().getFullYear(),T=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset();var S=Math.max(T,y);(M(),I)[c>>>2>>>0]=60*S,(M(),O)[h>>>2>>>0]=+(T!=y),c=(h=F=>{var G=Math.abs(F);return`UTC${0<=F?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(T),h=h(y),yDate.now();function qw(c,h,p){return p>>>=0,0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),c=Math.round(1e6*c),(M(),ee)[p>>>3>>>0]=BigInt(c),0):28}var La=[],bu=(c,h)=>{La.length=0;for(var p;p=(M(),q)[c++>>>0];){var m=p!=105;h+=(m&=p!=112)&&h%8?4:0,La.push(p==112?(M(),I)[h>>>2>>>0]:p==106?(M(),ee)[h>>>3>>>0]:p==105?(M(),O)[h>>>2>>>0]:(M(),H)[h>>>3>>>0]),h+=m?8:4}return La};function Ww(c,h,p){return c>>>=0,h=bu(h>>>0,p>>>0),Ha[c](...h)}function Hw(c,h,p){return c>>>=0,h=bu(h>>>0,p>>>0),Ha[c](...h)}var Qw=()=>{};function Xw(c,h){return E($r(c>>>0,h>>>0))}var Yw=()=>{throw Me+=1,"unwind"};function Jw(){return 4294901760}var Kw=()=>1,Zw=()=>navigator.hardwareConcurrency;function ev(c){c>>>=0;var h=(M(),q).length;if(c<=h||4294901760=p;p*=2){var m=h*(1+.2/p);m=Math.min(m,c+100663296);e:{m=(Math.min(4294901760,65536*Math.ceil(Math.max(c,m)/65536))-ir.buffer.byteLength+65535)/65536|0;try{ir.grow(m),W();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1}var zt=c=>{var h=Xt(c)+1,p=fs(h);return Qt(c,p,h),p},Ia=(c,h)=>{(M(),I)[c>>>2>>>0]=h;var p=(M(),I)[c>>>2>>>0];(M(),I)[c+4>>>2>>>0]=(h-p)/4294967296},An=c=>(M(),I)[c>>>2>>>0]+4294967296*(M(),O)[c+4>>>2>>>0],Ke=[],tv=(c,h)=>{Ke[c>>>0]=h},Yt=[],us=[],Ur=(c,h)=>{us[c]=new Promise(p=>h.finally(()=>p(c)))},Z=c=>{if(c)return Ke[c>>>0]},rv=(c,h)=>{for(c=(M(),I)[c>>>2>>>0];c;c=(M(),I)[c>>>2>>>0])h[(M(),O)[c+4>>>2>>>0]](c)},ds=(c,h,p)=>{(M(),I)[c>>>2>>>0]=h,(M(),I)[c+4>>>2>>>0]=p},xu=c=>{var h=(M(),I)[c>>>2>>>0];return c=(M(),I)[c+4>>>2>>>0],$r(h,c)},Jt=c=>{var h=(M(),I)[c>>>2>>>0];return c=(M(),I)[c+4>>>2>>>0],h?$r(h,c):c===0?"":void 0},nv=c=>{var h=Jt(c+4),p=(p=(M(),I)[c+12>>>2>>>0])?Z(p):"auto";if(c+=16){var m=Z((M(),I)[c+4>>>2>>>0]),y=(M(),I)[c+16>>>2>>>0],T=(M(),I)[c+20>>>2>>>0];if(y){for(var S={},F=0;F>>3>>>0]}y=S}else y=void 0;c={module:m,constants:y,entryPoint:Jt(c+8)}}else c=void 0;return{label:h,layout:p,compute:c}},Tu=(c,h)=>{function p(m,y){m=c[m],(M(),I)[h+y>>>2>>>0]=m}p("maxTextureDimension1D",4),p("maxTextureDimension2D",8),p("maxTextureDimension3D",12),p("maxTextureArrayLayers",16),p("maxBindGroups",20),p("maxBindGroupsPlusVertexBuffers",24),p("maxBindingsPerBindGroup",28),p("maxDynamicUniformBuffersPerPipelineLayout",32),p("maxDynamicStorageBuffersPerPipelineLayout",36),p("maxSampledTexturesPerShaderStage",40),p("maxSamplersPerShaderStage",44),p("maxStorageBuffersPerShaderStage",48),p("maxStorageTexturesPerShaderStage",52),p("maxUniformBuffersPerShaderStage",56),p("minUniformBufferOffsetAlignment",80),p("minStorageBufferOffsetAlignment",84),Ia(h+64,c.maxUniformBufferBindingSize),Ia(h+72,c.maxStorageBufferBindingSize),p("maxVertexBuffers",88),Ia(h+96,c.maxBufferSize),p("maxVertexAttributes",104),p("maxVertexBufferArrayStride",108),p("maxInterStageShaderVariables",112),p("maxColorAttachments",116),p("maxColorAttachmentBytesPerSample",120),p("maxComputeWorkgroupStorageSize",124),p("maxComputeInvocationsPerWorkgroup",128),p("maxComputeWorkgroupSizeX",132),p("maxComputeWorkgroupSizeY",136),p("maxComputeWorkgroupSizeZ",140),p("maxComputeWorkgroupsPerDimension",144),c.ze!==void 0&&p("maxImmediateSize",148)},sv=[,"validation","out-of-memory","internal"],av=[,"compatibility","core"],ku={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"},ov=[,"low-power","high-performance"],iv=[,"occlusion","timestamp"],lv={undefined:1,unknown:1,destroyed:2};function cv(c,h,p,m,y,T){h=Je(h),p=Je(p),m>>>=0,y>>>=0,T>>>=0;var S=Z(c>>>0);if(c={},T){var F=(M(),I)[T+12>>>2>>>0];if(F){var G=(M(),I)[T+16>>>2>>>0];c.requiredFeatures=Array.from((M(),I).subarray(G>>>2>>>0,G+4*F>>>2>>>0),Y=>ku[Y])}var X=(M(),I)[T+20>>>2>>>0];if(X){let Y=function(Fe,Qe,Fn=!1){Qe=X+Qe,(Qe=(M(),I)[Qe>>>2>>>0])==4294967295||Fn&&Qe==0||(ge[Fe]=Qe)},ce=function(Fe,Qe){Qe=X+Qe;var Fn=(M(),I)[Qe>>>2>>>0],Qa=(M(),I)[Qe+4>>>2>>>0];Fn==4294967295&&Qa==4294967295||(ge[Fe]=An(Qe))};var ge={};Y("maxTextureDimension1D",4),Y("maxTextureDimension2D",8),Y("maxTextureDimension3D",12),Y("maxTextureArrayLayers",16),Y("maxBindGroups",20),Y("maxBindGroupsPlusVertexBuffers",24),Y("maxDynamicUniformBuffersPerPipelineLayout",32),Y("maxDynamicStorageBuffersPerPipelineLayout",36),Y("maxSampledTexturesPerShaderStage",40),Y("maxSamplersPerShaderStage",44),Y("maxStorageBuffersPerShaderStage",48),Y("maxStorageTexturesPerShaderStage",52),Y("maxUniformBuffersPerShaderStage",56),Y("minUniformBufferOffsetAlignment",80),Y("minStorageBufferOffsetAlignment",84),ce("maxUniformBufferBindingSize",64),ce("maxStorageBufferBindingSize",72),Y("maxVertexBuffers",88),ce("maxBufferSize",96),Y("maxVertexAttributes",104),Y("maxVertexBufferArrayStride",108),Y("maxInterStageShaderVariables",112),Y("maxColorAttachments",116),Y("maxColorAttachmentBytesPerSample",120),Y("maxComputeWorkgroupStorageSize",124),Y("maxComputeInvocationsPerWorkgroup",128),Y("maxComputeWorkgroupSizeX",132),Y("maxComputeWorkgroupSizeY",136),Y("maxComputeWorkgroupSizeZ",140),Y("maxComputeWorkgroupsPerDimension",144),Y("maxImmediateSize",148,!0),c.requiredLimits=ge}(F=(M(),I)[T+24>>>2>>>0])&&(F={label:Jt(F+4)},c.defaultQueue=F),c.label=Jt(T+4)}Me+=1,Ur(h,S.requestDevice(c).then(Y=>{--Me,ut(()=>{Ke[y>>>0]=Y.queue,Ke[m>>>0]=Y,Me+=1,Ur(p,Y.lost.then(ce=>{ut(()=>{Y.onuncapturederror=()=>{};var Fe=re(),Qe=zt(ce.message);Ba(p,lv[ce.reason],Qe),te(Fe)}),--Me})),Y.onuncapturederror=ce=>{var Fe=5;ce.error instanceof GPUValidationError?Fe=2:ce.error instanceof GPUOutOfMemoryError?Fe=3:ce.error instanceof GPUInternalError&&(Fe=4);var Qe=re();ce=zt(ce.error.message),Wu(m,Fe,ce),te(Qe)},"adapterInfo"in Y||(Y.adapterInfo=S.info),$a(h,1,m,0)})},Y=>{--Me,ut(()=>{var ce=re(),Fe=zt(Y.message);$a(h,3,m,Fe),p&&Ba(p,4,Fe),te(ce)})}))}function uv(c){var h=Z(c>>>=0),p=Yt[c];if(p){for(var m=0;m>>=0;var m=Z(c>>>=0);p==4294967295&&(p=void 0);try{var y=m.getMappedRange(h>>>0,p)}catch{return 0}var T=ja(16,y.byteLength);return(M(),q).set(new Uint8Array(y),T>>>0),Yt[c].push(()=>Et(T)),T}function hv(c,h,p){p>>>=0;var m=Z(c>>>=0);p==4294967295&&(p=void 0);try{var y=m.getMappedRange(h>>>0,p)}catch{return 0}var T=ja(16,y.byteLength);return(M(),q).fill(0,T,y.byteLength),Yt[c].push(()=>{new Uint8Array(y).set((M(),q).subarray(T>>>0,T+y.byteLength>>>0)),Et(T)}),T}function fv(c,h,p,m,y){c>>>=0,h=Je(h),p=Je(p),y>>>=0;var T=Z(c);Yt[c]=[],y==4294967295&&(y=void 0),Me+=1,Ur(h,T.mapAsync(p,m>>>0,y).then(()=>{--Me,ut(()=>{Ra(h,1,0)})},S=>{--Me,ut(()=>{re();var F=zt(S.message);Ra(h,S.name==="AbortError"?4:S.name==="OperationError"?3:0,F),delete Yt[c]})}))}function _v(c){var h=Z(c>>>=0),p=Yt[c];if(p){for(var m=0;m>>0]}function mv(c,h,p){c>>>=0,h>>>=0,p>>>=0;var m=!!(M(),I)[h+32>>>2>>>0];h={label:Jt(h+4),usage:(M(),I)[h+16>>>2>>>0],size:An(h+24),mappedAtCreation:m},c=Z(c);try{var y=c.createBuffer(h)}catch{return!1}return Ke[p>>>0]=y,m&&(Yt[p]=[]),!0}function gv(c,h,p,m){c>>>=0,h=Je(h),m>>>=0,p=nv(p>>>0),c=Z(c),Me+=1,Ur(h,c.createComputePipelineAsync(p).then(y=>{--Me,ut(()=>{Ke[m>>>0]=y,za(h,1,m,0)})},y=>{--Me,ut(()=>{var T=re(),S=zt(y.message);za(h,y.reason==="validation"?3:y.reason==="internal"?4:0,m,S),te(T)})}))}function wv(c,h,p){c>>>=0,h>>>=0,p>>>=0;var m=(M(),I)[h>>>2>>>0],y=(M(),O)[m+4>>>2>>>0];h={label:Jt(h+4),code:""},y===2&&(h.code=xu(m+8)),c=Z(c).createShaderModule(h),Ke[p>>>0]=c}var vv=c=>{(c=Z(c)).onuncapturederror=null,c.destroy()};function yv(c,h){h=Je(h),c=Z(c>>>0),Me+=1,Ur(h,c.popErrorScope().then(p=>{--Me,ut(()=>{var m=5;p?p instanceof GPUValidationError?m=2:p instanceof GPUOutOfMemoryError?m=3:p instanceof GPUInternalError&&(m=4):m=1;var y=re(),T=p?zt(p.message):0;Ga(h,1,m,T),te(y)})},p=>{--Me,ut(()=>{var m=re(),y=zt(p.message);Ga(h,1,5,y),te(m)})}))}function Mv(c,h,p,m){if(h=Je(h),m>>>=0,p>>>=0){var y={featureLevel:av[(M(),O)[p+4>>>2>>>0]],powerPreference:ov[(M(),O)[p+8>>>2>>>0]],forceFallbackAdapter:!!(M(),I)[p+12>>>2>>>0]};(c=(M(),I)[p>>>2>>>0])!==0&&(M(),y.De=!!(M(),I)[c+8>>>2>>>0])}"gpu"in navigator?(Me+=1,Ur(h,navigator.gpu.requestAdapter(y).then(T=>{--Me,ut(()=>{if(T)Ke[m>>>0]=T,Sn(h,1,m,0);else{var S=re(),F=zt("WebGPU not available on this browser (requestAdapter returned null)");Sn(h,3,m,F),te(S)}})},T=>{--Me,ut(()=>{var S=re(),F=zt(T.message);Sn(h,4,m,F),te(S)})}))):(y=re(),c=zt("WebGPU not available on this browser (navigator.gpu is not available)"),Sn(h,3,m,c),te(y))}function bv(c,h,p){return c>>>=0,h>>>=0,p>>>=0,_u(async()=>{var m=[];if(p){var y=(M(),O)[p>>>2>>>0];m.length=h+1,m[h]=new Promise(F=>setTimeout(F,y,0))}else m.length=h;for(var T=0;T{if(!Oa){var c,h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in Na)Na[c]===void 0?delete h[c]:h[c]=Na[c];var p=[];for(c in h)p.push(`${c}=${h[c]}`);Oa=p}return Oa};function Cu(c,h){if(s)return be(19,1,c,h);c>>>=0,h>>>=0;var p,m=0,y=0;for(p of Eu()){var T=h+m;(M(),I)[c+y>>>2>>>0]=T,m+=Qt(p,T,1/0)+1,y+=4}return 0}function Au(c,h){if(s)return be(20,1,c,h);c>>>=0,h>>>=0;var p=Eu();for(var m of((M(),I)[c>>>2>>>0]=p.length,c=0,p))c+=Xt(m)+1;return(M(),I)[h>>>2>>>0]=c,0}function Su(c){return s?be(21,1,c):52}function Pu(c,h,p,m){return s?be(22,1,c,h,p,m):52}function Fu(c,h,p,m){return s?be(23,1,c,h,p,m):70}var xv=[null,[],[]];function Lu(c,h,p,m){if(s)return be(24,1,c,h,p,m);h>>>=0,p>>>=0,m>>>=0;for(var y=0,T=0;T>>2>>>0],F=(M(),I)[h+4>>>2>>>0];h+=8;for(var G=0;G>>0],Y=xv[X];ge===0||ge===10?((X===1?C:E)(Qc(Y)),Y.length=0):Y.push(ge)}y+=F}return(M(),I)[m>>>2>>>0]=y,0}function Tv(c){return c>>>0}function kv(c,h){return Tu(Z(c>>>0).limits,h>>>0),1}function Ev(c,h){return Z(c>>>0).features.has(ku[h])}function Cv(c){return BigInt(Z(c>>>0).size)}function Av(c){return BigInt(Z(c>>>0).usage)}function Sv(c,h){if(c>>>=0,h>>>=0){var p=Jt(h+4);p={label:p,timestampWrites:h=(h=(M(),I)[h+12>>>2>>>0])!==0?{querySet:Z((M(),I)[h+4>>>2>>>0]),beginningOfPassWriteIndex:(M(),I)[h+8>>>2>>>0],endOfPassWriteIndex:(M(),I)[h+12>>>2>>>0]}:void 0}}return h=Z(c),c=$u(0),p=h.beginComputePass(p),Ke[c>>>0]=p,c}function Pv(c,h,p,m){p=Je(p),(m=Je(m))==-1&&(m=void 0),(c=Z(c>>>0)).clearBuffer(Z(h>>>0),p,m)}function Fv(c,h,p,m,y,T){p=Je(p),y=Je(y),T=Je(T),Z(c>>>0).copyBufferToBuffer(Z(h>>>0),p,Z(m>>>0),y,T)}function Lv(c){var h=Z(c>>>0);return c=Ru(0),h=h.finish(),Ke[c>>>0]=h,c}function Iv(c,h,p,m,y,T){T=Je(T),Z(c>>>0).resolveQuerySet(Z(h>>>0),p,m,Z(y>>>0),T)}function Ov(c,h,p,m){Z(c>>>0).dispatchWorkgroups(h,p,m)}function Nv(c,h,p){p=Je(p),Z(c>>>0).dispatchWorkgroupsIndirect(Z(h>>>0),p)}function Dv(c){Z(c>>>0).end()}function zv(c,h,p,m,y){m>>>=0,y>>>=0,c=Z(c>>>0),p=Z(p>>>0),m==0?c.setBindGroup(h,p):c.setBindGroup(h,p,(M(),I),y>>>2,m)}function Bv(c,h){Z(c>>>0).setPipeline(Z(h>>>0))}function Rv(c,h,p){Z(c>>>0).Ce(Z(h>>>0),p)}function Gv(c,h){var p=Z(c>>>0);return c=Bu(0),h=p.getBindGroupLayout(h),Ke[c>>>0]=h,c}function $v(c,h){function p(y){var T=(M(),I)[y+8>>>2>>>0],S=(M(),I)[y+32>>>2>>>0],F=(M(),I)[y+36>>>2>>>0],G=0;return rv(y,{327681:X=>{G=(M(),I)[X+8>>>2>>>0]}}),T?((S=An(y+24))==-1&&(S=void 0),T={buffer:Z(T),offset:An(y+16),size:S}):T=Z(S||F||G),{binding:(M(),I)[y+4>>>2>>>0],resource:T}}c>>>=0,h={label:Jt(4+(h>>>=0)),layout:Z((M(),I)[h+12>>>2>>>0]),entries:(function(y,T){for(var S=[],F=0;F>>2>>>0],(M(),I)[h+20>>>2>>>0])},c=Z(c);var m=zu(0);return tv(m,c.createBindGroup(h)),m}function Vv(c,h){var p;return c>>>=0,(h>>>=0)&&(p={label:Jt(h+4)}),h=Z(c),c=Gu(0),p=h.createCommandEncoder(p),Ke[c>>>0]=p,c}function Uv(c,h){c>>>=0,h>>>=0,h={type:iv[(M(),O)[h+12>>>2>>>0]],count:(M(),I)[h+16>>>2>>>0]};var p=Z(c);return c=Vu(0),h=p.createQuerySet(h),Ke[c>>>0]=h,c}function jv(c,h){c=Z(c>>>0).adapterInfo,h>>>=0,(M(),I)[h+52>>>2>>>0]=c.subgroupMinSize,(M(),I)[h+56>>>2>>>0]=c.subgroupMaxSize;var p=c.vendor+c.architecture+c.device+c.description,m=Xt(p)+1,y=jr(m);return y&&Qt(p,y,m),p=y,m=Xt(c.vendor),ds(h+4,p,m),p+=m,m=Xt(c.architecture),ds(h+12,p,m),p+=m,m=Xt(c.device),ds(h+20,p,m),ds(h+28,p+m,Xt(c.description)),(M(),O)[h+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(M(),O)[h+40>>>2>>>0]=c,(M(),I)[h+44>>>2>>>0]=0,(M(),I)[h+48>>>2>>>0]=0,1}var qv={"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 Wv(c,h){h>>>=0;var p=Z(c>>>0);c=jr(4*p.features.size);var m=0,y=0;for(let T of p.features)0<=(p=qv[T])&&((M(),O)[c+m>>>2>>>0]=p,m+=4,y++);(M(),I)[h+4>>>2>>>0]=c,(M(),I)[h>>>2>>>0]=y}function Hv(c,h){return Tu(Z(c>>>0).limits,h>>>0),1}function Qv(c,h){Z(c>>>0).pushErrorScope(sv[h])}function Xv(c,h,p){h>>>=0,p>>>=0,c=Z(c>>>0),h=Array.from((M(),O).subarray(p>>>2>>>0,p+4*h>>>2>>>0),m=>Z(m)),c.submit(h)}function Yv(c,h,p,m,y){p=Je(p),m>>>=0,y>>>=0,c=Z(c>>>0),h=Z(h>>>0),m=(M(),q).subarray(m>>>0,m+y>>>0),c.writeBuffer(h,p,m,0,y)}s||(function(){for(var c=t.numThreads-1;c--;)$c();ct.push(async()=>{var h=(async function(){if(!s)return Promise.all(or.map(Gc))})();Se++,await h,--Se==0&&ve&&(h=ve,ve=null,h())})})(),s||(ir=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),W()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>re(),t.stackRestore=c=>te(c),t.stackAlloc=c=>fs(c),t.setValue=function(c,h,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":(M(),R)[c>>>0]=h;break;case"i16":(M(),K)[c>>>1>>>0]=h;break;case"i32":(M(),O)[c>>>2>>>0]=h;break;case"i64":(M(),ee)[c>>>3>>>0]=BigInt(h);break;case"float":(M(),$)[c>>>2>>>0]=h;break;case"double":(M(),H)[c>>>3>>>0]=h;break;case"*":(M(),I)[c>>>2>>>0]=h;break;default:Te(`invalid type for setValue: ${p}`)}},t.getValue=function(c,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":return(M(),R)[c>>>0];case"i16":return(M(),K)[c>>>1>>>0];case"i32":return(M(),O)[c>>>2>>>0];case"i64":return(M(),ee)[c>>>3>>>0];case"float":return(M(),$)[c>>>2>>>0];case"double":return(M(),H)[c>>>3>>>0];case"*":return(M(),I)[c>>>2>>>0];default:Te(`invalid type for getValue: ${h}`)}},t.UTF8ToString=$r,t.stringToUTF8=Qt,t.lengthBytesUTF8=Xt;var Iu,Ou,Da,hs,Et,jr,Nu,Du,zu,Bu,Ru,Gu,$u,Vu,Uu,ju,qu,za,Ba,Ra,Ga,Sn,$a,Wu,Va,Hu,Qu,Xu,Ua,Yu,Ju,ja,fe,Pn,Ku,te,fs,re,Zu,qa,ed,td,rd,Wa,nd,sd,ad,od,id,ld,cd,ud,dd,hd,fd,_d,pd,md,gd,wd,vd,yd,Md,bd,xd,Td,kd,Ed,Cd,Ad,Sd,Pd,Fd,Ld,Id,Od,Nd,Dd,zd,Bd,Rd,Gd,Kt,Jv=[Br,kn,jc,Xc,Yc,Jc,Kc,Zc,eu,tu,ru,nu,su,au,ou,iu,vu,yu,Mu,Cu,Au,Su,Pu,Fu,Lu],Ha={970348:(c,h,p,m,y)=>{if(t===void 0||!t.Uc)return 1;if((c=$r(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=t.Uc.get(c)))return 2;if(h=Number(h>>>0),p=Number(p>>>0),m=Number(m>>>0),h+p>c.byteLength)return 3;try{let T=c.subarray(h,h+p);switch(y){case 0:(M(),q).set(T,m>>>0);break;case 1:t.ad?t.ad(m,T):t.ne(m,T);break;default:return 4}return 0}catch{return 4}},971172:(c,h,p)=>{t.Sd(c,(M(),q).subarray(h>>>0,h+p>>>0))},971236:()=>t.le(),971278:c=>{t.jd(c)},971315:()=>typeof wasmOffsetConverter<"u"};function Kv(c,h,p,m){var y=re();try{return ud(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function Zv(c,h,p){var m=re();try{return id(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;fe(1,0)}}function ey(c){var h=re();try{nd(c)}catch(p){if(te(h),p!==p+0)throw p;fe(1,0)}}function ty(c,h){var p=re();try{return Wa(c,h)}catch(m){if(te(p),m!==m+0)throw m;fe(1,0)}}function ry(c,h,p){var m=re();try{rd(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;fe(1,0)}}function ny(c,h){var p=re();try{dd(c,h)}catch(m){if(te(p),m!==m+0)throw m;fe(1,0)}}function sy(c,h,p,m,y,T,S){var F=re();try{return od(c,h,p,m,y,T,S)}catch(G){if(te(F),G!==G+0)throw G;fe(1,0)}}function ay(c,h,p,m,y,T){var S=re();try{sd(c,h,p,m,y,T)}catch(F){if(te(S),F!==F+0)throw F;fe(1,0)}}function oy(c,h,p,m){var y=re();try{cd(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function iy(c,h,p,m,y,T,S){var F=re();try{fd(c,h,p,m,y,T,S)}catch(G){if(te(F),G!==G+0)throw G;fe(1,0)}}function ly(c,h,p,m,y,T,S){var F=re();try{_d(c,h,p,m,y,T,S)}catch(G){if(te(F),G!==G+0)throw G;fe(1,0)}}function cy(c,h,p,m,y,T,S,F){var G=re();try{xd(c,h,p,m,y,T,S,F)}catch(X){if(te(G),X!==X+0)throw X;fe(1,0)}}function uy(c,h,p,m,y,T,S,F,G,X,ge,Y){var ce=re();try{pd(c,h,p,m,y,T,S,F,G,X,ge,Y)}catch(Fe){if(te(ce),Fe!==Fe+0)throw Fe;fe(1,0)}}function dy(c,h,p,m,y){var T=re();try{return hd(c,h,p,m,y)}catch(S){if(te(T),S!==S+0)throw S;fe(1,0)}}function hy(c,h,p,m,y){var T=re();try{ad(c,h,p,m,y)}catch(S){if(te(T),S!==S+0)throw S;fe(1,0)}}function fy(c,h,p,m,y,T,S,F){var G=re();try{ld(c,h,p,m,y,T,S,F)}catch(X){if(te(G),X!==X+0)throw X;fe(1,0)}}function _y(c){var h=re();try{return Td(c)}catch(p){if(te(h),p!==p+0)throw p;fe(1,0)}}function py(c,h,p){var m=re();try{return kd(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;fe(1,0)}}function my(c,h){var p=re();try{return Dd(c,h)}catch(m){if(te(p),m!==m+0)throw m;return fe(1,0),0n}}function gy(c){var h=re();try{return md(c)}catch(p){if(te(h),p!==p+0)throw p;return fe(1,0),0n}}function wy(c,h,p,m){var y=re();try{return Ed(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function vy(c,h,p,m,y){var T=re();try{return Cd(c,h,p,m,y)}catch(S){if(te(T),S!==S+0)throw S;fe(1,0)}}function yy(c,h,p,m,y,T){var S=re();try{return Ad(c,h,p,m,y,T)}catch(F){if(te(S),F!==F+0)throw F;fe(1,0)}}function My(c,h,p,m,y,T){var S=re();try{return Md(c,h,p,m,y,T)}catch(F){if(te(S),F!==F+0)throw F;fe(1,0)}}function by(c,h,p,m,y,T){var S=re();try{return Sd(c,h,p,m,y,T)}catch(F){if(te(S),F!==F+0)throw F;fe(1,0)}}function xy(c,h,p,m,y,T,S,F){var G=re();try{return bd(c,h,p,m,y,T,S,F)}catch(X){if(te(G),X!==X+0)throw X;fe(1,0)}}function Ty(c,h,p,m,y){var T=re();try{return Pd(c,h,p,m,y)}catch(S){if(te(T),S!==S+0)throw S;return fe(1,0),0n}}function ky(c,h,p,m){var y=re();try{return Fd(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function Ey(c,h,p,m){var y=re();try{return Ld(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function Cy(c,h,p,m,y,T,S,F,G,X,ge,Y){var ce=re();try{return Id(c,h,p,m,y,T,S,F,G,X,ge,Y)}catch(Fe){if(te(ce),Fe!==Fe+0)throw Fe;fe(1,0)}}function Ay(c,h,p,m,y,T,S,F,G,X,ge){var Y=re();try{Od(c,h,p,m,y,T,S,F,G,X,ge)}catch(ce){if(te(Y),ce!==ce+0)throw ce;fe(1,0)}}function Sy(c,h,p,m,y,T,S,F,G,X,ge,Y,ce,Fe,Qe,Fn){var Qa=re();try{Nd(c,h,p,m,y,T,S,F,G,X,ge,Y,ce,Fe,Qe,Fn)}catch(Xa){if(te(Qa),Xa!==Xa+0)throw Xa;fe(1,0)}}function Py(c,h,p){var m=re();try{return wd(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;return fe(1,0),0n}}function Fy(c,h,p){var m=re();try{return gd(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;fe(1,0)}}function Ly(c,h,p){var m=re();try{return vd(c,h,p)}catch(y){if(te(m),y!==y+0)throw y;fe(1,0)}}function Iy(c,h,p,m){var y=re();try{yd(c,h,p,m)}catch(T){if(te(y),T!==T+0)throw T;fe(1,0)}}function _s(){if(0{let h=new WeakMap,p,m,y=1;t.webgpuRegisterDevice=F=>{if(m!==void 0)throw Error("another WebGPU EP inference session is being created.");if(F){var G=h.get(F);if(!G){let X=((ge,Y=0)=>{var ce=qu(Y);return Y=ju(Y,ce),Ke[ce>>>0]=ge.queue,Ke[Y>>>0]=ge,Y})(F,G=Du(0));G=[y++,G,X],h.set(F,G)}return p=F,m=G[0],G}p=void 0,m=0};let T=new Map;t.webgpuOnCreateSession=F=>{if(m!==void 0){var G=m;if(m=void 0,F){let X=Da(G);T.set(F,X),G===0&&c(p??Z(X))}p=void 0}},t.webgpuOnReleaseSession=F=>{T.delete(F)};let S=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(F,G,X)=>{if(X)return F[S]=[X,NaN],X;if(X=F[S])return X[1]++,X[0];if((G=T.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((ge,Y=0)=>(ge.mapState==="unmapped"||Te(),Y=Uu(Y),Ke[Y>>>0]=ge,Y))(F,G),F[S]=[G,1],G},t.webgpuUnregisterBuffer=F=>{let G=F[S];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(Nu(G[0]),delete F[S])},t.webgpuGetBuffer=F=>Z(F),t.webgpuCreateDownloader=(F,G,X)=>{if((X=T.get(X))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ge=Z(X),Y=16*Math.ceil(Number(G)/16);return async()=>{let ce=ge.createBuffer({size:Y,usage:9});try{let Fe=ge.createCommandEncoder();return Fe.copyBufferToBuffer(F,0,ce,0,Y),ge.queue.submit([Fe.finish()]),await ce.mapAsync(GPUMapMode.READ),ce.getMappedRange().slice(0,G)}finally{ce.destroy()}}},t.ad=(F,G)=>{var X=G.buffer;let ge=G.byteOffset,Y=G.byteLength;if(G=16*Math.ceil(Number(Y)/16),F=Z(F),!p){var ce=Da(m);p=Z(ce)}let Fe=(ce=p.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(Fe).set(new Uint8Array(X,ge,Y)),ce.unmap(),(X=p.createCommandEncoder()).copyBufferToBuffer(ce,0,F,0,G),p.queue.submit([X.finish()]),ce.destroy()}},t.webnnInit=c=>{let h=c[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=c.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=p=>h.onRunStart(p),t.webnnOnRunEnd=h.onRunEnd.bind(h),t.webnnOnReleaseSession=p=>{h.onReleaseSession(p)},t.webnnCreateMLTensorDownloader=(p,m)=>h.createMLTensorDownloader(p,m),t.webnnRegisterMLTensor=(p,m,y,T)=>h.registerMLTensor(p,m,y,T),t.webnnCreateMLContext=p=>h.createMLContext(p),t.webnnRegisterMLConstant=(p,m,y,T,S,F)=>h.registerMLConstant(p,m,y,T,S,t.Uc,F),t.webnnRegisterGraphInput=h.registerGraphInput.bind(h),t.webnnIsGraphInput=h.isGraphInput.bind(h),t.webnnRegisterGraphOutput=h.registerGraphOutput.bind(h),t.webnnIsGraphOutput=h.isGraphOutput.bind(h),t.webnnCreateTemporaryTensor=h.createTemporaryTensor.bind(h),t.webnnIsGraphInputOutputTypeSupported=h.isGraphInputOutputTypeSupported.bind(h)},B?t:new Promise((c,h)=>{w=c,v=h})}var Nf,Ud,eM=me(()=>{Nf=Vd,Ud=globalThis.self?.name?.startsWith("em-pthread"),Ud&&Vd()}),to,Po,jd,ft,Df,ms,qd,Wd,ro,Hd,no,zf,so,Bf,Yo=me(()=>{Xo(),to=typeof location>"u"?void 0:location.origin,Po=import.meta.url>"file:"&&import.meta.url<"file;",jd=()=>{{if(Po){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,to).href}return import.meta.url}},ft=jd(),Df=()=>{if(ft&&!ft.startsWith("blob:"))return ft.substring(0,ft.lastIndexOf("/")+1)},ms=(e,t)=>{try{let r=t??ft;return(r?new URL(e,r):new URL(e)).origin===to}catch{return!1}},qd=(e,t)=>{let r=t??ft;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Wd=(e,t)=>`${t??"./"}${e}`,ro=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Hd=async e=>(await import(e)).default,no=(Zy(),Is(Lf)).default,zf=async()=>{if(!ft)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ms(ft))return[void 0,no()];let e=await ro(ft);return[e,no(e)]},so=(eM(),Is(Of)).default,Bf=async(e,t,r,n)=>{let s=so&&!(e||t);if(s)if(ft)s=ms(ft)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,so];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??qd(a,t),i=r&&o&&!ms(o,t),l=i?await ro(o):o??Wd(a,t);return[i?l:void 0,await Hd(l)]}}}),ao,gs,In,oo,Qd,Xd,Yd,Jo,Pe,Nr=me(()=>{Yo(),gs=!1,In=!1,oo=!1,Qd=()=>{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}},Xd=()=>{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}},Yd=()=>{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}},Jo=async e=>{if(gs)return Promise.resolve();if(In)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(oo)throw new Error("previous call to 'initializeWebAssembly()' failed.");In=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Yd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Xd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Qd();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,o=s?.mjs,i=o?.href??o,l=s?.wasm,u=l?.href??l,d=e.wasmBinary,[f,_]=await Bf(i,a,r>1,!!d||!!u),g=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{g=!0,v()},t)})),w.push(new Promise((v,x)=>{let b={numThreads:r};if(d)b.wasmBinary=d,b.locateFile=k=>k;else if(u||a)b.locateFile=k=>u??a+k;else if(i&&i.indexOf("blob:")!==0)b.locateFile=k=>new URL(k,i).href;else if(f){let k=Df();k&&(b.locateFile=C=>k+C)}_(b).then(k=>{In=!1,gs=!0,ao=k,v(),f&&URL.revokeObjectURL(f)},k=>{In=!1,oo=!0,x(k)})})),await Promise.race(w),g)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(gs&&ao)return ao;throw new Error("WebAssembly is not initialized yet.")}}),_t,Ns,xe,Ko=me(()=>{Nr(),_t=(e,t)=>{let r=Pe(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ns=(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 o=t?t+s:s;if(typeof a=="object")Ns(a,o+".",r,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},xe=e=>{let t=Pe(),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")),o=t.getValue(s+n,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),Rf,tM=me(()=>{Nr(),Ko(),Rf=e=>{let t=Pe(),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=_t(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&xe("Can't create run options."),e?.extra!==void 0&&Ns(e.extra,"",new WeakSet,(o,i)=>{let l=_t(o,n),u=_t(i,n);t._OrtAddRunConfigEntry(r,l,u)!==0&&xe(`Can't set a run config entry: ${o} - ${i}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),a}}}),Jd,Kd,Zd,ws,ur,eh,Gf,rM=me(()=>{Nr(),Ko(),Jd=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}`)}},Kd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Zd=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)},ws=(e,t,r,n)=>{let s=_t(t,n),a=_t(r,n);Pe()._OrtAddSessionConfigEntry(e,s,a)!==0&&xe(`Can't set a session config entry: ${t} - ${r}.`)},ur=(e,t,r,n)=>{let s=_t(t,n),a=_t(r,n);e.push([s,a])},eh=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let f=s?.deviceType;f&&ws(e,"deviceType",f,r)}break;case"webgpu":{a="WebGPU";let f;if(typeof s!="string"){let g=s;if(g.device)if(typeof GPUDevice<"u"&&g.device instanceof GPUDevice)f=g.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&ur(o,"enableGraphCapture","1",r),typeof g.preferredLayout=="string"&&ur(o,"preferredLayout",g.preferredLayout,r),g.forceCpuNodeNames){let v=Array.isArray(g.forceCpuNodeNames)?g.forceCpuNodeNames:[g.forceCpuNodeNames];ur(o,"forceCpuNodeNames",v.join(` +`),r)}g.validationMode&&ur(o,"validationMode",g.validationMode,r)}let _=Pe().webgpuRegisterDevice(f);if(_){let[g,w,v]=_;ur(o,"deviceId",g.toString(),r),ur(o,"webgpuInstance",w.toString(),r),ur(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=_t(a,r),l=o.length,u=0,d=0;if(l>0){u=Pe()._malloc(l*Pe().PTR_SIZE),r.push(u),d=Pe()._malloc(l*Pe().PTR_SIZE),r.push(d);for(let f=0;f{let t=Pe(),r=0,n=[],s=e||{};Zd(s);try{let a=Jd(s.graphOptimizationLevel??"all"),o=Kd(s.executionMode??"sequential"),i=typeof s.logId=="string"?_t(s.logId,n):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let u=s.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let d=typeof s.optimizedModelFilePath=="string"?_t(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,u,d),r===0&&xe("Can't create session options."),s.executionProviders&&await eh(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);ws(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[f,_]of Object.entries(s.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let g=_t(f,n);t._OrtAddFreeDimensionOverride(r,g,_)!==0&&xe(`Can't set a free dimension override: ${f} - ${_}.`)}return s.extra!==void 0&&Ns(s.extra,"",new WeakSet,(f,_)=>{ws(r,f,_,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&xe("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Ar,Ss,Yr,Un,Ds,Zo,ei,Fo,an=me(()=>{Ar=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}`)}},Ss=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}`)}},Yr=(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},Un=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}`)}},Ds=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}`)}},Zo=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ei=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fo=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}`)}}}),ti,$f=me(()=>{Xo(),ti=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(i){if(i instanceof RangeError){let l=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;let u=l.byteLength;new Uint8Array(a,o,u).set(l),o+=u}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Vf,nM=me(()=>{an(),Vf=(e,t)=>new(Un(t))(e)}),th,rh,nh,sh,Uf,ah,nt,jf=me(()=>{an(),th=["V","I","W","E","F"],rh=(e,t)=>{console.log(`[${th[e]},${new Date().toISOString()}]${t}`)},Uf=(e,t)=>{nh=e,sh=t},ah=(e,t)=>{let r=Ds(e),n=Ds(nh);r>=n&&rh(r,typeof t=="function"?t():t)},nt=(...e)=>{sh&&ah(...e)}}),io,Lo,lo,oh,co,ih,uo,ho,fo,lh,qf,sM=me(()=>{an(),jf(),io=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Lo=(e,t)=>{if(t==="int32")return e;let r=io.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(Un(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},lo=(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}`)}},oh=1,co=()=>oh++,ih=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),uo=(e,t)=>{let r=io.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},ho=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return uo(this.dataType,this.tensorShape)}destroy(){nt("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=lo(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}},fo=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),o;if(!a?.input.dataTypes.includes(t)){if(o=ih.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);nt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==uo(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 i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),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=Lo(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 nt("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?lo(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()}},lh=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=co();return this.tensorTrackersById.set(e,new fo(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){nt("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){nt("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=co(),o=new ho({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new fo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[u,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){nt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=e,f}nt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new ho({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},qf=(...e)=>new lh(...e)}),Wf={};Wn(Wf,{WebNNBackend:()=>Hf});var On,ch,Hf,aM=me(()=>{an(),Nr(),nM(),sM(),jf(),On=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ch=(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])},Hf=class{constructor(e){this.tensorManager=qf(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,Uf(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){nt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){nt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)nt("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=>ch(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){nt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=On.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){nt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=On.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(!Pe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");nt("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 Vf(r,t)}}registerMLTensor(e,t,r,n){let s=On.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return nt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(t,t+r).buffer,d;switch(s.dataType){case"float32":d=new Float32Array(u);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":d=new Int32Array(u);break;case"uint32":d=new Uint32Array(u);break;case"int64":if(o){let f=Lo(new Uint8Array(u),"int64");d=new Int32Array(f.buffer),s.dataType="int32"}else d=new BigInt64Array(u);break;case"uint64":d=new BigUint64Array(u);break;case"int8":d=new Int8Array(u);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return nt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,d)}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=On.get(Ar(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),uh,ri,ni,dr,dh,_o,zs,si,ai,po,oi,ii,li,Qf=me(()=>{Or(),tM(),rM(),an(),Nr(),Ko(),$f(),uh=(e,t)=>{Pe()._OrtInit(e,t)!==0&&xe("Can't initialize onnxruntime.")},ri=async e=>{uh(e.wasm.numThreads,Ds(e.logLevel))},ni=async(e,t)=>{Pe().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"&&Pe().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(aM(),Is(Wf)).WebNNBackend(e);Pe().webnnInit([n,()=>n.reserveTensorId(),s=>n.releaseTensorId(s),async(s,a,o,i,l)=>n.ensureTensor(s,a,o,i,l),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},dr=new Map,dh=e=>{let t=Pe(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&xe("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)}},_o=(e,t)=>{let r=Pe(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&xe("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));s=Number(r.getValue(o+a,"*"));let l=r.HEAP32[s/4];if(l===0)return[i,0];let u=r.HEAPU32[s/4+1],d=[];for(let f=0;f{let t=Pe(),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]},si=async(e,t)=>{let r,n,s=Pe();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=zs(e);let a=0,o=0,i=0,l=[],u=[],d=[];try{if([o,l]=await Gf(t),t?.externalData&&s.mountExternalData){let E=[];for(let P of t.externalData){let z=typeof P=="string"?P:P.path;E.push(ti(typeof P=="string"?P:P.data).then(M=>{s.mountExternalData(z,M)}))}await Promise.all(E)}for(let E of t?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof E!="string"){let P=E,z=P?.context,M=P?.gpuDevice,V=P?.deviceType,R=P?.powerPreference;z?s.currentContext=z:M?s.currentContext=await s.webnnCreateMLContext(M):s.currentContext=await s.webnnCreateMLContext({deviceType:V,powerPreference:R})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&xe("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[f,_]=dh(a),g=!!t?.enableGraphCapture,w=[],v=[],x=[],b=[],k=[];for(let E=0;EE==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&xe("Can't create IO binding."),C={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>Fo(E))}),dr.set(a,[a,u,d,C,g,!1]),[a,w,v,x,b]}catch(f){throw u.forEach(_=>s._OrtFree(_)),d.forEach(_=>s._OrtFree(_)),i!==0&&s._OrtReleaseBinding(i)!==0&&xe("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&xe("Can't release session."),f}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&xe("Can't release session options."),l.forEach(f=>s._free(f)),s.unmountExternalData?.()}},ai=e=>{let t=Pe(),r=dr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&xe("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&xe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(n)!==0&&xe("Can't release session."),dr.delete(e)},po=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Pe(),l=i.PTR_SIZE,u=e[0],d=e[1],f=e[3],_=f,g,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let b=e[2].gpuBuffer;w=Yr(Ar(u),d);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=k(b,n)}}else if(f==="ml-tensor"){let b=e[2].mlTensor;w=Yr(Ar(u),d);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=k(n,b,Ar(u),d)}else{let b=e[2];if(Array.isArray(b)){w=l*b.length,g=i._malloc(w),r.push(g);for(let k=0;ki.setValue(x+C*l,k,l===4?"i32":"i64"));let b=i._OrtCreateTensor(Ar(u),g,w,x,d.length,Fo(_));b===0&&xe(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(b)}finally{i.stackRestore(v)}},oi=async(e,t,r,n,s,a)=>{let o=Pe(),i=o.PTR_SIZE,l=dr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],f=l[2],_=l[3],g=l[4],w=l[5],v=t.length,x=n.length,b=0,k=[],C=[],E=[],P=[],z=[],M=o.stackSave(),V=o.stackAlloc(v*i),R=o.stackAlloc(v*i),q=o.stackAlloc(x*i),K=o.stackAlloc(x*i);try{[b,k]=Rf(a),mr("wasm prepareInputOutputTensor");for(let $=0;$Se*ve,1);B=Ss(Te);let ct=_?.outputPreferredLocations[n[$]];if(B==="string"){if(ct==="gpu-buffer"||ct==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Se=[];for(let ve=0;ve0){let Se=o.webgpuGetBuffer;if(!Se)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Se(W),rt=Yr(Te,He);if(rt===void 0||!Zo(B))throw new Error(`Unsupported data type: ${B}`);N=!0;{o.webgpuRegisterBuffer(ve,e,W);let Me=o.webgpuCreateDownloader(ve,rt,e);O.push([B,Le,{gpuBuffer:ve,download:async()=>{let be=await Me();return new(Un(B))(be)},dispose:()=>{o._OrtReleaseTensor(H)!==0&&xe("Can't release tensor.")}},"gpu-buffer"])}}else if(ct==="ml-tensor"&&He>0){let Se=o.webnnEnsureTensor,ve=o.webnnIsGraphInputOutputTypeSupported;if(!Se||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Yr(Te,He)===void 0||!ei(B))throw new Error(`Unsupported data type: ${B}`);if(!ve(e,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Se(e,W,Te,Le,!1);N=!0,O.push([B,Le,{mlTensor:rt,download:o.webnnCreateMLTensorDownloader(W,B),dispose:()=>{o.webnnReleaseTensorId(W),o._OrtReleaseTensor(H)}},"ml-tensor"])}else if(ct==="ml-tensor-cpu-output"&&He>0){let Se=o.webnnCreateMLTensorDownloader(W,B)(),ve=O.length;N=!0,I.push((async()=>{let rt=[ve,await Se];return o.webnnReleaseTensorId(W),o._OrtReleaseTensor(H),rt})()),O.push([B,Le,[],"cpu"])}else{let Se=Un(B),ve=new Se(He);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(o.HEAPU8.subarray(W,W+ve.byteLength)),O.push([B,Le,ve,"cpu"])}}finally{o.stackRestore(ee),B==="string"&&W&&o._free(W),N||o._OrtReleaseTensor(H)}}_&&!g&&(o._OrtClearBoundOutputs(_.handle)!==0&&xe("Can't clear bound outputs."),dr.set(e,[u,d,f,_,g,!1]));for(let[$,H]of await Promise.all(I))O[$][2]=H;return gr("wasm ProcessOutputTensor"),O}finally{o.webnnOnRunEnd?.(u),o.stackRestore(M),r.forEach(Q=>{Q&&Q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(Q[2].gpuBuffer)}),s.forEach(Q=>{Q&&Q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(Q[2].gpuBuffer)}),C.forEach(Q=>o._OrtReleaseTensor(Q)),E.forEach(Q=>o._OrtReleaseTensor(Q)),P.forEach(Q=>o._free(Q)),b!==0&&o._OrtReleaseRunOptions(b),k.forEach(Q=>o._free(Q))}},ii=e=>{let t=Pe(),r=dr.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&xe("Can't get an profile file name."),t._OrtFree(s)},li=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),hr,yt,qr,Nn,Dn,vs,mo,ys,br,xr,hh,Xf,Yf,Jf,Kf,Zf,e_,t_,r_=me(()=>{Or(),Qf(),Nr(),Yo(),hr=()=>!!De.wasm.proxy&&typeof document<"u",qr=!1,Nn=!1,Dn=!1,ys=new Map,br=(e,t)=>{let r=ys.get(e);r?r.push(t):ys.set(e,[t])},xr=()=>{if(qr||!Nn||Dn||!yt)throw new Error("worker not ready")},hh=e=>{switch(e.data.type){case"init-wasm":qr=!1,e.data.err?(Dn=!0,mo[1](e.data.err)):(Nn=!0,mo[0]()),vs&&(URL.revokeObjectURL(vs),vs=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ys.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Xf=async()=>{if(!Nn){if(qr)throw new Error("multiple calls to 'initWasm()' detected.");if(Dn)throw new Error("previous call to 'initWasm()' failed.");if(qr=!0,hr())return new Promise((e,t)=>{yt?.terminate(),zf().then(([r,n])=>{try{yt=n,yt.onerror=a=>t(a),yt.onmessage=hh,mo=[e,t];let s={type:"init-wasm",in:De};!s.in.wasm.wasmPaths&&(r||Po)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",import.meta.url).href}),yt.postMessage(s),vs=r}catch(s){t(s)}},t)});try{await Jo(De.wasm),await ri(De),Nn=!0}catch(e){throw Dn=!0,e}finally{qr=!1}}},Yf=async e=>{if(hr())return xr(),new Promise((t,r)=>{br("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:De}};yt.postMessage(n)});await ni(De,e)},Jf=async e=>hr()?(xr(),new Promise((t,r)=>{br("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};yt.postMessage(n,[e.buffer])})):zs(e),Kf=async(e,t)=>{if(hr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xr(),new Promise((r,n)=>{br("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),yt.postMessage(s,a)})}else return si(e,t)},Zf=async e=>{if(hr())return xr(),new Promise((t,r)=>{br("release",[t,r]);let n={type:"release",in:e};yt.postMessage(n)});ai(e)},e_=async(e,t,r,n,s,a)=>{if(hr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return xr(),new Promise((o,i)=>{br("run",[o,i]);let l=r,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};yt.postMessage(u,li(l))})}else return oi(e,t,r,n,s,a)},t_=async e=>{if(hr())return xr(),new Promise((t,r)=>{br("end-profiling",[t,r]);let n={type:"end-profiling",in:e};yt.postMessage(n)});ii(e)}}),go,fh,n_,oM=me(()=>{Or(),r_(),an(),Xo(),$f(),go=(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()}`)}},fh=e=>{switch(e[3]){case"cpu":return new Ct(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Zo(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Ct.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!ei(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Ct.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},n_=class{async fetchModelAndCopyToWasmMemory(e){return Jf(await ti(e))}async loadModel(e,t){Lr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Kf(r,t),Ir()}async dispose(){return Zf(this.sessionId)}async run(e,t,r){Lr();let n=[],s=[];Object.entries(e).forEach(f=>{let _=f[0],g=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);n.push(g),s.push(w)});let a=[],o=[];Object.entries(t).forEach(f=>{let _=f[0],g=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(g),o.push(w)});let i=n.map((f,_)=>go(f,()=>`input "${this.inputNames[s[_]]}"`)),l=a.map((f,_)=>f?go(f,()=>`output "${this.outputNames[o[_]]}"`):null),u=await e_(this.sessionId,s,i,o,l,r),d={};for(let f=0;fOo,initializeFlags:()=>Io,wasmBackend:()=>a_});var Io,Oo,a_,iM=me(()=>{Or(),r_(),oM(),Io=()=>{(typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0);let e=De.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.`),De.wasm.simd=!1),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=!1),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=!1),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)De.wasm.numThreads=1;else{let t=typeof navigator>"u"?By("node:os").cpus().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Oo=class{async init(e){Io(),await Xf(),await Yf(e)}async createInferenceSessionHandler(e,t){let r=new n_;return await r.loadModel(e,t),r}},a_=new Oo});Or();Or();Or();var lM="1.26.0-dev.20260416-b7804b056c",cM=Ff;{let e=(iM(),Is(s_)).wasmBackend;Pr("webgpu",e,5),Pr("webnn",e,5),Pr("cpu",e,10),Pr("wasm",e,10)}Object.defineProperty(De.versions,"web",{value:lM,enumerable:!0});const uM=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Qo},get TRACE(){return Os},get TRACE_EVENT_BEGIN(){return mr},get TRACE_EVENT_END(){return gr},get TRACE_FUNC_BEGIN(){return Lr},get TRACE_FUNC_END(){return Ir},get Tensor(){return Ct},default:cM,get env(){return De},get registerBackend(){return Pr}},Symbol.toStringTag,{value:"Module"})),dM=(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 o=t?.format!==void 0?t.format:"RGB",i=t?.norm;let l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));const d=a*s;let f=0,_=d,g=d*2,w=-1;o==="RGBA"?(f=0,_=d,g=d*2,w=d*3):o==="RGB"?(f=0,_=d,g=d*2):o==="RBG"&&(f=0,g=d,_=d*2);for(let v=0;v{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm;let u,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let g=0,w=1,v=2,x=3,b=0,k=f,C=f*2,E=-1;i==="RGBA"?(b=0,k=f,C=f*2,E=f*3):i==="RGB"?(b=0,k=f,C=f*2):i==="RBG"&&(b=0,C=f,k=f*2),n=r.createImageData(s,a);for(let P=0;P{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,o;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"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=r*n,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let f=4,_=0,g=1,w=2,v=3,x=0,b=u,k=u*2,C=-1;i==="RGB"&&(f=3,_=0,g=1,w=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?(x=0,k=u,b=u*2):l==="BGR"&&(k=0,b=u,x=u*2);for(let P=0;P{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 o,i=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){const d=l();d.width=e.width,d.height=e.height;const f=u(d);if(f!=null){let _=e.height,g=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,g=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=g}else i.tensorFormat="RGBA",i.height=_,i.width=g;f.drawImage(e,0,0),o=f.getImageData(0,0,g,_).data}else throw new Error("Can not access image data")}else if(n){let d,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,f=t.resizedWidth):(d=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=f,t!==void 0){const _=l();_.width=f,_.height=d;const g=u(_);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,f,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const d=l();d.width=e.width,d.height=e.height;const f=u(d);if(f!=null){const _=e.height,g=e.width;return f.drawImage(e,0,0,g,_),o=f.getImageData(0,0,g,_).data,i.height=_,i.width=g,wo(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,f)=>{const _=l(),g=u(_);if(!e||!g)return f();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,g.drawImage(w,0,0,_.width,_.height);const v=g.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(wo(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return wo(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},_M=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new xt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},pM=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new xt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},mM=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new xt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},gM=(e,t,r)=>new xt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),Kr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ps=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let _h=!1;const wM=()=>{if(!_h){_h=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Kr.set("int64",BigInt64Array),Ps.set(BigInt64Array,"int64")),t&&(Kr.set("uint64",BigUint64Array),Ps.set(BigUint64Array,"uint64")),n?(Kr.set("float16",r),Ps.set(r,"float16")):Kr.set("float16",Uint16Array)}},vM=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new xt(e.type,e.data,t);case"cpu-pinned":return new xt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new xt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new xt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new xt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let xt=class{constructor(t,r,n){wM();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 i=Kr.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,l;if(typeof t=="string")if(s=t,l=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const u=Kr.get(t);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&u===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${u.name} as data.`);t==="uint64"||t==="int64"?i=u.from(r,BigInt):i=u.from(r)}else if(r instanceof u)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&u!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${u}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof t[0];if(u==="string")s="string",i=t;else if(u==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{const u=Ps.get(t.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=u,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}const o=vM(a);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=a,this.size=o}static async fromImage(t,r){return fM(t,r)}static fromTexture(t,r){return _M(t,r)}static fromGpuBuffer(t,r){return pM(t,r)}static fromMLTensor(t,r){return mM(t,r)}static fromPinnedBuffer(t,r,n){return gM(t,r,n)}toDataURL(t){return dM(this,t)}toImageData(t){return hM(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 yM(this,t)}};const MM=xt;var vo={},bM=Object.defineProperty,on=(e,t)=>{for(var r in t)bM(e,r,{get:t[r],enumerable:!0})},mt={},$t={},xM={},TM="4.2.0",ci=typeof self<"u",tn=!c_(mt),o_=!c_($t),Bs=ci&&"caches"in self,kM=typeof globalThis.Deno<"u",Hs=kM&&Bs&&!tn,i_=typeof process<"u",l_=i_&&process?.release?.name==="node"&&!Hs,ui=typeof window<"u"&&typeof window.document<"u",di=ci&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),EM=ui||di||Hs,CM=l_||typeof navigator<"u"&&"gpu"in navigator,AM=typeof navigator<"u"&&"ml"in navigator,SM=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",PM=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",FM=typeof ServiceWorkerGlobalScope<"u"&&ci&&self instanceof ServiceWorkerGlobalScope,LM=()=>{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},IM=LM(),ue=Object.freeze({IS_BROWSER_ENV:ui,IS_WEBWORKER_ENV:di,IS_WEB_ENV:EM,IS_SERVICE_WORKER_ENV:FM,IS_DENO_WEB_RUNTIME:Hs,IS_WEB_CACHE_AVAILABLE:Bs,IS_WEBGPU_AVAILABLE:CM,IS_WEBNN_AVAILABLE:AM,IS_SAFARI:IM,IS_PROCESS_AVAILABLE:i_,IS_NODE_ENV:l_,IS_FS_AVAILABLE:tn,IS_PATH_AVAILABLE:o_,IS_CRYPTO_AVAILABLE:SM,IS_CHROME_AVAILABLE:PM}),hi=tn&&o_,Rs="./";if(hi){const e=Object(import.meta).url;e?Rs=$t.dirname($t.dirname(xM.fileURLToPath(e))):typeof __dirname<"u"&&(Rs=$t.dirname(__dirname))}var OM=hi?$t.join(Rs,"/.cache/"):null,ph="/models/",NM=hi?$t.join(Rs,ph):ph,DM=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,At=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),mh=At.WARNING,pe={version:TM,backends:{onnx:{}},get logLevel(){return mh},set logLevel(e){mh=e,pe.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(ui||di||Hs),localModelPath:NM,useFS:tn,useBrowserCache:Bs,useFSCache:tn,cacheDir:OM,useCustomCache:!1,customCache:null,useWasmCache:Bs||tn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:DM};function c_(e){return Object.keys(e).length===0}var gt=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 Sr(e,t){e&&e(t)}var gh=class extends gt{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 zM(e){return Number.isInteger(e)||typeof e=="bigint"}function wh(e){return e==null||e===-1}function vh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Vt(...e){return Array.prototype.concat.apply([],e)}function Gs(e,t){return Math.abs((e+t)%(2*t)-t)}function Ze(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function BM(e,t){let r=0;for(const n of e)n===t&&++r;return r}var de={error(...e){pe.logLevel<=At.ERROR&&console.error(...e)},warn(...e){pe.logLevel<=At.WARNING&&console.warn(...e)},info(...e){pe.logLevel<=At.INFO&&console.log(...e)},debug(...e){pe.logLevel<=At.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},RM=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(o),s+=o.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]]))})(),VM=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),UM=VM(u_),Mh=".,!?…。,、।۔،",jM=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|[${Mh}])]+`,` ?[^\\s${Mh}]+`]]),$s="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",fi=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"),Qs=(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 jM)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,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return s=!0,`${i}{Script=${l}}`}});if(!s)throw n;try{return new RegExp(a,"gu")}catch{throw n}}}else if(e.String!==void 0){const r=qM(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},qM=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),WM=(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,QM=e=>Number.isInteger(e)||typeof e=="bigint",XM=e=>{let t=0;for(const r of e)++t;return t},YM=e=>d_(e.toLowerCase()),St=(...e)=>Array.prototype.concat.apply([],e),_i=e=>new Map(Object.entries(e)),JM=(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,""),bh=(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},KM=e=>e.match(/\S+/g)||[],ZM=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Hn=ZM,eb=class extends Hn{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},nr=eb,tb=class extends nr{tokenize_chinese_chars(e){const t=[];for(let r=0;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},sb=nb,ab=class extends nr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>h_(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},ob=ab,ib=class extends nr{normalize(e){const t=Qs(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},lb=ib,cb=class extends nr{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Xs=cb,ub=class extends Xs{constructor(){super(...arguments),this.form="NFC"}},db=ub,hb=class extends Xs{constructor(){super(...arguments),this.form="NFD"}},fb=hb,_b=class extends Xs{constructor(){super(...arguments),this.form="NFKC"}},pb=_b,mb=class extends Xs{constructor(){super(...arguments),this.form="NFKD"}},gb=mb,wb=class extends nr{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}},vb=wb,yb=class extends nr{normalize(e){return d_(e)}},Mb=yb,bb=class extends nr{normalize(e){return e.toLowerCase()}},xb=bb,Tb=class extends nr{normalize(e){return e=this.config.prepend+e,e}},kb=Tb;function Eb(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new rb(e);case"Precompiled":return new sb(e);case"Sequence":return new ob(e);case"Replace":return new lb(e);case"NFC":return new db(e);case"NFD":return new fb(e);case"NFKC":return new pb(e);case"NFKD":return new gb(e);case"Strip":return new vb(e);case"StripAccents":return new Mb(e);case"Lowercase":return new xb(e);case"Prepend":return new kb(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var h_=Eb,Cb=class extends Hn{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)}},Ft=Cb,Ab=class extends Ft{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=u_,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(""))}},Sb=Ab,Pb=class extends Ft{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Fb=Pb,Lb=class extends Ft{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]}},Ib=Lb,Ob=class extends Ft{constructor(e){super(),this.config=e,this.pattern=Qs(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):JM(e,this.pattern)}},Nb=Ob,Db=class extends Ft{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${$s}]+|[${$s}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},zb=Db,Bb=class extends Ft{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)||[]}},Rb=Bb,Gb=class extends Ft{constructor(){super(),this.pattern=new RegExp(`[^\\s${$s}]+|[${$s}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},$b=Gb,Vb=class extends Ft{constructor(e){super(),this.config=e,this.pattern=Qs(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},Ub=Vb,jb=class extends Ft{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>f_(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},qb=jb,Wb=class extends Ft{pre_tokenize_text(e){return KM(e)}},Hb=Wb,Qb=class extends Ft{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 o=[];for(;a0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},xh=Kb,Th=class __{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new __(!1,new Map)}},Zb=class{constructor(){this.root=Th.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=Th.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)}}},e0=Zb,yo=class p_{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 p_(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},t0=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 yo(this.bos_token_id??0,0,0,0,0),s=new yo(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 yo(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 o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let u of this.end_nodes[t]){const d=u.backtrace_score+o.score;(l===null||d>i)&&(l=u.clone(),i=d)}if(l!==null)o.prev=l,o.backtrace_score=i;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)}},r0=t0;function n0(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=n0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new e0,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()}},l0=i0,c0=class extends Ys{constructor(e){super(e),this.tokens_to_ids=_i(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 l0(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 o0((i,l)=>i.score`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Eh=c0,u0=class extends Ys{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=_i(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}},d0=u0;function h0(e,t){switch(e.type){case"WordPiece":return new xh(e);case"Unigram":return new kh(e,t.eos_token);case"BPE":return new Eh(e);default:if(e.vocab)return Array.isArray(e.vocab)?new kh(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Eh(e):new xh(e):new d0(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 f0=h0,_0=class extends Hn{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Qn=_0,p0=class extends Qn{post_process(e,t=null,r=!0){const n=t===null?this.config.single:this.config.pair;let s=[],a=[];for(const o of n)"SpecialToken"in o?r&&(s.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(s=St(s,e),a=St(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=St(s,t),a=St(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},m0=p0,g0=class extends Qn{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},w0=g0,v0=class extends Qn{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=St([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=St(e,s,t,a),n=St(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},y0=v0,M0=class extends Qn{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=St([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=St(e,s,t,a),n=St(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},b0=M0,x0=class extends Qn{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>m_(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}},T0=x0;function k0(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new m0(e);case"ByteLevel":return new w0(e);case"BertProcessing":return new y0(e);case"RobertaProcessing":return new b0(e);case"Sequence":return new T0(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var m_=k0,E0=class extends Hn{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("")}},Lt=E0,C0=class extends Lt{constructor(e){super(e),this.byte_decoder=UM,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}},A0=C0,S0=class extends Lt{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=fi(t)),t})}},P0=S0,F0=class extends Lt{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?"":" "))}},O0=I0,N0=class extends Lt{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=fi(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},D0=N0,z0=class extends Lt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>g_(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},B0=z0,R0=class extends Lt{decode_chain(e){const t=Qs(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},G0=R0,$0=class extends Lt{decode_chain(e){return[e.join("")]}},V0=$0,U0=class extends Lt{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}},W0=q0;function H0(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new A0(e);case"WordPiece":return new P0(e);case"Metaspace":return new L0(e);case"BPEDecoder":return new O0(e);case"CTC":return new D0(e);case"Sequence":return new B0(e);case"Replace":return new G0(e);case"Fuse":return new V0(e);case"Strip":return new j0(e);case"ByteFallback":return new W0(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var g_=H0,Q0=class{constructor(e,t){const r=bh(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=bh(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=h_(this.tokenizer.normalizer),this.pre_tokenizer=f_(this.tokenizer.pre_tokenizer),this.model=f0(this.tokenizer.model,this.config),this.post_processor=m_(this.tokenizer.post_processor),this.decoder=g_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const s=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new $M(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else s.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 yh(s),this.splitter_normalized=new yh(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}),o=s.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:s,attention_mask:new Array(o.length).fill(1)};return n&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!QM(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=fi(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=YM(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const s=this.splitter_normalized.split(r);return s.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(s[o-1]=s[o-1].trimEnd()),i.rstrip&&o{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:n}):[a];return this.model(o)})})}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:St(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=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],J0=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function K0(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 Z0(e,t={}){const r=[],n=K0(e,t);let s=0,a=0;const o=u=>{let d="";for(;u(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const f=n[s++],_=J0.get(f);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);d+=_;continue}if(d+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{const u=r.at(-1);u&&u.type===D.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;s0){r.push(new Mt(f,D.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const f=n[s]==="-";f&&++s;let _="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");_+=n[s++]}const g=_.endsWith("-");g&&(_=_.slice(0,-1)),f&&i(),r.push(new Mt(_,D.Comment)),s+=2,g&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new Mt("{%",D.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new Mt("{{",D.OpenExpression)),a=0,s+=3;continue}if(o(Ah),n.slice(s,s+3)==="-%}"){r.push(new Mt("%}",D.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Mt("}}",D.CloseExpression)),s+=3,l();continue}const d=n[s];if(d==="-"||d==="+"){const f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++s;const _=o(zn);r.push(new Mt(`${d}${_}`,_.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(const[f,_]of Y0){if(f==="}}"&&a>0)continue;if(n.slice(s,s+f.length)===f){r.push(new Mt(f,_)),_===D.OpenExpression?a=0:_===D.OpenCurlyBracket?++a:_===D.CloseCurlyBracket&&--a,s+=f.length;continue e}}if(d==="'"||d==='"'){++s;const f=o(_=>_!==d);r.push(new Mt(f,D.StringLiteral)),++s;continue}if(zn(d)){let f=o(zn);if(n[s]==="."&&zn(n[s+1])){++s;const _=o(zn);f=`${f}.${_}`}r.push(new Mt(f,D.NumericLiteral));continue}if(Ch(d)){const f=o(Ch);r.push(new Mt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var It=class{type="Statement"},ex=class extends It{constructor(e){super(),this.body=e}type="Program"},tx=class extends It{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},rx=class extends It{constructor(e,t,r,n){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},nx=class extends It{type="Break"},sx=class extends It{type="Continue"},ax=class extends It{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},ox=class extends It{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},ix=class extends It{constructor(e){super(),this.value=e}type="Comment"},wt=class extends It{type="Expression"},lx=class extends wt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},Sh=class extends wt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},Wr=class extends wt{constructor(e){super(),this.value=e}type="Identifier"},ln=class extends wt{constructor(e){super(),this.value=e}type="Literal"},cx=class extends ln{type="IntegerLiteral"},ux=class extends ln{type="FloatLiteral"},Ph=class extends ln{type="StringLiteral"},dx=class extends ln{type="ArrayLiteral"},Fh=class extends ln{type="TupleLiteral"},hx=class extends ln{type="ObjectLiteral"},Bn=class extends wt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},fx=class extends wt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},_x=class extends It{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},px=class extends wt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},mx=class extends wt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},gx=class extends wt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},wx=class extends wt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},vx=class extends wt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},yx=class extends wt{constructor(e){super(),this.argument=e}type="SpreadExpression"},Mx=class extends It{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},bx=class extends wt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function xx(e){const t=new ex([]);let r=0;function n(L,N){const B=e[r++];if(!B||B.type!==L)throw new Error(`Parser Error: ${N}. ${B.type} !== ${L}.`);return B}function s(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function a(){switch(e[r].type){case D.Comment:return new ix(e[r++].value);case D.Text:return u();case D.OpenStatement:return d();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...L){return r+L.length<=e.length&&L.every((N,B)=>N===e[r+B].type)}function i(...L){return e[r]?.type===D.OpenStatement&&e[r+1]?.type===D.Identifier&&L.includes(e[r+1]?.value)}function l(...L){return r+L.length<=e.length&&L.every((N,B)=>e[r+B].type==="Identifier"&&N===e[r+B].value)}function u(){return new Ph(n(D.Text,"Expected text token").value)}function d(){if(n(D.OpenStatement,"Expected opening statement token"),e[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const L=e[r].value;let N;switch(L){case"set":++r,N=_();break;case"if":++r,N=g(),n(D.OpenStatement,"Expected {% token"),s("endif"),n(D.CloseStatement,"Expected %} token");break;case"macro":++r,N=w(),n(D.OpenStatement,"Expected {% token"),s("endmacro"),n(D.CloseStatement,"Expected %} token");break;case"for":++r,N=x(),n(D.OpenStatement,"Expected {% token"),s("endfor"),n(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;o(D.OpenParen)&&(B=q());const W=ee();if(W.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const he=q();n(D.CloseStatement,"Expected closing statement token");const Te=[];for(;!i("endcall");)Te.push(a());n(D.OpenStatement,"Expected '{%'"),s("endcall"),n(D.CloseStatement,"Expected closing statement token");const oe=new Sh(W,he);N=new Mx(oe,B,Te);break}case"break":++r,n(D.CloseStatement,"Expected closing statement token"),N=new nx;break;case"continue":++r,n(D.CloseStatement,"Expected closing statement token"),N=new sx;break;case"filter":{++r;let B=ee();B instanceof Wr&&o(D.OpenParen)&&(B=R(B)),n(D.CloseStatement,"Expected closing statement token");const W=[];for(;!i("endfilter");)W.push(a());n(D.OpenStatement,"Expected '{%'"),s("endfilter"),n(D.CloseStatement,"Expected '%}'"),N=new _x(B,W);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return N}function f(){n(D.OpenExpression,"Expected opening expression token");const L=b();return n(D.CloseExpression,"Expected closing expression token"),L}function _(){const L=v();let N=null;const B=[];if(o(D.Equals))++r,N=v();else{for(n(D.CloseStatement,"Expected %} token");!i("endset");)B.push(a());n(D.OpenStatement,"Expected {% token"),s("endset")}return n(D.CloseStatement,"Expected closing statement token"),new ax(L,N,B)}function g(){const L=b();n(D.CloseStatement,"Expected closing statement token");const N=[],B=[];for(;!i("elif","else","endif");)N.push(a());if(i("elif")){++r,++r;const W=g();B.push(W)}else if(i("else"))for(++r,++r,n(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(a());return new tx(L,N,B)}function w(){const L=ee();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const N=q();n(D.CloseStatement,"Expected closing statement token");const B=[];for(;!i("endmacro");)B.push(a());return new ox(L,N,B)}function v(L=!1){const N=L?ee:b,B=[N()],W=o(D.Comma);for(;W&&(++r,B.push(N()),!!o(D.Comma)););return W?new Fh(B):B[0]}function x(){const L=v(!0);if(!(L instanceof Wr||L instanceof Fh))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const N=b();n(D.CloseStatement,"Expected closing statement token");const B=[];for(;!i("endfor","else");)B.push(a());const W=[];if(i("else"))for(++r,++r,n(D.CloseStatement,"Expected closing statement token");!i("endfor");)W.push(a());return new rx(L,N,B,W)}function b(){return k()}function k(){const L=C();if(l("if")){++r;const N=C();if(l("else")){++r;const B=k();return new bx(N,L,B)}else return new px(L,N)}return L}function C(){let L=E();for(;l("or");){const N=e[r];++r;const B=E();L=new Bn(N,L,B)}return L}function E(){let L=P();for(;l("and");){const N=e[r];++r;const B=P();L=new Bn(N,L,B)}return L}function P(){let L;for(;l("not");){const N=e[r];++r;const B=P();L=new gx(N,B)}return L??z()}function z(){let L=M();for(;;){let N;if(l("not","in"))N=new Mt("not in",D.Identifier),r+=2;else if(l("in"))N=e[r++];else if(o(D.ComparisonBinaryOperator))N=e[r++];else break;const B=M();L=new Bn(N,L,B)}return L}function M(){let L=I();for(;o(D.AdditiveBinaryOperator);){const N=e[r];++r;const B=I();L=new Bn(N,L,B)}return L}function V(){const L=O(ee());return o(D.OpenParen)?R(L):L}function R(L){let N=new Sh(L,q());return N=O(N),o(D.OpenParen)&&(N=R(N)),N}function q(){n(D.OpenParen,"Expected opening parenthesis for arguments list");const L=K();return n(D.CloseParen,"Expected closing parenthesis for arguments list"),L}function K(){const L=[];for(;!o(D.CloseParen);){let N;if(e[r].type===D.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const B=b();N=new yx(B)}else if(N=b(),o(D.Equals)){if(++r,!(N instanceof Wr))throw new SyntaxError("Expected identifier for keyword argument");const B=b();N=new vx(N,B)}L.push(N),o(D.Comma)&&++r}return L}function Q(){const L=[];let N=!1;for(;!o(D.CloseSquareBracket);)o(D.Colon)?(L.push(void 0),++r,N=!0):(L.push(b()),o(D.Colon)&&(++r,N=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new wx(...L)}return L[0]}function O(L){for(;o(D.Dot)||o(D.OpenSquareBracket);){const N=e[r];++r;let B;const W=N.type===D.OpenSquareBracket;if(W)B=Q(),n(D.CloseSquareBracket,"Expected closing square bracket");else if(B=ee(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new lx(L,B,W)}return L}function I(){let L=$();for(;o(D.MultiplicativeBinaryOperator);){const N=e[r++],B=$();L=new Bn(N,L,B)}return L}function $(){let L=H();for(;l("is");){++r;const N=l("not");N&&++r;const B=ee();if(!(B instanceof Wr))throw new SyntaxError("Expected identifier for the test");L=new mx(L,N,B)}return L}function H(){let L=V();for(;o(D.Pipe);){++r;let N=ee();if(!(N instanceof Wr))throw new SyntaxError("Expected identifier for the filter");o(D.OpenParen)&&(N=R(N)),L=new fx(L,N)}return L}function ee(){const L=e[r++];switch(L.type){case D.NumericLiteral:{const N=L.value;return N.includes(".")?new ux(Number(N)):new cx(Number(N))}case D.StringLiteral:{let N=L.value;for(;o(D.StringLiteral);)N+=e[r++].value;return new Ph(N)}case D.Identifier:return new Wr(L.value);case D.OpenParen:{const N=v();return n(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case D.OpenSquareBracket:{const N=[];for(;!o(D.CloseSquareBracket);)N.push(b()),o(D.Comma)&&++r;return++r,new dx(N)}case D.OpenCurlyBracket:{const N=new Map;for(;!o(D.CloseCurlyBracket);){const B=b();n(D.Colon,"Expected colon between key and value in object literal");const W=b();N.set(B,W),o(D.Comma)&&++r}return++r,new hx(N)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let s=e;st;s+=r)n.push(s);return n}function Lh(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 o=t;s*ot.toUpperCase())}function Ex(e){return Cx(new Date,e)}function Cx(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 Ax(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Sx(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(Ax(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var Ih=class extends Error{},Oh=class extends Error{},qt=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new se(!!this.value)}toString(){return String(this.value)}},le=class extends qt{type="IntegerValue"},Re=class extends qt{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},J=class extends qt{type="StringValue";builtins=new Map([["upper",new Oe(()=>new J(this.value.toUpperCase()))],["lower",new Oe(()=>new J(this.value.toLowerCase()))],["strip",new Oe(()=>new J(this.value.trim()))],["title",new Oe(()=>new J(kx(this.value)))],["capitalize",new Oe(()=>new J(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new le(this.value.length)],["rstrip",new Oe(()=>new J(this.value.trimEnd()))],["lstrip",new Oe(()=>new J(this.value.trimStart()))],["startswith",new Oe(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof J)return new se(this.value.startsWith(t.value));if(t instanceof _e){for(const r of t.value){if(!(r instanceof J))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new se(!0)}return new se(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Oe(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof J)return new se(this.value.endsWith(t.value));if(t instanceof _e){for(const r of t.value){if(!(r instanceof J))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new se(!0)}return new se(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Oe(e=>{const t=e[0]??new ze;if(!(t instanceof J||t instanceof ze))throw new Error("sep argument must be a string or null");const r=e[1]??new le(-1);if(!(r instanceof le))throw new Error("maxsplit argument must be a number");let n=[];if(t instanceof ze){const s=this.value.trimStart();for(const{0:a,index:o}of s.matchAll(/\S+/g)){if(r.value!==-1&&n.length>=r.value&&o!==void 0){n.push(a+s.slice(o+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 _e(n.map(s=>new J(s)))})],["replace",new Oe(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],r=e[1];if(!(t instanceof J&&r instanceof J))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 ze:n=e[2]:n=new ze,!(n instanceof le||n instanceof ze))throw new Error("replace() count argument must be a number or null");return new J(Sx(this.value,t.value,r.value,n.value))})]])},se=class extends qt{type="BooleanValue"},Px=/[\x7f-\uffff]/g;function Nh(e){return e.replace(Px,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Fr(e,t={},r=0,n=!0){const{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,u;switch(o?[l,u]=o:s?(l=",",u=": "):(l=", ",u=": "),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 d=JSON.stringify(e.value);return a&&(d=Nh(d)),d}case"ArrayValue":case"ObjectValue":{const d=s?" ".repeat(s):"",f=` +`+d.repeat(r),_=f+d;if(e.type==="ArrayValue"){const g=e.value.map(w=>Fr(w,t,r+1,n));return s?`[${_}${g.join(`${l}${_}`)}${f}]`:`[${g.join(l)}]`}else{let g=Array.from(e.value.entries());i&&(g=g.sort(([v],[x])=>v.localeCompare(x)));const w=g.map(([v,x])=>{let b=JSON.stringify(v);a&&(b=Nh(b));const k=`${b}${u}${Fr(x,t,r+1,n)}`;return s?`${_}${k}`:k});return s?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var Ye=class extends qt{type="ObjectValue";__bool__(){return new se(this.value.size>0)}builtins=new Map([["get",new Oe(([e,t])=>{if(!(e instanceof J))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new ze})],["items",new Oe(()=>this.items())],["keys",new Oe(()=>this.keys())],["values",new Oe(()=>this.values())],["dictsort",new Oe(e=>{let t=new Map;const r=e.filter(i=>i instanceof Gn?(t=i.value,!1):!0),n=r.at(0)??t.get("case_sensitive")??new se(!1);if(!(n instanceof se))throw new Error("case_sensitive must be a boolean");const s=r.at(1)??t.get("by")??new J("key");if(!(s instanceof J))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 se(!1);if(!(a instanceof se))throw new Error("reverse must be a boolean");const o=Array.from(this.value.entries()).map(([i,l])=>new _e([new J(i),l])).sort((i,l)=>{const u=s.value==="key"?0:1,d=i.value[u],f=l.value[u],_=No(d,f,n.value);return a.value?-_:_});return new _e(o)})]]);items(){return new _e(Array.from(this.value.entries()).map(([e,t])=>new _e([new J(e),t])))}keys(){return new _e(Array.from(this.value.keys()).map(e=>new J(e)))}values(){return new _e(Array.from(this.value.values()))}toString(){return Fr(this,{},0,!1)}},Gn=class extends Ye{type="KeywordArgumentsValue"},_e=class extends qt{type="ArrayValue";builtins=new Map([["length",new le(this.value.length)]]);__bool__(){return new se(this.value.length>0)}toString(){return Fr(this,{},0,!1)}},Dh=class extends _e{type="TupleValue"},Oe=class extends qt{type="FunctionValue"},ze=class extends qt{type="NullValue"},Ie=class extends qt{type="UndefinedValue"},kr=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Oe(e=>{if(e.length===0)return new Ye(new Map);if(e.length!==1||!(e[0]instanceof Ye))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 Oe],["odd",e=>{if(!(e instanceof le))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof le))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 le||e instanceof Re],["integer",e=>e instanceof le],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof Ye],["sequence",e=>e instanceof _e||e instanceof Ye||e instanceof J],["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,Fs(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 Ie}catch{return new Ie}}};function Fx(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",Tx),e.set("strftime_now",Ex),e.set("True",!0),e.set("False",!1),e.set("None",null)}function zh(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof Ye)n=n.value.get(s)??new Ie;else if(n instanceof _e){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&aa instanceof le||a instanceof Re||a instanceof se,s=a=>a instanceof se?a.value?1:0:a.value;if(n(e)&&n(t)){const a=s(e),o=s(t);return ao?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type==="StringValue"){let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),ao?1:0}else throw new Error(`Cannot compare type: ${e.type}`)}var Lx=class{global;constructor(e){this.global=e??new kr}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 se(r.value==n.value);case"!=":return new se(r.value!=n.value)}if(r instanceof Ie||n instanceof Ie){if(n instanceof Ie&&["in","not in"].includes(e.operator.value))return new se(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof ze||n instanceof ze)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new J(r.value.toString()+n.value.toString());if((r instanceof le||r instanceof Re)&&(n instanceof le||n instanceof Re)){const s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof Re||n instanceof Re?new Re(o):new le(o)}case"/":return new Re(s/a);case"%":{const o=s%a;return r instanceof Re||n instanceof Re?new Re(o):new le(o)}case"<":return new se(s":return new se(s>a);case">=":return new se(s>=a);case"<=":return new se(s<=a)}}else if(r instanceof _e&&n instanceof _e){if(e.operator.value==="+")return new _e(r.value.concat(n.value))}else if(n instanceof _e){const s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new se(s);case"not in":return new se(!s)}}}if((r instanceof J||n instanceof J)&&e.operator.value==="+")return new J(r.value.toString()+n.value.toString());if(r instanceof J&&n instanceof J)switch(e.operator.value){case"in":return new se(n.value.includes(r.value));case"not in":return new se(!n.value.includes(r.value))}if(r instanceof J&&n instanceof Ye)switch(e.operator.value){case"in":return new se(n.value.has(r.value));case"not in":return new se(!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,o=this.evaluate(a.argument,t);if(!(o instanceof _e))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}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 J(Fr(e,{}));if(e instanceof _e)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 le(e.value.length);case"reverse":return new _e(e.value.slice().reverse());case"sort":return new _e(e.value.slice().sort((s,a)=>No(s,a,!1)));case"join":return new J(e.value.map(s=>s.value).join(""));case"string":return new J(Fr(e,{},0,!1));case"unique":{const s=new Set,a=[];for(const o of e.value)s.has(o.value)||(s.add(o.value),a.push(o));return new _e(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof J)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const s=e.builtins.get(n.value);if(s instanceof Oe)return s.value([],r);if(s instanceof le)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new J(e.value.trim());case"indent":return new J(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 le(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new Re(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof le||e instanceof Re)switch(n.value){case"abs":return e instanceof le?new le(Math.abs(e.value)):new Re(Math.abs(e.value));case"int":return new le(Math.floor(e.value));case"float":return new Re(e.value);case"string":return new J(e.toString());default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof Ye)switch(n.value){case"items":return new _e(Array.from(e.value.entries()).map(([s,a])=>new _e([new J(s),a])));case"length":return new le(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof Oe?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof se)switch(n.value){case"bool":return new se(e.value);case"int":return new le(e.value?1:0);case"float":return new Re(e.value?1:0);case"string":return new J(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),o=a.get("indent")??new ze;if(!(o instanceof le||o instanceof ze))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new se(!1);if(!(i instanceof se))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new se(!1);if(!(l instanceof se))throw new Error("If set, sort_keys must be a boolean");const u=a.get("separators")??new ze;let d=null;if(u instanceof _e||u instanceof Dh){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");const[f,_]=u.value;if(!(f instanceof J)||!(_ instanceof J))throw new Error("separators must be a tuple of two strings");d=[f.value,_.value]}else if(!(u instanceof ze))throw new Error("If set, separators must be a tuple of two strings");return new J(Fr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(s==="join"){let a;if(e instanceof J)a=Array.from(e.value);else if(e instanceof _e)a=e.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(n.args,r),l=o.at(0)??i.get("separator")??new J("");if(!(l instanceof J))throw new Error("separator must be a string");return new J(a.join(l.value))}else if(s==="int"||s==="float"){const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("default")??(s==="int"?new le(0):new Re(0));if(e instanceof J){const l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new le(l):new Re(l)}else{if(e instanceof le||e instanceof Re)return e;if(e instanceof se)return s==="int"?new le(e.value?1:0):new Re(e.value?1:0);throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}}else if(s==="default"){const[a,o]=this.evaluateArguments(n.args,r),i=a[0]??new J(""),l=a[1]??o.get("boolean")??new se(!1);if(!(l instanceof se))throw new Error("`default` filter flag must be a boolean");return e instanceof Ie||l.value&&!e.__bool__().value?i:e}if(e instanceof _e){switch(s){case"sort":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new se(!1);if(!(i instanceof se))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new se(!1);if(!(l instanceof se))throw new Error("case_sensitive must be a boolean");const u=a.at(2)??o.get("attribute")??new ze;if(!(u instanceof J||u instanceof le||u instanceof ze))throw new Error("attribute must be a string, integer, or null");const d=f=>{if(u instanceof ze)return f;const _=u instanceof le?String(u.value):u.value;return zh(f,_)};return new _e(e.value.slice().sort((f,_)=>{const g=d(f),w=d(_),v=No(g,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(f=>!(f instanceof Ye)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[o,i,l]=n.args.map(f=>this.evaluate(f,r));let u;if(i){const f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;const d=e.value.filter(f=>{const _=f.value.get(o.value),g=_?u(_,l):!1;return a?g:!g});return new _e(d)}case"map":{const[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof J))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(u=>{if(!(u instanceof Ye))throw new Error("items in map must be an object");const d=zh(u,o.value);return d instanceof Ie?i??new Ie:d});return new _e(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof J){switch(s){case"indent":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new le(4);if(!(i instanceof le))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new se(!1),u=a.at(2)??o.get("blank")??new se(!1),d=e.value.split(` +`),f=" ".repeat(i.value),_=d.map((g,w)=>!l.value&&w===0||!u.value&&g.length===0?g:f+g);return new J(_.join(` +`))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Oe))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new Gn(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof Ye){const a=e.builtins.get(s);if(a&&a instanceof Oe){const[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new Gn(i)),a.value(o,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 se(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ie}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);if(e.operator.value==="not")return new se(!r.value);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 J(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 Gn(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 _e||e instanceof J))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 le||n instanceof Ie))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof le||s instanceof Ie))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof le||a instanceof Ie))throw new Error("Slice step must be numeric or undefined");return e instanceof _e?new _e(Lh(e.value,n.value,s.value,a.value)):new J(Lh(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 J(e.property.value);let s;if(r instanceof Ye){if(!(n instanceof J))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 _e||r instanceof J)if(n instanceof le)s=r.value.at(n.value),r instanceof J&&(s=new J(r.value.at(n.value)));else if(n instanceof J)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 J))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof qt?s:new Ie}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 _e))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;ag.setVariable(e.loopvar.value,f);else if(e.loopvar.type==="TupleLiteral"){const g=e.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);const w=f;if(g.value.length!==w.value.length)throw new Error(`Too ${g.value.length>w.value.length?"few":"many"} items to unpack`);_=v=>{for(let x=0;x0?a[u-1]:new Ie],["nextitem",u{const s=new kr(n);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let o=0;o{const u=new kr(l);if(e.callerArgs)for(let d=0;dthis.evaluate(r,t)));case"TupleLiteral":return new Dh(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 J))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new Ye(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 ze;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Fs(e){switch(typeof e){case"number":return Number.isInteger(e)?new le(e):new Re(e);case"string":return new J(e);case"boolean":return new se(e);case"undefined":return new Ie;case"object":return e===null?new ze:Array.isArray(e)?new _e(e.map(Fs)):new Ye(new Map(Object.entries(e).map(([t,r])=>[t,Fs(r)])));case"function":return new Oe((t,r)=>{const n=e(...t.map(s=>s.value))??null;return Fs(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Ue=` +`,Ix="{%- ",Ox=" -%}";function Nx(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 Dx(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Pt(e.body,0,r).replace(/\n$/,"")}function et(...e){return Ix+e.join(" ")+Ox}function Pt(e,t,r){return e.map(n=>zx(n,t,r)).join(Ue)}function zx(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return Pt(e.body,t,r);case"If":return Bx(e,t,r);case"For":return Rx(e,t,r);case"Set":return Gx(e,t,r);case"Macro":return $x(e,t,r);case"Break":return n+et("break");case"Continue":return n+et("continue");case"CallStatement":return Vx(e,t,r);case"FilterStatement":return Ux(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+we(e)+" -}}"}}function Bx(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 o=n+et("if",we(s[0].test))+Ue+Pt(s[0].body,t+1,r);for(let i=1;i0&&(o+=Ue+n+et("else")+Ue+Pt(a.alternate,t+1,r)),o+=Ue+n+et("endif"),o}function Rx(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;s=`${we(o.lhs)} if ${we(o.test)}`}else s=we(e.iterable);let a=n+et("for",we(e.loopvar),"in",s)+Ue+Pt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Ue+n+et("else")+Ue+Pt(e.defaultBlock,t+1,r)),a+=Ue+n+et("endfor"),a}function Gx(e,t,r){const n=r.repeat(t),s=we(e.assignee),a=e.value?we(e.value):"",o=n+et("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Ue+Pt(e.body,t+1,r)+Ue+n+et("endset")}function $x(e,t,r){const n=r.repeat(t),s=e.args.map(we).join(", ");return n+et("macro",`${e.name.value}(${s})`)+Ue+Pt(e.body,t+1,r)+Ue+n+et("endmacro")}function Vx(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(we).join(", ")})`:"",a=we(e.call);let o=n+et(`call${s}`,a)+Ue;return o+=Pt(e.body,t+1,r)+Ue,o+=n+et("endcall"),o}function Ux(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:we(e.filter);let a=n+et("filter",s)+Ue;return a+=Pt(e.body,t+1,r)+Ue,a+=n+et("endfilter"),a}function we(e,t=-1){switch(e.type){case"SpreadExpression":return`*${we(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=Nx(r),s=we(r.left,n),a=we(r.right,n+1),o=`${s} ${r.operator.value} ${a}`;return n`${we(n)}: ${we(s)}`).join(", ")}}`;case"SliceExpression":{const r=e,n=r.start?we(r.start):"",s=r.stop?we(r.stop):"",a=r.step?`:${we(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${we(r.value)}`}case"Ternary":{const r=e,n=`${we(r.trueExpr)} if ${we(r.condition,0)} else ${we(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}var jx=class{parsed;constructor(e){const t=Z0(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=xx(t)}render(e){const t=new kr;if(Fx(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new Lx(t).run(this.parsed).value}format(e){return Dx(this.parsed,e?.indent||" ")}},qx={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"},Vs=class w_{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=mt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=mt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=mt.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",qx[t]??"application/octet-stream")}clone(){let t=new w_(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 mt.promises.readFile(this.filePath)).buffer}async blob(){const t=await mt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await mt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Js=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(ue.IS_CRYPTO_AVAILABLE){const o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;const t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,n=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))n.push(o&4294967295);n.length||n.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let s=1,a=0;for(let o=Math.max(624,n.length);o>0;--o,++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 o=623;o>0;--o,++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[v_(this._random_fn,t)]}};function v_(e,t){let r=0;for(let s=0;sv_(pi.random,e),Hx=new Js,y_=class{constructor(e){this.path=e}async match(e){let t=$t.join(this.path,e),r=new Vs(t);if(r.exists)return r}async put(e,t,r=void 0){const n=$t.join(this.path,e),s=ue.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Hx._int32().toString(36),o=n+`.tmp.${s}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let u=0;await mt.promises.mkdir($t.dirname(n),{recursive:!0});const d=mt.createWriteStream(o),f=t.body.getReader();for(;;){const{done:_,value:g}=await f.read();if(_)break;await new Promise((v,x)=>{d.write(g,b=>{if(b){x(b);return}v()})}),u+=g.length;const w=l?u/l*100:0;r?.({progress:w,loaded:u,total:l})}await new Promise((_,g)=>{d.close(w=>w?g(w):_())}),await mt.promises.rename(o,n)}catch(i){try{await mt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=$t.join(this.path,e);try{return await mt.promises.unlink(t),!0}catch{return!1}}},Qx={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"},Bh=100,Xx=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Ms(...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 cn(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 Yx(e){return!(!Xx.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function Jx(e,t,r){if(!r)return null;const n=Qx[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function Kx(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&de.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),o=0;const i=e.body.getReader();async function l(){const{done:u,value:d}=await i.read();if(u)return;const f=o+d.length;if(f>s){s=f;const g=new Uint8Array(s);g.set(a),a=g}a.set(d,o),o=f;const _=o/s*100;return t({progress:_,loaded:o,total:s}),l()}return await l(),a}function Rh(e){return cn(e,["blob:"])}function Gh(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 M_="SHA-256",Zx="experimental_transformers-hash-cache",$h=e=>({algorithm:M_,value:e}),Vh=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(Zx),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([$h(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([$h(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(M_,t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}};async function mi(e=null){let t=null;if(pe.useCustomCache){if(!pe.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!pe.customCache.match||!pe.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=pe.customCache}if(!t&&pe.experimental_useCrossOriginStorage&&Vh.isAvailable()&&(t=new Vh),!t&&pe.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(pe.cacheKey)}catch(r){de.warn("An error occurred while opening the browser cache:",r)}}if(!t&&pe.useFSCache){if(!ue.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new y_(e??pe.cacheDir)}return t}async function e1(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}var t1=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()}},r1=100,Mo=new t1(r1);function b_(e,t){const r=Mo.get(e);if(r!==void 0)return r;const n=t().then(s=>s,s=>(Mo.delete(e),Promise.reject(s)));return Mo.put(e,n),n}async function n1(e){if(!cn(e,["http:","https:"]))return null;const t=x_(e);return t.set("Range","bytes=0-0"),pe.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function gi(e,t,r={}){const n=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return b_(n,()=>s1(e,t,r))}async function s1(e,t,r){const n=await mi(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=T_(e,t,r,n),l=await k_(n,s,o);if(l!==void 0&&typeof l!="string"){const u=l.headers.get("content-length"),d=l.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:d||void 0,fromCache:!0}}if(pe.allowLocalModels&&!cn(s,["http:","https:"]))try{const d=await Us(s);if(typeof d!="string"&&d.status!==404){const f=d.headers.get("content-length"),_=d.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(pe.allowRemoteModels&&!r.local_files_only&&i)try{const u=await n1(a);if(u&&u.status>=200&&u.status<300){let d;const f=u.headers.get("content-type");if(u.status===206){const _=u.headers.get("content-range");if(_){const g=_.match(/bytes \d+-\d+\/(\d+)/);g&&(d=parseInt(g[1],10))}}else if(u.status===200)try{await u.body?.cancel()}catch{}if(d===void 0){const _=u.headers.get("content-length");d=_?parseInt(_,10):void 0}return{exists:!0,size:d,contentType:f||void 0,fromCache:!1}}}catch(u){de.warn(`Unable to fetch file metadata for "${a}": ${u}`)}return{exists:!1,fromCache:!1}}async function Us(e){return pe.useFS&&!cn(e,["http:","https:","blob:"])?new Vs(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):pe.fetch(e,{headers:x_(e)})}function x_(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const n=!!vo?.TESTING_REMOTELY,s=pe.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),cn(e,["http:","https:"],["huggingface.co","hf.co"])){const o=vo?.HF_TOKEN??vo?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function T_(e,t,r={},n=null){const s=r.revision??"main",a=Ms(e,t),o=Yx(e),i=o?Ms(pe.localModelPath,a):a,l=Ms(pe.remoteHost,pe.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),u=n instanceof y_?s==="main"?a:Ms(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:o}}async function k_(e,t,r){if(e)return await e1(e,t,r)}async function a1(e,t,r,n,s,a,o={}){if(await r.match(n)===void 0)if(a){if(typeof s!="string"){const i=new Headers(s.headers);i.set("content-length",a.byteLength.toString()),await r.put(n,new Response(a,{headers:i})).catch(l=>{de.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>Sr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function o1(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:d}=T_(e,t,n,a);let f,_=!1,g;g=await k_(a,i,u);const w=g!==void 0;if(w)f=u;else{if(pe.allowLocalModels)if(cn(o,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!pe.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{g=await Us(i),f=i}catch(k){de.warn(`Unable to load from local path "${i}": "${k}"`)}if(g===void 0||typeof g!="string"&&g.status===404){if(n.local_files_only||!pe.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(g=await Us(l),g.status!==200)return Jx(g.status,l,r);f=u}_=a&&typeof Response<"u"&&g instanceof Response&&g.status===200}Sr(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(ue.IS_NODE_ENV&&s)){let b;if(typeof g!="string")if(!n.progress_callback)b=new Uint8Array(await g.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))b=new Uint8Array(await g.arrayBuffer()),Sr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:b.length,total:b.length});else{let k;const C=g.headers.get("content-length");if(C)k=parseInt(C,10);else try{const E=await gi(e,t,n);E.size&&(k=E.size)}catch{}b=await Kx(g,E=>{Sr(n.progress_callback,{status:"progress",name:e,file:t,...E})},k)}v=b}if(_&&f&&typeof g!="string"&&await a1(e,t,a,f,g,v,n),ue.IS_NODE_ENV&&s&&n.progress_callback&&typeof g!="string"){const b=parseInt(g.headers.get("content-length"),10)||0;Sr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:b,total:b})}if(Sr(n.progress_callback,{status:"done",name:e,file:t}),v){if(!ue.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(g instanceof Vs)return g.filePath;const x=await a?.match(f);if(x instanceof Vs)return x.filePath;if(x instanceof Response)return new Uint8Array(await x.arrayBuffer());if(typeof x=="string")return x;throw new Error("Unable to get model file path or buffer.")}var bs=new Map;async function js(e,t,r=!0,n={},s=!1){if(!pe.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(!pe.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Sr(n.progress_callback,{status:"initiate",name:e,file:t});const a=`${e}::${t}`;let o=bs.get(a);if(!o){const i=await mi(n?.cache_dir);o=o1(e,t,r,n,s,i).then(l=>(bs.delete(a),l),l=>{throw bs.delete(a),l}),bs.set(a,o)}return await o}async function wi(e,t,r=!0,n={}){const s=await js(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function sr(e,t,r=!0,n={}){const s=await wi(e,t,r,n);return s===null?{}:JSON.parse(s)}function i1(e,[t,r,n],[s,a],o="bilinear",i=!1){const l=a/n,u=s/r,d=new e.constructor(s*a*t),f=r*n,_=s*a;for(let g=0;g=0;--i)s[i]=l,n[i]=t[r[i]],l*=n[i];const a=r.map((i,l)=>s[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i=0;--u)l+=d%t[u]*a[u],d=Math.floor(d/t[u]);o[l]=e[i]}return[o,n]}function un(e){const t=je(e)[0],r=e.map(a=>Math.exp(a-t)),n=r.reduce((a,o)=>a+o,0);return r.map(a=>a/n)}function c1(e){const t=je(e)[0];let r=0;for(let a=0;aa-t-n)}function Do(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 E_(e){return e>0&&(e&e-1)===0}var C_=class{constructor(e){if(this.size=e|0,this.size<=1||!E_(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){o=n/a<<1;const f=o>>>2;for(i=0;i>>1,a>>>1)}else for(i=0,l=0;i>>1,a>>>1,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const _=o>>>1,g=_>>>1,w=g>>>1;for(i=0;i>>1;for(let _=2;_>1;++u){const d=(u+1-e)**2/2,f=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),g=2*u;s[g]=f*Math.cos(_),s[g+1]=f*Math.sin(_),a[g]=s[g],a[g+1]=-s[g+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new C_(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const n=this._buffer1,s=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(r)for(let d=0;d>1,g=t[_];n[d]=g*l[d],n[f]=g*l[f]}else for(let d=0;d=e.length&&(l=2*(e.length-1)-l),n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function xs(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function f1(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function _1(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 d=1;d0||i>0;)switch(l.push(o-1),u.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}var p1=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l>10;let _=l&1023;if(f===31)u=d|2139095040|_<<13;else if(f===0)if(_===0)u=d;else{let g=113;for(;(_&1024)===0;)_<<=1,--g;_&=-1025,u=d|g<<23|_<<13}else u=d|f+112<<23|_<<13;o[0]=u,e[l]=i[0]}}const r=t.length,n=e,s=new Float32Array(r);for(let a=0;am1});var m1={};async function S_(e){const t=e.split("/").pop();let r;try{if(r=await mi(),r){const s=await r.match(e);if(s)return s}}catch(s){de.warn(`Failed to load ${t} from cache:`,s)}const n=await pe.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){de.warn(`Failed to cache ${t}:`,s)}return n}async function g1(e){const t=await S_(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return de.warn("Failed to read WASM binary:",r),null}}async function w1(e){if(ue.IS_SERVICE_WORKER_ENV||ue.IS_CHROME_AVAILABLE)return e;const t=await S_(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 de.warn("Failed to read WASM factory:",r),null}}var v1=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 P_(e){return e<=At.DEBUG?0:e<=At.INFO?2:e<=At.WARNING||e<=At.ERROR?3:4}var y1={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},bt=[],zo,rn,Uh=Symbol.for("onnxruntime");if(Uh in globalThis)rn=globalThis[Uh];else if(ue.IS_NODE_ENV){switch(rn=A_,process.platform){case"win32":bt.push("dml");break;case"linux":process.arch==="x64"&&bt.push("cuda");break;case"darwin":bt.push("coreml");break}bt.push("webgpu"),bt.push("cpu"),zo=["cpu"]}else rn=uM,ue.IS_WEBNN_AVAILABLE&&bt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ue.IS_WEBGPU_AVAILABLE&&bt.push("webgpu"),bt.push("wasm"),zo=["wasm"];var M1=rn.InferenceSession;function b1(e=null){if(!e)return zo;switch(e){case"auto":return bt;case"gpu":return bt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(bt.includes(e))return[v1[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${bt.join(", ")}.`)}var jh=Promise.resolve(),Hr=null;async function x1(){if(Hr)return Hr;if(!(pe.useWasmCache&&typeof Ve?.wasm?.wasmPaths=="object"&&Ve?.wasm?.wasmPaths?.wasm&&Ve?.wasm?.wasmPaths?.mjs)){if(ue.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Hr=Promise.resolve(),Hr}return Hr=(async()=>{const t=Ve.wasm.wasmPaths;let r=!1;await Promise.all([t.wasm&&!Rh(t.wasm)?(async()=>{try{const n=await g1(Gh(t.wasm));n&&(Ve.wasm.wasmBinary=n,r=!0)}catch(n){de.warn("Failed to pre-load WASM binary:",n)}})():Promise.resolve(),t.mjs&&!Rh(t.mjs)?(async()=>{try{const n=await w1(Gh(t.mjs));n&&(Ve.wasm.wasmPaths.mjs=n)}catch(n){de.warn("Failed to pre-load WASM factory:",n)}})():Promise.resolve()]),r||(Ve.wasm.wasmPaths.mjs=t.mjs)})(),Hr}async function F_(e,t,r){await x1();const n=P_(pe.logLevel??At.WARNING),s=()=>M1.create(e,{logSeverityLevel:n,...t}),a=await(ue.IS_WEB_ENV?jh=jh.then(s):s());return a.config=r,a}var qh=Promise.resolve();async function L_(e,t){const r=()=>e.run(t);return ue.IS_WEB_ENV?qh=qh.then(r):r()}function I_(e){return e instanceof rn.Tensor}var Ve=rn?.env;function vi(){return Ve?.wasm?.proxy}if(Ve){let e=function(t){const r=P_(t);Ve.logLevel=y1[r]};if(Ve.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Ve.versions?.web&&!Ve.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ve.versions.web}/dist/`;Ve.wasm.wasmPaths=ue.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`}}Ve.wasm.proxy=!1}Ve.webgpu&&(Ve.webgpu.powerPreference="high-performance"),e(pe.logLevel??At.WARNING),pe.backends.onnx={...Ve,setLogLevel:e}}var fr=async(e,t,r)=>{const n=await F_(new Uint8Array(e),t);return(async s=>{const a=vi(),o=Object.fromEntries(Object.entries(s).map(([l,u])=>[l,(a?u.clone():u).ort_tensor])),i=await L_(n,o);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},nn=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=fr([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=fr([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=fr([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=fr([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=fr([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=fr([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=fr([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=fr([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}},T1=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"}),bo=ue.IS_NODE_ENV?"cpu":"wasm";function O_(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 (${bo}).`),bo):bo}var k1=(function(){let e;return async function(){if(e===void 0)if(!ue.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),Ge=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"}),Wh=Ge.fp32,Hh=Object.freeze({[T1.wasm]:Ge.q8}),Bo=Object.freeze({[Ge.fp32]:"",[Ge.fp16]:"_fp16",[Ge.int8]:"_int8",[Ge.uint8]:"_uint8",[Ge.q8]:"_quantized",[Ge.q4]:"_q4",[Ge.q2]:"_q2",[Ge.q1]:"_q1",[Ge.q4f16]:"_q4f16",[Ge.q2f16]:"_q2f16",[Ge.q1f16]:"_q1f16",[Ge.bnb4]:"_bnb4"});function N_(e,t,r,{configDtype:n=null,warn:s}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===Ge.auto){if(n){const l=typeof n=="string"?n:n?.[t];if(l&&l!==Ge.auto&&Ge.hasOwnProperty(l))return l}i=Hh[r]??Wh}else a&&Ge.hasOwnProperty(a)?i=a:i=Hh[r]??Wh;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var jn=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}),U=class Be{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 I_(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new MM(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,o)=>a*o);return this._subarray(t,s,n)}else return new Be(this.type,[this.data[t]],n)}indexOf(t){const r=this.data;for(let n=0;ng)throw new Error(`Invalid slice: ${f}`);const w=[Math.max(_,0),Math.min(g,this.dims[d])];n.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}const s=n.map(([d,f])=>f-d),a=s.reduce((d,f)=>d*f),o=this.data,i=new o.constructor(a),l=this.stride();let u=!0;for(let d=1;d=0;--_){const w=s[_];f+=(g%w+n[_][0])*l[_],g=Math.floor(g/w)}i[d]=o[f]}return new Be(this.type,i,r)}permute(...t){return C1(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 o,i;if(a?(o=(f,_)=>f+_,i=0n):(o=(f,_)=>f+_**t,i=0),r===null){let f=s.reduce(o,i);return t!==1&&(f=f**(1/t)),new Be(this.type,[f],[])}const[l,u,d]=$n(o,this,r,n);if(t!==1)for(let f=0;f=0;--l){const f=this.dims[l];if(l!==r){const _=u%f;i+=_*d,d*=this.dims[l]}u=Math.floor(u/f)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return xo(this.dims)}squeeze(t=null){return new Be(this.type,this.data,Qh(this.dims,t))}squeeze_(t=null){return this.dims=Qh(this.dims,t),this}unsqueeze(t){return new Be(this.type,this.data,Xh(this.dims,t))}unsqueeze_(t){return this.dims=Xh(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((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;si!==r?a*o:a,1);t[r]=n.length/s}return new Be(this.type,n,t)}neg_(){const t=this.data;for(let r=0;rt?1:0;return new Be("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;sMath.min(o,i),this,t,r,1/0);return new Be(n,s,a)}max(t=null,r=!1){if(t===null){const o=je(this.data)[0];return new Be(this.type,[o],[])}const[n,s,a]=$n((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Be(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Do(this.data)[1];return new Be("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=je(this.data)[1];return new Be("int64",[BigInt(n)],[])}repeat(...t){if(t.lengthd===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,f=Array(d).fill(1).concat(this.dims);return new Be(this.type,this.data.slice(),f)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((d,f)=>d*t[f]),a=s.reduce((d,f)=>d*f,1),o=this.data,i=new o.constructor(a),l=xo(n),u=xo(s);for(let d=0;dBigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Be(t,p1(this.data),this.dims);return new Be(t,jn[t].from(this.data,r),this.dims)}};function E1(e,t){const r=e.length,n=t.reduce((a,o)=>a*o);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((o,i)=>{let l=o[o.length-1];return l.lengthnew U("int64",e,[e.length]);async function B_(e,t,r,n,s){return await(await nn.slice)({x:e,s:Ts(t),e:Ts(r),a:Ts(n),t:Ts(new Array(n.length).fill(1))})}function Qh(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 Xh(e,t){return t=Gt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Gt(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 Ne(e,t=0){t=Gt(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const n=r.reduce((o,i)=>o*i,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;s.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i=0;--_){const v=u[_];let x=g%v;_===t&&(x+=o),f+=x*w,w*=r[_],g=Math.floor(g/v)}s[f]=l[d]}o+=u[t]}}return new U(a,s,r)}function er(e,t=0){return Ne(e.map(r=>r.unsqueeze(t)),t)}function $n(e,t,r,n=!1,s=null){const a=t.data,o=t.dims;r=Gt(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);s!==null&&l.fill(s);for(let u=0;u=0;--f){const w=o[f];if(f!==r){const v=_%w;d+=v*g,g*=i[f]}_=Math.floor(_/w)}l[d]=e(l[d],a[u],u,d)}return n||i.splice(r,1),[t.type,l,i]}function S1(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const g=s.reduce((b,k)=>b+k,0)/s.length,w=Math.sqrt(s.reduce((b,k)=>b+(k-g)**2,0)/(s.length-r)),v=new U(e.type,[g],[]);return[new U(e.type,[w],[]),v]}t=Gt(t,a.length);const o=yi(e,t,n),i=o.data,[l,u,d]=$n((_,g,w,v)=>_+(g-i[v])**2,e,t,n);for(let _=0;_u+d,0);return new U(e.type,[l/s.length],[])}t=Gt(t,n.length);const[a,o,i]=$n((l,u)=>l+u,e,t,r);if(n[t]!==1)for(let l=0;l=0;--r)t[r]=n,n*=e[r];return t}function Mi(e,t,r,n){const s=e.reduce((a,o)=>a*o,1);return new U(r,new n(s).fill(t),e)}function st(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 Mi(e,t,r,n)}function Ro(e,t){return st(e.dims,t)}function dt(e){return Mi(e,1n,"int64",BigInt64Array)}function R_(e){return dt(e.dims)}function G_(e){return Mi(e,0n,"int64",BigInt64Array)}function $_(e){return G_(e.dims)}function P1(e){const t=e.reduce((r,n)=>r*n,1);return new U("float32",Float32Array.from({length:t},()=>pi.gauss()),e)}async function F1(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await gi(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function V_(e,t){const r=await F1(e);return await Promise.all(r.map(n=>sr(e,n,!0,t)))}function bi(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 L1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function I1(e,t,r,n){for(const s of Object.keys(e)){const a=t-e[s].length,o=r(s),i=new Array(a).fill(o);e[s]=n==="right"?Vt(e[s],i):Vt(i,e[s])}}function O1(e,t){for(const r of Object.keys(e))e[r].length=t}function Tr(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 N1(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var ae=class extends gt{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new X0(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Tr(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Tr(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Tr(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Tr(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Tr(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Tr(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=N1(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 o=await V_(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a});return new this(...o)}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:o=null,max_length:i=null}=t;const l=t.return_tensor??!0,u=Array.isArray(e);let d;if(u){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");d=e.map((_,g)=>this._encode_plus(_,{text_pair:r[g],add_special_tokens:n,return_token_type_ids:a}))}else d=e.map(_=>this._encode_plus(_,{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).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:n,return_token_type_ids:a})]}if(i===null?i=this.model_max_length:o===null&&(s===!0?(de.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),i=this.model_max_length):s===!1&&(de.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."),o=!0)),s===!0&&(i=Math.min(je(d.map(_=>_.input_ids.length))[0],i??1/0)),i=Math.min(i,this.model_max_length??1/0),s||o)for(let _=0;_i?o&&O1(d[_],i):s&&I1(d[_],i,g=>g==="input_ids"?this.pad_token_id:0,this.padding_side));const f={};if(l){if(!(s&&o)&&d.some(g=>{for(const w of Object.keys(g))if(g[w].length!==d[0][w]?.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 _=[d.length,d[0].input_ids.length];for(const g of Object.keys(d[0]))f[g]=new U("int64",BigInt64Array.from(d.flatMap(w=>w[g]).map(BigInt)),_)}else{for(const _ of Object.keys(d[0]))f[_]=d.map(g=>g[_]);if(!u)for(const _ of Object.keys(f))f[_]=f[_][0]}return f}_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:o}=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,...o?{token_type_ids:o}:{}}}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 U&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof U&&(e=bi(e)),!Array.isArray(e)||e.length===0||!zM(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:o=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:d=!0,return_dict:f=!0,tokenizer_kwargs:_={},...g}=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 w=this._compiled_template_cache.get(s);w===void 0&&(w=new jx(s),this._compiled_template_cache.set(s,w));const v=Object.create(null);for(const b of L1){const k=Tr(this.config,b);k&&(v[b]=k)}const x=w.render({messages:e,add_generation_prompt:a,tools:r,documents:n,...v,...g});if(o){const b=this._call(x,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:d,..._});return f?b:b.input_ids}return x}};function xi(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 o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.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 U_={};on(U_,{AlbertTokenizer:()=>D1,AutoTokenizer:()=>ke,BartTokenizer:()=>z1,BertTokenizer:()=>B1,BlenderbotSmallTokenizer:()=>R1,BlenderbotTokenizer:()=>G1,BloomTokenizer:()=>$1,CLIPTokenizer:()=>U1,CamembertTokenizer:()=>V1,CodeGenTokenizer:()=>q1,CodeLlamaTokenizer:()=>j1,CohereAsrTokenizer:()=>H1,CohereTokenizer:()=>W1,ConvBertTokenizer:()=>Q1,DebertaTokenizer:()=>Y1,DebertaV2Tokenizer:()=>X1,DistilBertTokenizer:()=>J1,ElectraTokenizer:()=>K1,EsmTokenizer:()=>Z1,FalconTokenizer:()=>eT,GPT2Tokenizer:()=>nT,GPTNeoXTokenizer:()=>rT,GemmaTokenizer:()=>tT,HerbertTokenizer:()=>sT,LlamaTokenizer:()=>aT,M2M100Tokenizer:()=>oT,MBart50Tokenizer:()=>lT,MBartTokenizer:()=>j_,MPNetTokenizer:()=>dT,MarianTokenizer:()=>iT,MgpstrTokenizer:()=>cT,MobileBertTokenizer:()=>uT,NllbTokenizer:()=>hT,NougatTokenizer:()=>fT,PreTrainedTokenizer:()=>ae,Qwen2Tokenizer:()=>_T,RoFormerTokenizer:()=>mT,RobertaTokenizer:()=>pT,SiglipTokenizer:()=>gT,SpeechT5Tokenizer:()=>wT,SqueezeBertTokenizer:()=>vT,T5Tokenizer:()=>yT,TokenizersBackend:()=>ae,VitsTokenizer:()=>bT,Wav2Vec2CTCTokenizer:()=>xT,WhisperTokenizer:()=>AT,XLMRobertaTokenizer:()=>ST,XLMTokenizer:()=>PT});var D1=class extends ae{return_token_type_ids=!0},z1=class extends ae{},B1=class extends ae{return_token_type_ids=!0},R1=class extends ae{},G1=class extends ae{},$1=class extends ae{},V1=class extends ae{},U1=class extends ae{},j1=class extends ae{},q1=class extends ae{},W1=class extends ae{},H1=class extends ae{},Q1=class extends ae{return_token_type_ids=!0},X1=class extends ae{return_token_type_ids=!0},Y1=class extends ae{return_token_type_ids=!0},J1=class extends ae{},K1=class extends ae{return_token_type_ids=!0},Z1=class extends ae{},eT=class extends ae{},tT=class extends ae{},rT=class extends ae{},nT=class extends ae{},sT=class extends ae{return_token_type_ids=!0},aT=class extends ae{padding_side="left"},oT=class extends ae{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 xi(this,e,t,r)}},iT=class extends ae{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)),de.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)||de.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Vt([n],super._encode_text(s))}}},j_=class extends ae{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 xi(this,e,t,r)}},lT=class extends j_{},cT=class extends ae{},uT=class extends ae{return_token_type_ids=!0},dT=class extends ae{},hT=class extends ae{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 xi(this,e,t,r)}},fT=class extends ae{},_T=class extends ae{},pT=class extends ae{},mT=class extends ae{return_token_type_ids=!0},gT=class extends ae{},wT=class extends ae{},vT=class extends ae{return_token_type_ids=!0},yT=class extends ae{},MT=class extends Lt{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 kT(e){e=e.toLowerCase();let t=TT.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),Ls.has(e))t=e;else{const s=e.length===2?Ls.keys():Ls.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var ET="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Yh=new RegExp(`^[${ET}]+$`,"gu"),CT=.1,AT=class extends ae{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 o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let u=i(),d=0;const f=this.timestamp_begin,g=f+1500;let w=[],v=[],x=!1,b=null;const k=new Set(this.all_special_ids);for(const P of e){const z=P.tokens,M=o?P.token_timestamps:null;let V=null,R=f;if("stride"in P){const[Q,O,I]=P.stride;if(d-=O,b=Q-I,O&&(R=O/n+f),I)for(let $=z.length-1;$>=0;--$){const H=Number(z[$]);if(H>=f){if(V!==null&&(H-f)*n=f&&O<=g){const I=(O-f)*n+d,$=xs(I,2);if(V!==null&&O>=V)x=!0;else if(x||w.length>0&&O0&&u.timestamp[1]!==null))for(const N of u.words)N.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=N.timestamp[0]&&(N.timestamp[1]=u.timestamp[1]);l.push(u),w=[],q=[],v=[],K=[],u=i()}}else if(q.push(O),o){let I=xs(M[Q]+d,2),$;if(Q+10?(w.push(q),o&&v.push(K)):w.every(Q=>Q.length===0)&&(u=i(),w=[],q=[],v=[],K=[])}if(w.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[P,z]=this.findLongestCommonSequence(w,v),M=this.decode(P);u.text=M,o&&(u.words=this.collateWordTimestamps(P,z,a)),l.push(u)}let C=Object.create(null);const E=l.map(P=>P.text).join("");if(t||r){for(let P=0;P0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;lO===R[I]&&i[E+I][0]-CT<=t[l][M+I][0]).length:q=z.filter((O,I)=>O===R[I]).length;const K=C/1e4,Q=q/C+K;q>1&&Q>d&&(d=Q,f=[E,P,M,V])}const[g,w,v,x]=f,b=Math.floor((w+g)/2);let k=Math.floor((x+v)/2);if(a&&d===0&&n>0){const C=i[n-1][0],E=t[l].findIndex(P=>P[0]>=C);k=E===-1?u.length:E}s.push(...r.slice(0,b)),r=u.slice(k),n=r.length,a&&(o.push(...i.slice(0,b)),i=t[l].slice(k))}return s.push(...r),a?(o.push(...i),[s,o]):[s,[]]}collateWordTimestamps(e,t,r){const[n,s,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i=n){const o=((a-n)*r).toFixed(2);s.push(`<|${o}|>`),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 o=[],i=[],l=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),g=l.trim(),w=Yh.test(g);if(f||_||w||s.length===0)s.push(l),a.push(u),o.push(d);else{const v=s.length-1;s[v]+=l,a[v].push(...u),o[v].push(...d)}}return[s,a,o]}mergePunctuations(e,t,r,n,s){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(r);let l=a.length-2,u=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[u]=a[l]+a[u],o[u]=Vt(o[l],o[u]),i[u]=Vt(i[l],i[u]),a[l]="",o[l]=[],i[l]=[]):u=l,--l;for(l=0,u=1;ud),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},ST=class extends ae{},PT=class extends ae{return_token_type_ids=!0;constructor(e,t){super(e,t),de.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},ke=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[o,i]=await V_(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let u=U_[l];return u||(de.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),u=ae),new u(o,i)}},Ks="https://github.com/huggingface/transformers.js/issues/new/choose",Ti="preprocessor_config.json",W_=Ti,H_="processor_config.json",Q_="chat_template.jinja",Ae=class extends gt{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?sr(e,H_,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?wi(e,Q_,!0,t):null]);return new this(r,n,s)}},FT={};on(FT,{ChatterboxProcessor:()=>nk,CohereAsrProcessor:()=>ak,Florence2Processor:()=>oE,Gemma3Processor:()=>iE,Gemma3nProcessor:()=>lE,Gemma4Processor:()=>cE,Glm46VProcessor:()=>uE,GraniteSpeechProcessor:()=>dE,GroundingDinoProcessor:()=>fE,Idefics3Processor:()=>nf,JinaCLIPProcessor:()=>wE,Lfm2VlProcessor:()=>vE,LlavaProcessor:()=>yE,MgpstrProcessor:()=>ME,MoonshineProcessor:()=>bE,OwlViTProcessor:()=>xE,PaliGemmaProcessor:()=>kE,Phi3VProcessor:()=>CE,PixtralProcessor:()=>AE,Processor:()=>Ae,PyAnnoteProcessor:()=>SE,Qwen2VLProcessor:()=>Si,Qwen2_5_VLProcessor:()=>Ep,Qwen3VLProcessor:()=>PE,Sam2Processor:()=>Ap,Sam2VideoProcessor:()=>FE,SamProcessor:()=>Cp,SmolVLMProcessor:()=>nf,SpeechT5Processor:()=>LE,UltravoxProcessor:()=>IE,VLChatProcessor:()=>gE,VoxtralProcessor:()=>zE,VoxtralRealtimeProcessor:()=>GE,Wav2Vec2Processor:()=>$E,Wav2Vec2ProcessorWithLM:()=>VE,WhisperProcessor:()=>UE});var at=class extends gt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await sr(e,Ti,!0,t);return new this(r)}};function tt(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 X_={};on(X_,{ASTFeatureExtractor:()=>UT,ChatterboxFeatureExtractor:()=>jT,ClapFeatureExtractor:()=>qT,CohereAsrFeatureExtractor:()=>HT,DacFeatureExtractor:()=>ep,EncodecFeatureExtractor:()=>K_,FeatureExtractor:()=>at,Gemma3nAudioFeatureExtractor:()=>tp,Gemma4AudioFeatureExtractor:()=>rp,GraniteSpeechFeatureExtractor:()=>QT,MoonshineFeatureExtractor:()=>XT,ParakeetFeatureExtractor:()=>Z_,PyAnnoteFeatureExtractor:()=>np,SeamlessM4TFeatureExtractor:()=>YT,SnacFeatureExtractor:()=>JT,SpeechT5FeatureExtractor:()=>KT,VoxtralRealtimeFeatureExtractor:()=>tk,Wav2Vec2FeatureExtractor:()=>ZT,WeSpeakerFeatureExtractor:()=>ek,WhisperFeatureExtractor:()=>rk});var LT=()=>{},IT=LT;async function OT(e,t){if(ue.IS_BROWSER_ENV){if(ue.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(ue.IS_FS_AVAILABLE)t.stream(),mt.createWriteStream(e),await IT();else throw new Error("Unable to save because filesystem is disabled in this environment.")}function Y_(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 To(e,t="htk"){const r=DT[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 zT={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 BT(e,t="htk"){const r=zT[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 RT(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),n=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;onew Array(e.length));for(let o=0;oe+n*a)}function jt(e,t,r,n,s,a=null,o="htk",i=!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 l=To(r,o),u=To(n,o),d=Kh(l,u,t+2);let f=BT(d,o),_;if(i){const w=s/((e-1)*2);_=To(Float64Array.from({length:e},(v,x)=>x*w),o),f=d}else _=Kh(0,Math.floor(s/2),e);const g=RT(_,f);if(a!==null&&a==="slaney")for(let w=0;ws)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(R!==r)throw new Error(`Length of the window (${R}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&f!==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(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){const W=Math.floor(r/2);switch(i){case"reflect":{e=GT(e,W,W);break}case"constant":{const he=new e.constructor(e.length+2*W);he.set(e,W),e=he;break}case"semicausal":{const he=new e.constructor(e.length+W);he.set(e,W),e=he;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let q=Math.floor(1+Math.floor((e.length-r)/n));C!==null&&qq?P&&(O=E):O=Q=E);const I=new d1(s),$=new Float64Array(s),H=new Float64Array(I.outputBufferSize),ee=new Float32Array(K*O);for(let W=0;W=1;--oe)$[oe]-=u*$[oe-1];$[0]*=1-u}for(let oe=0;oeMath.pow(u,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),n===null||e===n)return o;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);const i=new Float64Array(n),l=s?Math.floor((n-e)/2):0;return i.set(o,l),i}var UT=class extends at{constructor(e){super(e);const t=this.config.sampling_rate,r=jt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ar(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Wt(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){tt(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 o=Math.floor(pi.random()*(a+1));e=e.subarray(o,o+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 o=new Float64Array(t);if(o.set(e),n==="repeat")for(let i=e.length;i=1;--n)e[n]-=t*e[n-1];return await Wt(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){tt(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,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d1?r-1:1;for(let d=0;d=u){i.push(e.slice(l,u));break}const d=Math.max(l,l+a-o),f=Math.min(l+a,u);let _;f<=d?_=l+a:_=this._find_split_point_energy(e,d,f,n),_=Math.max(l+1,Math.min(_,u)),i.push(e.slice(l,_)),l=_}return i}_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,o=t;const i=s-n;for(let l=0;l<=i;l+=n){let u=0;for(let d=0;dt&&(e=e.slice(0,t)),n&&e.length%s!==0){const i=s-e.length%s,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=st([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},rp=class extends tp{async _extract_fbank_features(e,t){const{frame_length:r,hop_length:n,fft_length:s}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/n)+1;return Wt(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:o})}async _call(e,t={}){tt(e,"Gemma4AudioFeatureExtractor");const r=e.length,n=await super._call(e,t),{input_features:s}=n,[,a,o]=s.dims,{frame_length:i,hop_length:l}=this.config,u=Math.floor(i/2),d=i+1,f=new Uint8Array(r+u+(t.pad_to_multiple_of??128));f.fill(1,u,u+r);const _=new Uint8Array(a);for(let w=0;w({id:i,start:l*r,end:u*r,confidence:d/(u-l)})))}return n}},YT=class extends at{constructor(e){super(e);const t=this.config.sampling_rate,r=jt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ar(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Wt(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}={}){tt(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[g,w]=a.dims,v=a.data;for(let x=0;x0){const b=new Float32Array(w*(g+x));b.set(v),b.fill(this.config.padding_value,v.length);const k=g+x;a=new U(a.type,b,[k,w]),s&&(o=new U("int64",new BigInt64Array(k),[1,k]),o.data.fill(1n,0,g))}}const[i,l]=a.dims,u=this.config.stride;if(i%u!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${u}).`);const f=a.view(1,Math.floor(i/u),l*u),_={input_features:f};if(s){const g=f.dims[1],w=new BigInt64Array(g);if(o){const v=o.data;for(let x=1,b=0;xs+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){tt(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 U("float32",t,r),attention_mask:new U("int64",new BigInt64Array(t.length).fill(1n),r)}}},ek=class extends at{constructor(e){super(e);const t=this.config.sampling_rate,r=jt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ar(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),Wt(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){tt(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,o]=t.dims;for(let i=0;in?(e.length>this.config.n_samples&&de.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)}}},Tt=class{static async from_pretrained(e,t={}){const r=await sr(e,Ti,!0,t),n=r.feature_extractor_type,s=X_[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Ks}.`);return new s(r)}},nk=class extends Ae{static tokenizer_class=ke;static feature_extractor_class=Tt;async _call(e,t=null){const r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},sk=new Set(["ja","zh"]),ak=class extends Ae{static tokenizer_class=ke;static feature_extractor_class=Tt;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=sk.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}},Go={},Er,sp,_r;if(ue.IS_WEB_ENV)Er=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},_r=self.createImageBitmap,sp=self.ImageData;else if(Go)_r=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new qn(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 ok={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ik=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),qn=class Rt{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 Rt)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(!ue.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 Rt(n,t.width,t.height,4)}static async fromURL(t){const r=await Us(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(ue.IS_WEB_ENV){const r=await _r(t),n=Er(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=Go(await t.arrayBuffer());return await _r(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 Rt(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?l=n:d=-n,s>=0?u=s:f=-s,i.drawImage(o,l,u,t,r,d,f,t,r),new Rt(i.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 o=Math.floor(-s),i=Math.floor(-n);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;s<0?(o[0]=Math.floor(-s),o[1]=r-this.height-o[0]):i=Math.floor(s);let l=[0,0],u=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):u=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:t,height:r})}return await _r(a)}}async toBlob(t="image/png",r=1){if(!ue.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 U("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(!ue.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Er(t.width,t.height),n=new sp(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,o=t.length/s,i=Array.from({length:s},()=>new a(o));for(let l=0;lnew Rt(l,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 Rt(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(ue.IS_WEB_ENV){if(ue.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=ik.get(r)??"image/png",s=await this.toBlob(n);return OT(t,s)}else if(ue.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(ue.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Go(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};qn.read.bind(qn);function Zh(e,t,r=0,n=null){const s=e/t;let a=f1(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),at&&b.push(C)}else{let C=je(x.data)[1];if(C===l-1||(k=un(x.data),k[C]P*f[(z+1)%2])),_.boxes.push(E),_.classes.push(C),_.scores.push(k[C])}}u.push(_)}return u}function op(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;af[b]&&(f[b]=x[b],_[b]=v)}const g=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const x=_[v];g[x]=x}const w=g.filter(v=>v!==void 0);s.push({segmentation:d,labels:w})}return s}function lk(e,t,r,n){const s=[],a=[],o=[];for(let i=0;ir&&(s.push(u),a.push(_),o.push(d))}return[s,a,o]}function ck(e,t,r,n=.5,s=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let d=0;d=n&&++i;let u=o>0&&i>0;return u&&(u=o/i>s),[u,a]}function uk(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,u=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v_[k]&&(f[k]=v,_[k]=b[k])}let g=0;const w=u.data;for(let v=0;v200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>s){const l=Math.sqrt(a*e*t/s);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r)}else if(a*o*is?l=Math.floor(s*i/n):s>n&&(i=Math.floor(n*l/s)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),n=Do(r.data)[0],a=je(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,u=0,d=0;const f=r.data;for(let _=0;_this.preprocess(s)));return{pixel_values:er(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 sr(e,W_,!0,t);return new this(r)}},cp={};on(cp,{BeitFeatureExtractor:()=>dk,BitImageProcessor:()=>hk,CHMv2ImageProcessor:()=>_k,CLIPFeatureExtractor:()=>pk,CLIPImageProcessor:()=>up,ChineseCLIPFeatureExtractor:()=>fk,ConvNextFeatureExtractor:()=>mk,ConvNextImageProcessor:()=>dp,DINOv3ViTImageProcessor:()=>vk,DPTFeatureExtractor:()=>Mk,DPTImageProcessor:()=>_p,DeiTFeatureExtractor:()=>gk,DeiTImageProcessor:()=>hp,DetrFeatureExtractor:()=>wk,DetrImageProcessor:()=>fp,DonutFeatureExtractor:()=>yk,DonutImageProcessor:()=>Ei,EfficientNetImageProcessor:()=>bk,GLPNFeatureExtractor:()=>Ck,Gemma3ImageProcessor:()=>xk,Gemma4ImageProcessor:()=>pp,Glm46VImageProcessor:()=>Ek,GroundingDinoImageProcessor:()=>Ak,Idefics3ImageProcessor:()=>tf,ImageFeatureExtractor:()=>ie,ImageProcessor:()=>ie,JinaCLIPImageProcessor:()=>Pk,Lfm2VlImageProcessor:()=>Nk,LlavaOnevisionImageProcessor:()=>Dk,Mask2FormerImageProcessor:()=>Bk,MaskFormerFeatureExtractor:()=>zk,MaskFormerImageProcessor:()=>Ci,MobileNetV1FeatureExtractor:()=>Rk,MobileNetV1ImageProcessor:()=>gp,MobileNetV2FeatureExtractor:()=>Gk,MobileNetV2ImageProcessor:()=>wp,MobileNetV3FeatureExtractor:()=>$k,MobileNetV3ImageProcessor:()=>vp,MobileNetV4FeatureExtractor:()=>Vk,MobileNetV4ImageProcessor:()=>yp,MobileViTFeatureExtractor:()=>Uk,MobileViTImageProcessor:()=>Mp,NougatImageProcessor:()=>jk,OwlViTFeatureExtractor:()=>qk,OwlViTImageProcessor:()=>Ai,Owlv2ImageProcessor:()=>Wk,Phi3VImageProcessor:()=>Qk,PixtralImageProcessor:()=>Xk,PvtImageProcessor:()=>Yk,Qwen2VLImageProcessor:()=>mp,RTDetrImageProcessor:()=>Jk,Sam2ImageProcessor:()=>Co,Sam3ImageProcessor:()=>Co,SamImageProcessor:()=>Co,SapiensFeatureExtractor:()=>Kk,SapiensImageProcessor:()=>bp,SegformerFeatureExtractor:()=>Zk,SegformerImageProcessor:()=>xp,SiglipImageProcessor:()=>eE,SmolVLMImageProcessor:()=>tf,Swin2SRImageProcessor:()=>tE,VLMImageProcessor:()=>Sk,ViTFeatureExtractor:()=>rE,ViTImageProcessor:()=>Tp,VitMatteImageProcessor:()=>nE,VitPoseImageProcessor:()=>sE,YolosFeatureExtractor:()=>aE,YolosImageProcessor:()=>kp});var dk=class extends ie{},hk=class extends ie{},fk=class extends ie{},_k=class extends ie{},up=class extends ie{},pk=class extends up{},dp=class extends ie{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}},mk=class extends dp{},hp=class extends ie{},gk=class extends hp{},fp=class extends ie{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=st(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Zs(...e)}post_process_panoptic_segmentation(...e){return ip(...e)}post_process_instance_segmentation(...e){return lp(...e)}},wk=class extends fp{},vk=class extends ie{},Ei=class extends ie{pad_image(e,t,r,n={}){const[s,a,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const u=i.map((d,f)=>-d/l[f]);return super.pad_image(e,t,r,{center:!0,constant_values:u,...n})}},yk=class extends Ei{},_p=class extends ie{},Mk=class extends _p{},bk=class extends ie{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))}},xk=class extends ie{};function Tk(e,t,r,n,s){const a=n*r**2,o=Math.sqrt(a/(e*t)),i=s*r;let l=Math.floor(o*e/i)*i,u=Math.floor(o*t/i)*i;if(l===0&&u===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);const d=Math.floor(n/s**2)*i;return l===0?(l=i,u=Math.min(Math.floor(t/e)*i,d)):u===0&&(u=i,l=Math.min(Math.floor(e/t)*i,d)),[l,u]}function kk(e,t,r,n,s,a,o){const i=Math.floor(t/s),l=Math.floor(r/s),u=i*l,d=s*s*n,f=new Float32Array(a*d);let _=0;for(let v=0;va),0));const u=a.dims[0]/o,d=a.dims[1],f=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),g=a.view(u,o,d,Math.floor(f/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(u*f*_,d*o*l*l),w=new U("int64",[u,f,_],[1,3]);return{pixel_values:g,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},Ek=class extends mp{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return ki(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}},Ck=class extends ie{},Ak=class extends ie{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=dt([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},tf=class extends ie{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=[],o=[];const i=[],l=[];for(const x of n){let b=await Promise.all(x.map(E=>this.preprocess(E)));i.push(...b.map(E=>E.original_size)),l.push(...b.map(E=>E.reshaped_input_size)),b.forEach(E=>E.pixel_values.unsqueeze_(0));const{longest_edge:k}=this.max_image_size;let C;if(t??this.do_image_splitting){let E=new Array(b.length),P=new Array(b.length);C=await Promise.all(b.map(async(z,M)=>{const V=this.get_resize_for_vision_encoder(z.pixel_values,k),R=await Ut(z.pixel_values,{size:[V.height,V.width]}),{frames:q,num_splits_h:K,num_splits_w:Q}=await this.split_image(R,this.max_image_size);return E[M]=K,P[M]=Q,Ne(q,0)})),a.push(E),o.push(P)}else{const E=[k,k];C=await Promise.all(b.map(P=>Ut(P.pixel_values,{size:E}))),a.push(new Array(b.length).fill(0)),o.push(new Array(b.length).fill(0))}s.push(Ne(C,0))}const u=s.length,[d,f,_,g]=s[0].dims;let w,v;if(u===1)w=s[0].unsqueeze_(0),v=st([u,d,_,g],!0);else{const x=Math.max(...s.map(C=>C.dims.at(0)));v=st([u,x,_,g],!0);const b=v.data,k=x*_*g;for(let C=0;Cr||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);const u=Math.ceil(a/i),d=Math.ceil(o/l);for(let g=0;gt*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},Pk=class extends ie{constructor(e){const{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,o=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},i=n==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:s,do_normalize:!0})}};function rf(e,t){return Math.round(e/t)*t}function Fk(e,t,r,n,s){let a=1/0,o=[1,1];const i=r*n;for(const l of t){const u=Math.abs(e-l[0]/l[1]);u.5*s*s*l[0]*l[1]&&(o=l)}return o}function Lk(e,t){const r=[],n=new Set;for(let s=e;s<=t;++s)for(let a=1;a<=s;++a)for(let o=1;o<=s;++o){const i=a*o;if(i>=e&&i<=t){const l=a<<16|o;n.has(l)||(n.add(l),r.push([a,o]))}}return r.sort((s,a)=>s[0]*s[1]-a[0]*a[1])}function Ik(e,t){const[r,n,s,a]=e.dims,o=Math.floor(s/t),i=Math.floor(a/t),l=t*t*n,u=e.data,d=new Float32Array(r*o*i*l),f=s*a;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=Lk(this.min_tiles,this.max_tiles),[n,s]=Fk(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=[],o=[],i=[],l=[];for(const d of r){const f=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(const{pixel_values:_}of f){const[,g,w]=_.dims,v=_.unsqueeze_(0),x=this.encoder_patch_size*this.downsample_factor,b=x**2,[k,C]=ki(Math.max(x,g),Math.max(x,w),x,this.min_image_tokens*b,this.max_image_tokens*b).map(R=>Math.max(x,R));let E,P=1,z=1;const M=this._is_image_too_large(g,w),V=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(M&&V){const{grid_width:R,grid_height:q,target_width:K,target_height:Q}=this._get_grid_layout(g,w);P=q,z=R;const O=await Ut(v,{size:[Q,K]});E=[];for(let I=0;I(u-this.image_mean[d])/this.image_std[d]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Eo(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(f=>this.preprocess(f))),s=n.map(f=>f.original_size),a=n.map(f=>f.reshaped_input_size),o=[];for(const{pixel_values:f}of n){f.unsqueeze_(0);const[_,g]=f.dims.slice(-2),w=await Ut(f,{size:[ht,ht],mode:"bicubic"});if(t>0){const v=[],x=Eo(t),b=Qr(g/x),k=Qr(_/x);for(let E=0;Ef.map(_=>ht*ko(_/ht))),u=new U("int64",l.flat(),[r,2]),d=l.map(([f,_])=>this.calc_num_image_tokens_from_image_size(_,f));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:d}}},Xk=class extends ie{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 o=n,i=s;a>1&&(o=Math.floor(n/a),i=Math.floor(s/a));const{patch_size:l,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");const d=l*u,f=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[f*d,_*d]}},Yk=class extends ie{},Jk=class extends ie{post_process_object_detection(...e){return Zs(...e)}},Co=class extends ie{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=vh(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 U("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 o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;ln&&(g[w]=1);f=new U("bool",g,f.dims)}o.push(f)}return o}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}={}){}},bp=class extends ie{post_process_semantic_segmentation(...e){return op(...e)}},Kk=class extends bp{},xp=class extends ie{post_process_semantic_segmentation(...e){return op(...e)}},Zk=class extends xp{},eE=class extends ie{},tE=class extends ie{pad_image(e,t,r,n={}){const[s,a,o]=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})}},Tp=class extends ie{},rE=class extends Tp{},nE=class extends ie{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:er(r.map((a,o)=>Ne([a.pixel_values,n[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},sE=class extends ie{post_process_pose_estimation(e,t,{threshold:r=null}={}){const n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let u=0;u/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",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[u,d,...f]of o)i.push(d?d.trim():i.at(-1)??""),l.push(f.map((_,g)=>(Number(_)+.5)/this.size_per_bin*r[g%2]));s={labels:i,[a]:l};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}}},iE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;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 o=s.repeat(this.image_seq_length);this.full_image_sequence=` + +${n}${o}${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}}},lE=class extends Ae{static image_processor_class=ot;static feature_extractor_class=Tt;static tokenizer_class=ke;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:o,image_token_id:i,boi_token:l,image_token:u,eoi_token:d}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const f=a.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${s}${f}${o} + +`,this.image_token_id=i,this.boi_token=l,this.image_token=u;const _=u.repeat(this.image_seq_length);this.full_image_sequence=` + +${l}${_}${d} + +`}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(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,n),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...s}}},cE=class extends Ae{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:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=n,this.boa_token=s,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){const[r,n,s]=await Promise.all([sr(e,H_,!0,t),ke.from_pretrained(e,t),wi(e,Q_,!1,t)]),a={tokenizer:n};return r.image_processor&&(a.image_processor=new pp(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new rp(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 o=0;o<2;++o)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 o=s.num_soft_tokens_per_image;let i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>` + +${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token} + +`))}let a;if(r){const o=Array.isArray(r)?r:[r];a=await this.feature_extractor(o[0],n);const i=this.feature_extractor.config.sampling_rate??16e3;let l=0;e=e.map(u=>u.replaceAll(this.audio_token,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token} + +`))}return{...this.tokenizer(e,n),...s,...a}}},Si=class extends Ae{static image_processor_class=ot;static tokenizer_class=ke;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 o=this.image_processor.config.merge_size**2,i=0;const l=this.constructor.image_token,u=s.tolist();e=e.map(d=>{for(;d.includes(l);){const f=Number(u[i++].reduce((_,g)=>_*g,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(f/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...n}}},uE=class extends Si{static image_token="<|image|>"},dE=class extends Ae{static tokenizer_class=ke;static feature_extractor_class=Tt;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,o=Math.floor(a/2);return Math.ceil(o/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 o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);n.input_features_mask=new U("bool",i,[1,o]);const l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}};function hE(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((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var fE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;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:o}=e,i=a.dims[0];if(s!==null&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),u=a.sigmoid(),d=u.max(-1).tolist(),f=o.tolist().map(g=>g.map(w=>ap(w))),_=[];for(let g=0;gC.map((E,P)=>E*w[(P+1)%2])));const v=d[g],x=[],b=[],k=[];for(let C=0;C`+s.repeat(e);o+=` +`}return o+=` +${n}${a}`+s.repeat(e)+`${n}`,o}function pE(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function mE(e,t,r,n,s,a){return e===0&&t===0?pE(r,n,s,a):_E(r,e,t,n,s,a)}var nf=class extends Ae{static image_processor_class=ot;static tokenizer_class=ke;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)],o=this.config.image_seq_len,i=[],l=[];for(let d=0;dmE(b,g[k],o,this.fake_image_token,this.image_token,this.global_img_token)),v=f.split(this.image_token);if(v.length===0)throw new Error("The image token should be present in the text.");let x=v[0];for(let b=0;bv.images).flatMap(v=>v.images).map(v=>qn.read(v)));const n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>n.encode(v,{add_special_tokens:!1}),o=s.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,u,d]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let f=a(o[0]),_=new Array(f.length).fill(!1);for(let v=1;v0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},wE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;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}}},vE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;async _call(e,t=null,r={}){const{image_rows:n,image_cols:s,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){const i=this.config.image_token??"",{tile_size:l=512,downsample_factor:u=2,encoder_patch_size:d=16,use_thumbnail:f=!0}=this.image_processor.config,_=k=>Math.ceil(Math.floor(k/d)/u),g=_(l)**2,w=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",x=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let b=0;t=t.map(k=>{const C=k.split(i);return C[0]+C.slice(1).map(E=>{const P=b++,[z,M]=a[P],V=n[P],R=s[P],q=_(z)*_(M);let K=w;if(V>1||R>1){const Q=i.repeat(g);for(let O=0;O`+Q;f&&(K+=x+i.repeat(q))}else K+=i.repeat(q);return K+v+E}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},yE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:u}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+u;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let f=0;f0?w.reduce((x,b)=>x*b,1):0;l.push(g),i.push(v)}return[s(l),i]}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,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),u=[],d=[];for(let f=0;f";function TE(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e} +`}var kE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(de.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(l=>l.includes(Xr))?a=t.map(l=>{const u=l.replaceAll(Xr,Xr.repeat(s)),d=u.lastIndexOf(Xr),f=d===-1?0:d+Xr.length;return u.slice(0,f)+n+u.slice(f)+` +`}):(de.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(l=>TE(l,n,s,Xr,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},af="<|image|>",EE=/<\|image_\d+\|>/g,CE=class extends Ae{static image_processor_class=ot;static tokenizer_class=ke;async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:s});const{num_img_tokens:i}=o,l=e.map((d,f)=>d.split(EE).join(af.repeat(i[f])));a=this.tokenizer(l,{padding:r,truncation:n});const u=this.tokenizer._tokenizer.token_to_id(af);a.input_ids.map_(d=>d==u?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},AE=class extends Ae{static tokenizer_class=ke;static image_processor_class=ot;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:u,patch_size:d,spatial_merge_size:f}=this.config,_=d*f,g=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;vDE(g,i)),u=l.map(g=>g.length),d=l.flat(),f=(await Promise.all(d.map(g=>this.feature_extractor(g,r)))).map(g=>g.input_features);n.audio_values=f.length>1?Ne(f,0):f[0];let _=a[0];for(let g=0;g0){if(u>Bh)throw new Error(`The number of external data chunks (${u}) exceeds the maximum allowed value (${Bh}).`);const d=Pp(o,u);for(const f of d){const _=`${n.subfolder??""}/${f}`;l.push(new Promise(async(g,w)=>{const v=await js(e,_,!0,n,i);g(v instanceof Uint8Array?{path:f,data:v}:f)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const f=await js(e,d.data,!0,n);return{...d,data:f}}return d}));return Promise.all(l)}async function QE(e,t,r,n=!1,s=void 0){let a=r.config?.["transformers.js_config"]??{};const o=O_(r.device??a.device,t,{warn:k=>de.info(k)}),i=b1(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const u=N_(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:k=>de.info(k)});if(Bo.hasOwnProperty(u)){if(o==="webgpu"&&!ue.IS_NODE_ENV&&u===Ge.fp16&&!await k1())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${u}. Should be one of: ${Object.keys(Ge).join(", ")}`);const d=Bo[u],f={...r.session_options};f.executionProviders??=i;const _=a.free_dimension_overrides;_?f.freeDimensionOverrides??=_:o.startsWith("webnn")&&!f.freeDimensionOverrides&&de.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"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const g=WE(e,t,r,d),w=r.use_external_data_format??a.use_external_data_format,v=await HE(e,t,d,r,w,f);if(v.length>0&&(!ue.IS_NODE_ENV||v.some(k=>typeof k!="string"))&&(f.externalData=v),n&&o==="webgpu"){const k=ea(r.config,{prefix:"present",session_name:s});if(k.size>0&&!vi()){const C={};for(const E of k)C[E]="gpu-buffer";f.preferredOutputLocation=C}}return{buffer_or_path:await g,session_options:f,session_config:{dtype:u,device:o}}}async function XE(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:o,session_options:i,session_config:l}=await QE(e,t[s],r,a,s),u=await F_(o,i,l);return[s,u]})))}function Fp(e){for(let t in e)I_(e[t])?e[t]=new U(e[t]):typeof e[t]=="object"&&Fp(e[t]);return e}async function ye(e,t){const r=YE(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return ue.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await L_(e,n);return Fp(s)}catch(n){const s=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw de.error(`An error occurred during model execution: "${n}".`),de.error("Inputs given to model:",s),n}}function YE(e,t){const r=Object.create(null),n=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof U)){n.push(o);continue}r[o]=vi()?i.clone():i}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 o=Object.keys(t).filter(i=>!e.inputNames.includes(i));de.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var qe=class{},ne=class extends qe{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},$e=class extends qe{constructor({logits:e}){super(),this.logits=e}},We=class extends qe{constructor({logits:e}){super(),this.logits=e}},it=class extends qe{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Dr=class extends qe{constructor({logits:e}){super(),this.logits=e}},JE=class extends qe{constructor({alphas:e}){super(),this.alphas=e}},Ot=class extends gt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},KE=class extends gt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Uo=class extends gt{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()}},ZE=class extends Ot{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r=1&&s[s.length-1]>=this.timestamp_begin,o=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a&&(o?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 d=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(d+1).fill(-1/0)}const i=c1(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,f)=>d+f)),u=je(i.subarray(0,this.timestamp_begin))[0];l>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},n2=class extends Ot{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)}},d2=class extends ta{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)})}},ra=class extends gt{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 Wx(e)}static getSampler(e){if(e.do_sample)return new f2(e);if(e.num_beams>1)return new _2(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 h2(e)}},h2=class extends ra{async sample(e){const t=je(e.data)[1];return[[BigInt(t),0]]}},f2=class extends ra{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 z_(e,t),s=un(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},_2=class extends ra{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 z_(e,t),s=un(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},p2=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 U))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)}},Pi=p2,j={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},pr={[j.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[j.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[j.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[j.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[j.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"}},[j.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[j.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[j.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...pr[j.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"}},[j.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...pr[j.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"}},[j.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...pr[j.ImageAudioTextToText].text_only_sessions};return r||(n.audio_encoder="audio_encoder",n.vision_encoder="vision_encoder"),n},optional_configs:{generation_config:"generation_config.json"}},[j.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"}},[j.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"}},[j.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[j.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[j.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"}},[j.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...pr[j.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 m2(e,t,r={}){const n=pr[e]??pr.default;return{sessions:n.sessions(t,r,r.textOnly??!1),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}function g2(e,{warn:t=!0}={}){const r=e.architectures||[];for(const n of r){const s=Zt.get(n);if(s!==void 0)return s}if(e.model_type){const n=Zt.get(e.model_type);if(n!==void 0)return n;for(const s of Object.values(Zr))if(s.has(e.model_type)){const a=Zt.get(s.get(e.model_type));if(a!==void 0)return a}}if(t){const n=r.length>0?r.join(", "):"(none)";de.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: ${Ks}`)}return j.EncoderOnly}function w2(e,{config:t=null,cache_dir:r=null,local_files_only:n=!1,revision:s="main"}={}){if(t!==null)return qs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s});const a=JSON.stringify([e,r,n,s]);return b_(a,()=>qs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s}))}async function v2(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await w2(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",u=n??o.device;let d=r??o.dtype;const f=g2(t),_=(v,x=null)=>{x=x??v;const b=O_(u,v),k=N_(d,v,b),C=Bo[k]??"",E=`${x}${C}.onnx`,P=`${l}/${E}`;a.push(P);const z=Sp(i,E,v);for(const M of Pp(E,z)){const V=`${l}/${M}`;a.push(V)}},{sessions:g,optional_configs:w}=m2(f,t,{model_file_name:s});for(const[v,x]of Object.entries(g))_(v,x);if(w)for(const v of Object.values(w))a.push(v);return a}var Zr=null;function y2(e){Zr=e}function jo(e){if(e instanceof U)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 U("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new U("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function Dp(e){return new U("bool",[e],[1])}var lf={[j.DecoderOnly]:{can_generate:!0,forward:tr,prepare_inputs:Vn},[j.DecoderOnlyWithoutHead]:{can_generate:!1,forward:tr,prepare_inputs:Vn},[j.Seq2Seq]:{can_generate:!0,forward:Cs,prepare_inputs:Ws},[j.Vision2Seq]:{can_generate:!0,forward:Cs,prepare_inputs:Ws},[j.Musicgen]:{can_generate:!0,forward:Cs},[j.EncoderDecoder]:{can_generate:!1,forward:Cs},[j.ImageTextToText]:{can_generate:!0,forward:T2,prepare_inputs:As},[j.AudioTextToText]:{can_generate:!0,forward:x2,prepare_inputs:As},[j.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:As},[j.Phi3V]:{can_generate:!0,prepare_inputs:As},[j.MultiModality]:{can_generate:!0},[j.AutoEncoder]:{can_generate:!1,forward:M2},[j.Chatterbox]:{can_generate:!0,forward:wr},[j.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Vn},default:{can_generate:!1,forward:wr}};function cf(e,t){let r=Zt.get(e),n=!1;const s=t?.architectures?.[0];if(s&&s!==e&&e?.endsWith("ForCausalLM")&&s.endsWith("ForConditionalGeneration")){const i=Zt.get(s);i!==void 0&&(r=i,n=!0)}const a=lf[r]??lf.default,o=pr[r]??pr.default;return{typeConfig:{...a,...o},textOnly:n,modelType:r}}var Zt=new Map,Fi=new Map,sn=new Map,A=class extends gt{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=sn.get(this.constructor),{typeConfig:s}=cf(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:o=null,subfolder:i="onnx",device:l=null,dtype:u=null,use_external_data_format:d=null,session_options:f={}}={}){const _={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:u,use_external_data_format:d,session_options:f},g=sn.get(this);r=_.config=await qs.from_pretrained(e,_);const{typeConfig:w,textOnly:v,modelType:x}=cf(g,r);if(x===void 0){const E=g??r?.model_type;E!=="custom"&&de.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Ks}.`)}if(t&&!(t instanceof gh)){const E={};try{const P=await v2(e,{config:r,dtype:u,device:l,model_file_name:o});(await Promise.all(P.map(M=>gi(e,M,_)))).forEach((M,V)=>{if(M.exists){const R=P[V]==="config.json";E[P[V]]={loaded:R?M.size??0:0,total:M.size??0}}})}catch(P){de.warn(`Unable to fetch model file metadata for total progress tracking: ${P}`)}Object.keys(E).length>0&&(_.progress_callback=new gh(t,E))}const b=w.sessions(r,_,v),k=[XE(e,b,_,w.cache_sessions)];w.optional_configs&&k.push(E2(e,w.optional_configs,_));const C=await Promise.all(k);return new this(r,...C)}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 Uo;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new s2(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new n2(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new i2(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new a2(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 o2(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new ZE(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new e2(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new t2(e.suppress_tokens)),e.begin_suppress_tokens!==null){const s=t>1||e.forced_bos_token_id===null?t:t+1;n.push(new Lp(e.begin_suppress_tokens,s))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new l2(e.guidance_scale)),e.temperature===0&&e.do_sample&&(de.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 c2(e.temperature)),r!==null&&n.extend(r),n}_prepare_generation_config(e,t,r=Ip){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,Ze(t,Object.getOwnPropertyNames(s))),s}_get_stopping_criteria(e,t=null){const r=new Op;return e.max_length!==null&&r.push(new u2(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new d2(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[Zr.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Zr.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Zr.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Zr.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=sn.get(this.constructor),r=new Set,n=this.config.model_type;for(const a of e){const o=a?.get(n);o&&r.add(o)}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=qo(t,r.past_key_values),r.input_ids=new U("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in r&&(r.decoder_attention_mask=Ne([r.decoder_attention_mask,dt([r.decoder_attention_mask.dims[0],1])],1)):r.attention_mask=Ne([r.attention_mask,dt([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=Ze(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:o,attention_mask:i,...l}=t,u=await this._prepare_inputs_embeds(t);t={...l,...Ze(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:s}=await wr(this,t);if(n.guidance_scale!==null&&n.guidance_scale>1)s=Ne([s,Ro(s,0)],0),"attention_mask"in t&&(t.attention_mask=Ne([t.attention_mask,$_(t.attention_mask)],0));else if(t.decoder_input_ids){const a=jo(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=Ne(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:o,...i}=r;if(!(o instanceof U)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(n??=s,this.config.model_type==="musicgen")o=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}`);o=n}else o=Array.from({length:e},()=>[n]);o=jo(o)}return i.decoder_attention_mask=R_(o),{input_ids:o,model_inputs:i}}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:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const u=this.config.is_encoder_decoder;u&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:i,model_input_name:l,generation_config:t})));let d;u?{input_ids:d,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[l].dims.at(0),model_input_name:l,model_kwargs:i,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):d=i[l];let f=d.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=f+t.max_new_tokens);const _=this._get_logits_processor(t,f,r),g=this._get_stopping_criteria(t,n),w=i[l].dims.at(0),v=ra.getSampler(t),x=new Array(w).fill(0),b=d.tolist();s&&s.put(b);let k,C={},E={};for(;;){if(i=this.prepare_inputs_for_generation(b,i,t),k=await this.forward(i),t.return_dict_in_generate)if(t.output_attentions){const O=b2(k);for(const I in O)I in C||(C[I]=[]),C[I].push(O[I])}else this._return_dict_in_generate_keys&&Object.assign(E,Ze(k,this._return_dict_in_generate_keys));const R=k.logits.slice(null,-1,null).to("float32"),q=_(b,R),K=[];for(let O=0;OO))break;i=this._update_model_kwargs_for_generation({generated_input_ids:K,outputs:k,model_inputs:i,is_encoder_decoder:u})}s&&s.end();const P=new U("int64",b.flat(),[b.length,b[0].length]),z=qo(k,i.past_key_values),M=new Set(Object.values(z));for(const R of Object.values(k))R.location==="gpu-buffer"&&!M.has(R)&&R.dispose();return"past_key_values"in a||t.return_dict_in_generate||await z.dispose(),t.return_dict_in_generate?{sequences:P,past_key_values:z,...C,...E}:P}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 ye(n,Ze(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 Cs(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,decoder_attention_mask:a,...o}=t;if(!r){const i=Ze(t,e.sessions.model.inputNames);r=(await wr(e,i)).last_hidden_state}return o.input_ids=s,o.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await tr(e,o,!0)}async function wr(e,t){const r=e.sessions.model,n=Ze(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=$_(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=dt([s[0],s[2],s[3]])}return await ye(r,n)}async function M2(e,t){const r=await e.encode(t);return await e.decode(r)}function qo(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 Pi(r)}function b2(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 zp(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function Li(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=ea(e.config),o=e.config?.normalized_config?.num_heads,i={batch_size:s};typeof o=="number"&&(i["batch_size x num_heads"]=s*o);const l=Object.create(null);for(const u of n.inputMetadata){if(!a.has(u.name))continue;const d=zp(u.shape,i),f=d.reduce((w,v)=>w*v,1),_=jn[u.type],g=new U(u.type,new _(f),d);t[u.name]=g,l[u.name]=g}return r?(r.update(l),r):new Pi(l)}async function tr(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=Dp(s!=null&&Object.keys(s).length>0)),n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=k2(a,s,i)}n.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new U("int64",[0n],[])),Li(e,a,s);const o=Ze(a,n.inputNames);return await ye(n,o)}async function Bp(e,{encode_function:t,merge_function:r,modality_input_names:n,modality_output_name:s,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:d=null,logits_processor:f=null,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});const w=Ze(_,n);if(Object.keys(w).length>0){if(a.dims[1]!==1){const v=await t({...w,..._});({inputs_embeds:l,attention_mask:o}=r({[s]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(u&&a.dims[1]===1){const v=a.dims[1],x=u.get_seq_length();o=Ne([dt([a.dims[0],x]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}}if(!i&&["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:w,video_grid_thw:v}=_;[i]=e.get_rope_index(a,w,v,o)}return await tr(e,{inputs_embeds:l,past_key_values:u,attention_mask:o,position_ids:i,generation_config:d,logits_processor:f},!0)}async function x2(e,t){return await Bp(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 T2(e,t){return await Bp(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 Rp(e,t=0){const[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;oo.dims[1]||s[s.at(-1)])),{...r,decoder_input_ids:jo(t)}}function As(e,...t){return e.config.is_encoder_decoder?Ws(e,...t):Vn(e,...t)}function Gp({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(u=>u.reduce((d,f,_)=>(f==e&&d.push(_),d),[])),o=a.reduce((u,d)=>u+d.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let u=0;u{const s=await sr(e,t[n],!1,r);return[n,s]})))}var Oi={};on(Oi,{ASTForAudioClassification:()=>B2,ASTModel:()=>z2,ASTPreTrainedModel:()=>Bi,AfmoeForCausalLM:()=>O2,AfmoeModel:()=>I2,AfmoePreTrainedModel:()=>Di,AlbertForMaskedLM:()=>P2,AlbertForQuestionAnswering:()=>S2,AlbertForSequenceClassification:()=>A2,AlbertModel:()=>C2,AlbertPreTrainedModel:()=>Xn,ApertusForCausalLM:()=>L2,ApertusModel:()=>F2,ApertusPreTrainedModel:()=>Ni,ArceeForCausalLM:()=>D2,ArceeModel:()=>N2,ArceePreTrainedModel:()=>zi,BartForConditionalGeneration:()=>G2,BartForSequenceClassification:()=>$2,BartModel:()=>R2,BartPretrainedModel:()=>na,BeitForImageClassification:()=>U2,BeitModel:()=>V2,BeitPreTrainedModel:()=>Ri,BertForMaskedLM:()=>q2,BertForQuestionAnswering:()=>Q2,BertForSequenceClassification:()=>W2,BertForTokenClassification:()=>H2,BertModel:()=>j2,BertPreTrainedModel:()=>dn,BlenderbotForConditionalGeneration:()=>Y2,BlenderbotModel:()=>X2,BlenderbotPreTrainedModel:()=>Gi,BlenderbotSmallForConditionalGeneration:()=>K2,BlenderbotSmallModel:()=>J2,BlenderbotSmallPreTrainedModel:()=>$i,BloomForCausalLM:()=>eC,BloomModel:()=>Z2,BloomPreTrainedModel:()=>Vi,CHMv2ForDepthEstimation:()=>lC,CHMv2PreTrainedModel:()=>qp,CLIPModel:()=>uC,CLIPPreTrainedModel:()=>zr,CLIPSegForImageSegmentation:()=>pC,CLIPSegModel:()=>_C,CLIPSegPreTrainedModel:()=>Ui,CLIPTextModel:()=>dC,CLIPTextModelWithProjection:()=>Qp,CLIPVisionModel:()=>hC,CLIPVisionModelWithProjection:()=>fC,CamembertForMaskedLM:()=>rC,CamembertForQuestionAnswering:()=>aC,CamembertForSequenceClassification:()=>nC,CamembertForTokenClassification:()=>sC,CamembertModel:()=>tC,CamembertPreTrainedModel:()=>hn,ChatterboxModel:()=>Up,ChatterboxPreTrainedModel:()=>Vp,ChineseCLIPModel:()=>iC,ChineseCLIPPreTrainedModel:()=>jp,ClapAudioModelWithProjection:()=>Hp,ClapModel:()=>cC,ClapPreTrainedModel:()=>sa,ClapTextModelWithProjection:()=>Wp,CodeGenForCausalLM:()=>gC,CodeGenModel:()=>mC,CodeGenPreTrainedModel:()=>ji,Cohere2ForCausalLM:()=>MC,Cohere2Model:()=>yC,Cohere2PreTrainedModel:()=>Wi,CohereAsrForConditionalGeneration:()=>xC,CohereAsrModel:()=>bC,CohereAsrPreTrainedModel:()=>Hi,CohereForCausalLM:()=>vC,CohereModel:()=>wC,CoherePreTrainedModel:()=>qi,ConvBertForMaskedLM:()=>kC,ConvBertForQuestionAnswering:()=>AC,ConvBertForSequenceClassification:()=>EC,ConvBertForTokenClassification:()=>CC,ConvBertModel:()=>TC,ConvBertPreTrainedModel:()=>fn,ConvNextForImageClassification:()=>PC,ConvNextModel:()=>SC,ConvNextPreTrainedModel:()=>Qi,ConvNextV2ForImageClassification:()=>LC,ConvNextV2Model:()=>FC,ConvNextV2PreTrainedModel:()=>Xi,DFineForObjectDetection:()=>DC,DFineModel:()=>NC,DFinePreTrainedModel:()=>Ji,DINOv3ConvNextModel:()=>lA,DINOv3ConvNextPreTrainedModel:()=>nm,DINOv3ViTModel:()=>cA,DINOv3ViTPreTrainedModel:()=>sm,DPTForDepthEstimation:()=>gA,DPTModel:()=>mA,DPTPreTrainedModel:()=>nl,DacDecoderModel:()=>Kp,DacDecoderOutput:()=>Yp,DacEncoderModel:()=>Jp,DacEncoderOutput:()=>Xp,DacModel:()=>zC,DacPreTrainedModel:()=>aa,DebertaForMaskedLM:()=>RC,DebertaForQuestionAnswering:()=>VC,DebertaForSequenceClassification:()=>GC,DebertaForTokenClassification:()=>$C,DebertaModel:()=>BC,DebertaPreTrainedModel:()=>_n,DebertaV2ForMaskedLM:()=>WC,DebertaV2ForQuestionAnswering:()=>XC,DebertaV2ForSequenceClassification:()=>HC,DebertaV2ForTokenClassification:()=>QC,DebertaV2Model:()=>qC,DebertaV2PreTrainedModel:()=>pn,DecisionTransformerModel:()=>YC,DecisionTransformerPreTrainedModel:()=>Zp,DeepseekV3ForCausalLM:()=>jC,DeepseekV3Model:()=>UC,DeepseekV3PreTrainedModel:()=>Ki,DeiTForImageClassification:()=>KC,DeiTModel:()=>JC,DeiTPreTrainedModel:()=>Zi,DepthAnythingForDepthEstimation:()=>ZC,DepthAnythingPreTrainedModel:()=>em,DepthProForDepthEstimation:()=>eA,DepthProPreTrainedModel:()=>tm,DetrForObjectDetection:()=>rA,DetrForSegmentation:()=>nA,DetrModel:()=>tA,DetrObjectDetectionOutput:()=>el,DetrPreTrainedModel:()=>oa,DetrSegmentationOutput:()=>rm,Dinov2ForImageClassification:()=>aA,Dinov2Model:()=>sA,Dinov2PreTrainedModel:()=>tl,Dinov2WithRegistersForImageClassification:()=>iA,Dinov2WithRegistersModel:()=>oA,Dinov2WithRegistersPreTrainedModel:()=>rl,DistilBertForMaskedLM:()=>_A,DistilBertForQuestionAnswering:()=>fA,DistilBertForSequenceClassification:()=>dA,DistilBertForTokenClassification:()=>hA,DistilBertModel:()=>uA,DistilBertPreTrainedModel:()=>mn,DonutSwinModel:()=>pA,DonutSwinPreTrainedModel:()=>am,EdgeTamModel:()=>AL,EfficientNetForImageClassification:()=>vA,EfficientNetModel:()=>wA,EfficientNetPreTrainedModel:()=>sl,ElectraForMaskedLM:()=>MA,ElectraForQuestionAnswering:()=>TA,ElectraForSequenceClassification:()=>bA,ElectraForTokenClassification:()=>xA,ElectraModel:()=>yA,ElectraPreTrainedModel:()=>gn,Ernie4_5ForCausalLM:()=>EA,Ernie4_5Model:()=>kA,Ernie4_5PretrainedModel:()=>al,EsmForMaskedLM:()=>AA,EsmForSequenceClassification:()=>SA,EsmForTokenClassification:()=>PA,EsmModel:()=>CA,EsmPreTrainedModel:()=>Jn,EuroBertForMaskedLM:()=>LA,EuroBertForSequenceClassification:()=>IA,EuroBertForTokenClassification:()=>OA,EuroBertModel:()=>FA,EuroBertPreTrainedModel:()=>Kn,ExaoneForCausalLM:()=>DA,ExaoneModel:()=>NA,ExaonePreTrainedModel:()=>ol,FalconForCausalLM:()=>BA,FalconH1ForCausalLM:()=>GA,FalconH1Model:()=>RA,FalconH1PreTrainedModel:()=>ll,FalconModel:()=>zA,FalconPreTrainedModel:()=>il,FastViTForImageClassification:()=>VA,FastViTModel:()=>$A,FastViTPreTrainedModel:()=>cl,Florence2ForConditionalGeneration:()=>UA,Florence2PreTrainedModel:()=>om,GLPNForDepthEstimation:()=>oS,GLPNModel:()=>aS,GLPNPreTrainedModel:()=>gl,GPT2LMHeadModel:()=>mS,GPT2Model:()=>pS,GPT2PreTrainedModel:()=>bl,GPTBigCodeForCausalLM:()=>lS,GPTBigCodeModel:()=>iS,GPTBigCodePreTrainedModel:()=>wl,GPTJForCausalLM:()=>wS,GPTJModel:()=>gS,GPTJPreTrainedModel:()=>xl,GPTNeoForCausalLM:()=>uS,GPTNeoModel:()=>cS,GPTNeoPreTrainedModel:()=>vl,GPTNeoXForCausalLM:()=>hS,GPTNeoXModel:()=>dS,GPTNeoXPreTrainedModel:()=>yl,Gemma2ForCausalLM:()=>HA,Gemma2Model:()=>WA,Gemma2PreTrainedModel:()=>dl,Gemma3ForCausalLM:()=>JA,Gemma3ForConditionalGeneration:()=>cm,Gemma3Model:()=>YA,Gemma3PreTrainedModel:()=>lm,Gemma3nForCausalLM:()=>KA,Gemma3nForConditionalGeneration:()=>ia,Gemma3nPreTrainedModel:()=>um,Gemma4ForCausalLM:()=>ZA,Gemma4ForConditionalGeneration:()=>hl,GemmaForCausalLM:()=>qA,GemmaModel:()=>jA,GemmaPreTrainedModel:()=>ul,GlmForCausalLM:()=>tS,GlmModel:()=>eS,GlmMoeDsaForCausalLM:()=>nS,GlmMoeDsaModel:()=>rS,GlmMoeDsaPreTrainedModel:()=>_l,GlmOcrForConditionalGeneration:()=>sS,GlmPreTrainedModel:()=>fl,GptOssForCausalLM:()=>_S,GptOssModel:()=>fS,GptOssPreTrainedModel:()=>Ml,GraniteForCausalLM:()=>yS,GraniteModel:()=>vS,GraniteMoeHybridForCausalLM:()=>bS,GraniteMoeHybridModel:()=>MS,GraniteMoeHybridPreTrainedModel:()=>kl,GranitePreTrainedModel:()=>Tl,GraniteSpeechForConditionalGeneration:()=>xS,GroundingDinoForObjectDetection:()=>TS,GroundingDinoPreTrainedModel:()=>pm,GroupViTModel:()=>kS,GroupViTPreTrainedModel:()=>mm,HeliumForCausalLM:()=>CS,HeliumModel:()=>ES,HeliumPreTrainedModel:()=>Cl,HieraForImageClassification:()=>SS,HieraModel:()=>AS,HieraPreTrainedModel:()=>Al,HubertForCTC:()=>DS,HubertForSequenceClassification:()=>zS,HubertModel:()=>NS,HubertPreTrainedModel:()=>OS,HunYuanDenseV1ForCausalLM:()=>RS,HunYuanDenseV1Model:()=>BS,HunYuanDenseV1PreTrainedModel:()=>Sl,IJepaForImageClassification:()=>$S,IJepaModel:()=>GS,IJepaPreTrainedModel:()=>Pl,Idefics3ForConditionalGeneration:()=>gm,JAISLMHeadModel:()=>US,JAISModel:()=>VS,JAISPreTrainedModel:()=>Fl,JinaCLIPModel:()=>jS,JinaCLIPPreTrainedModel:()=>la,JinaCLIPTextModel:()=>wm,JinaCLIPVisionModel:()=>qS,Lfm2ForCausalLM:()=>HS,Lfm2Model:()=>WS,Lfm2MoeForCausalLM:()=>YS,Lfm2MoeModel:()=>XS,Lfm2MoePreTrainedModel:()=>Il,Lfm2PreTrainedModel:()=>Ll,Lfm2VlForConditionalGeneration:()=>JS,LightOnOcrForConditionalGeneration:()=>QS,LiteWhisperForConditionalGeneration:()=>XI,Llama4ForCausalLM:()=>eP,Llama4PreTrainedModel:()=>vm,LlamaForCausalLM:()=>ZS,LlamaModel:()=>KS,LlamaPreTrainedModel:()=>Ol,LlavaForConditionalGeneration:()=>rr,LlavaOnevisionForConditionalGeneration:()=>rr,LlavaPreTrainedModel:()=>im,LlavaQwen2ForCausalLM:()=>XA,LongT5ForConditionalGeneration:()=>rP,LongT5Model:()=>tP,LongT5PreTrainedModel:()=>Nl,M2M100ForConditionalGeneration:()=>sP,M2M100Model:()=>nP,M2M100PreTrainedModel:()=>Dl,MBartForCausalLM:()=>hP,MBartForConditionalGeneration:()=>uP,MBartForSequenceClassification:()=>dP,MBartModel:()=>cP,MBartPreTrainedModel:()=>Zn,MPNetForMaskedLM:()=>KP,MPNetForQuestionAnswering:()=>tF,MPNetForSequenceClassification:()=>ZP,MPNetForTokenClassification:()=>eF,MPNetModel:()=>JP,MPNetPreTrainedModel:()=>wn,MT5ForConditionalGeneration:()=>aF,MT5Model:()=>sF,MT5PreTrainedModel:()=>Hl,MarianMTModel:()=>oP,MarianModel:()=>aP,MarianPreTrainedModel:()=>zl,MaskFormerForInstanceSegmentation:()=>lP,MaskFormerModel:()=>iP,MaskFormerPreTrainedModel:()=>Bl,Metric3DForDepthEstimation:()=>fP,Metric3DPreTrainedModel:()=>ym,Metric3Dv2ForDepthEstimation:()=>_P,Metric3Dv2PreTrainedModel:()=>Mm,MgpstrForSceneTextRecognition:()=>pP,MgpstrModelOutput:()=>bm,MgpstrPreTrainedModel:()=>xm,MimiDecoderModel:()=>Cm,MimiDecoderOutput:()=>km,MimiEncoderModel:()=>Em,MimiEncoderOutput:()=>Tm,MimiModel:()=>mP,MimiPreTrainedModel:()=>ca,Mistral4ForCausalLM:()=>yP,Mistral4Model:()=>vP,Mistral4PreTrainedModel:()=>Gl,MistralForCausalLM:()=>wP,MistralModel:()=>gP,MistralPreTrainedModel:()=>Rl,MobileBertForMaskedLM:()=>bP,MobileBertForQuestionAnswering:()=>TP,MobileBertForSequenceClassification:()=>xP,MobileBertModel:()=>MP,MobileBertPreTrainedModel:()=>es,MobileLLMForCausalLM:()=>EP,MobileLLMModel:()=>kP,MobileLLMPreTrainedModel:()=>$l,MobileNetV1ForImageClassification:()=>AP,MobileNetV1ForSemanticSegmentation:()=>SP,MobileNetV1Model:()=>CP,MobileNetV1PreTrainedModel:()=>ua,MobileNetV2ForImageClassification:()=>FP,MobileNetV2ForSemanticSegmentation:()=>LP,MobileNetV2Model:()=>PP,MobileNetV2PreTrainedModel:()=>da,MobileNetV3ForImageClassification:()=>OP,MobileNetV3ForSemanticSegmentation:()=>NP,MobileNetV3Model:()=>IP,MobileNetV3PreTrainedModel:()=>ha,MobileNetV4ForImageClassification:()=>zP,MobileNetV4ForSemanticSegmentation:()=>BP,MobileNetV4Model:()=>DP,MobileNetV4PreTrainedModel:()=>fa,MobileViTForImageClassification:()=>GP,MobileViTModel:()=>RP,MobileViTPreTrainedModel:()=>Vl,MobileViTV2ForImageClassification:()=>VP,MobileViTV2Model:()=>$P,MobileViTV2PreTrainedModel:()=>Ul,ModernBertDecoderForCausalLM:()=>QP,ModernBertDecoderModel:()=>HP,ModernBertDecoderPreTrainedModel:()=>jl,ModernBertForMaskedLM:()=>jP,ModernBertForSequenceClassification:()=>qP,ModernBertForTokenClassification:()=>WP,ModernBertModel:()=>UP,ModernBertPreTrainedModel:()=>ts,Moondream1ForConditionalGeneration:()=>QA,MoonshineForConditionalGeneration:()=>YP,MoonshineModel:()=>XP,MoonshinePreTrainedModel:()=>ql,MptForCausalLM:()=>nF,MptModel:()=>rF,MptPreTrainedModel:()=>Wl,MultiModalityCausalLM:()=>oF,MultiModalityPreTrainedModel:()=>Am,MusicgenForCausalLM:()=>lF,MusicgenForConditionalGeneration:()=>Sm,MusicgenModel:()=>iF,MusicgenPreTrainedModel:()=>Ql,NanoChatForCausalLM:()=>uF,NanoChatModel:()=>cF,NanoChatPreTrainedModel:()=>Xl,NemotronHForCausalLM:()=>hF,NemotronHModel:()=>dF,NemotronHPreTrainedModel:()=>Yl,NeoBertForMaskedLM:()=>_F,NeoBertForQuestionAnswering:()=>gF,NeoBertForSequenceClassification:()=>pF,NeoBertForTokenClassification:()=>mF,NeoBertModel:()=>fF,NeoBertPreTrainedModel:()=>vn,NomicBertModel:()=>wF,NomicBertPreTrainedModel:()=>Pm,OPTForCausalLM:()=>LF,OPTModel:()=>FF,OPTPreTrainedModel:()=>nc,Olmo2ForCausalLM:()=>bF,Olmo2Model:()=>MF,Olmo2PreTrainedModel:()=>Kl,Olmo3ForCausalLM:()=>TF,Olmo3Model:()=>xF,Olmo3PreTrainedModel:()=>Zl,OlmoForCausalLM:()=>yF,OlmoHybridForCausalLM:()=>EF,OlmoHybridModel:()=>kF,OlmoHybridPreTrainedModel:()=>ec,OlmoModel:()=>vF,OlmoPreTrainedModel:()=>Jl,OpenAIPrivacyFilterForTokenClassification:()=>AF,OpenAIPrivacyFilterModel:()=>CF,OpenAIPrivacyFilterPreTrainedModel:()=>tc,OpenELMForCausalLM:()=>PF,OpenELMModel:()=>SF,OpenELMPreTrainedModel:()=>rc,OwlViTForObjectDetection:()=>DF,OwlViTModel:()=>NF,OwlViTPreTrainedModel:()=>ac,Owlv2ForObjectDetection:()=>OF,Owlv2Model:()=>IF,Owlv2PreTrainedModel:()=>sc,PaliGemmaForConditionalGeneration:()=>zF,ParakeetForCTC:()=>BF,ParakeetPreTrainedModel:()=>Fm,PatchTSMixerForPrediction:()=>GF,PatchTSMixerModel:()=>RF,PatchTSMixerPreTrainedModel:()=>oc,PatchTSTForPrediction:()=>VF,PatchTSTModel:()=>$F,PatchTSTPreTrainedModel:()=>ic,Phi3ForCausalLM:()=>WF,Phi3Model:()=>qF,Phi3PreTrainedModel:()=>cc,Phi3VForCausalLM:()=>Im,Phi3VPreTrainedModel:()=>Lm,PhiForCausalLM:()=>jF,PhiModel:()=>UF,PhiPreTrainedModel:()=>lc,PreTrainedModel:()=>A,PvtForImageClassification:()=>QF,PvtModel:()=>HF,PvtPreTrainedModel:()=>uc,PyAnnoteForAudioFrameClassification:()=>YF,PyAnnoteModel:()=>XF,PyAnnotePreTrainedModel:()=>dc,Qwen2ForCausalLM:()=>KF,Qwen2Model:()=>JF,Qwen2MoeForCausalLM:()=>eL,Qwen2MoeModel:()=>ZF,Qwen2MoePreTrainedModel:()=>fc,Qwen2PreTrainedModel:()=>hc,Qwen2VLForCausalLM:()=>hm,Qwen2VLForConditionalGeneration:()=>pl,Qwen2VLPreTrainedModel:()=>dm,Qwen2_5_VLForCausalLM:()=>fm,Qwen2_5_VLForConditionalGeneration:()=>ml,Qwen3ForCausalLM:()=>rL,Qwen3Model:()=>tL,Qwen3MoeForCausalLM:()=>sL,Qwen3MoeModel:()=>nL,Qwen3MoePreTrainedModel:()=>pc,Qwen3NextForCausalLM:()=>oL,Qwen3NextModel:()=>aL,Qwen3NextPreTrainedModel:()=>mc,Qwen3PreTrainedModel:()=>_c,Qwen3VLForCausalLM:()=>Om,Qwen3VLForConditionalGeneration:()=>gc,Qwen3VLMoeForCausalLM:()=>lL,Qwen3VLMoeForConditionalGeneration:()=>iL,Qwen3_5ForCausalLM:()=>Nm,Qwen3_5ForConditionalGeneration:()=>wc,Qwen3_5MoeForCausalLM:()=>uL,Qwen3_5MoeForConditionalGeneration:()=>cL,RFDetrForObjectDetection:()=>_L,RFDetrModel:()=>fL,RFDetrObjectDetectionOutput:()=>Dm,RFDetrPreTrainedModel:()=>yc,RTDetrForObjectDetection:()=>OC,RTDetrModel:()=>IC,RTDetrObjectDetectionOutput:()=>Yn,RTDetrPreTrainedModel:()=>Yi,RTDetrV2ForObjectDetection:()=>EL,RTDetrV2Model:()=>kL,RTDetrV2ObjectDetectionOutput:()=>zm,RTDetrV2PreTrainedModel:()=>Mc,ResNetForImageClassification:()=>hL,ResNetModel:()=>dL,ResNetPreTrainedModel:()=>vc,RoFormerForMaskedLM:()=>ML,RoFormerForQuestionAnswering:()=>TL,RoFormerForSequenceClassification:()=>bL,RoFormerForTokenClassification:()=>xL,RoFormerModel:()=>yL,RoFormerPreTrainedModel:()=>Mn,RobertaForMaskedLM:()=>mL,RobertaForQuestionAnswering:()=>vL,RobertaForSequenceClassification:()=>gL,RobertaForTokenClassification:()=>wL,RobertaModel:()=>pL,RobertaPreTrainedModel:()=>yn,Sam2ImageSegmentationOutput:()=>Gm,Sam2Model:()=>bc,Sam2PreTrainedModel:()=>$m,Sam3TrackerModel:()=>SL,SamImageSegmentationOutput:()=>Bm,SamModel:()=>CL,SamPreTrainedModel:()=>Rm,SapiensForDepthEstimation:()=>FL,SapiensForNormalEstimation:()=>LL,SapiensForSemanticSegmentation:()=>PL,SapiensPreTrainedModel:()=>_a,SegformerForImageClassification:()=>OL,SegformerForSemanticSegmentation:()=>NL,SegformerModel:()=>IL,SegformerPreTrainedModel:()=>pa,SiglipModel:()=>DL,SiglipPreTrainedModel:()=>xc,SiglipTextModel:()=>Vm,SiglipVisionModel:()=>zL,SmolLM3ForCausalLM:()=>RL,SmolLM3Model:()=>BL,SmolLM3PreTrainedModel:()=>Tc,SmolVLMForConditionalGeneration:()=>GL,SnacDecoderModel:()=>jm,SnacEncoderModel:()=>Um,SnacModel:()=>$L,SnacPreTrainedModel:()=>ma,SolarOpenForCausalLM:()=>UL,SolarOpenModel:()=>VL,SolarOpenPreTrainedModel:()=>kc,SpeechT5ForSpeechToText:()=>qL,SpeechT5ForTextToSpeech:()=>WL,SpeechT5HifiGan:()=>HL,SpeechT5Model:()=>jL,SpeechT5PreTrainedModel:()=>ga,SqueezeBertForMaskedLM:()=>XL,SqueezeBertForQuestionAnswering:()=>JL,SqueezeBertForSequenceClassification:()=>YL,SqueezeBertModel:()=>QL,SqueezeBertPreTrainedModel:()=>rs,StableLmForCausalLM:()=>ZL,StableLmModel:()=>KL,StableLmPreTrainedModel:()=>Ec,Starcoder2ForCausalLM:()=>tI,Starcoder2Model:()=>eI,Starcoder2PreTrainedModel:()=>Cc,StyleTextToSpeech2Model:()=>rI,StyleTextToSpeech2PreTrainedModel:()=>qm,SupertonicForConditionalGeneration:()=>Hm,SupertonicPreTrainedModel:()=>Wm,Swin2SRForImageSuperResolution:()=>iI,Swin2SRModel:()=>oI,Swin2SRPreTrainedModel:()=>Ac,SwinForImageClassification:()=>sI,SwinForSemanticSegmentation:()=>aI,SwinModel:()=>nI,SwinPreTrainedModel:()=>wa,T5ForConditionalGeneration:()=>cI,T5Model:()=>lI,T5PreTrainedModel:()=>Sc,TableTransformerForObjectDetection:()=>dI,TableTransformerModel:()=>uI,TableTransformerObjectDetectionOutput:()=>Qm,TableTransformerPreTrainedModel:()=>Pc,TrOCRForCausalLM:()=>hI,TrOCRPreTrainedModel:()=>Xm,UltravoxModel:()=>El,UltravoxPreTrainedModel:()=>_m,UniSpeechForCTC:()=>_I,UniSpeechForSequenceClassification:()=>pI,UniSpeechModel:()=>fI,UniSpeechPreTrainedModel:()=>va,UniSpeechSatForAudioFrameClassification:()=>vI,UniSpeechSatForCTC:()=>gI,UniSpeechSatForSequenceClassification:()=>wI,UniSpeechSatModel:()=>mI,UniSpeechSatPreTrainedModel:()=>ns,VaultGemmaForCausalLM:()=>MI,VaultGemmaModel:()=>yI,VaultGemmaPreTrainedModel:()=>Fc,ViTForImageClassification:()=>TI,ViTMAEModel:()=>kI,ViTMAEPreTrainedModel:()=>Ym,ViTMSNForImageClassification:()=>CI,ViTMSNModel:()=>EI,ViTMSNPreTrainedModel:()=>Ic,ViTModel:()=>xI,ViTPreTrainedModel:()=>Lc,VisionEncoderDecoderModel:()=>bI,VitMatteForImageMatting:()=>AI,VitMattePreTrainedModel:()=>Jm,VitPoseForPoseEstimation:()=>SI,VitPosePreTrainedModel:()=>Km,VitsModel:()=>PI,VitsModelOutput:()=>Zm,VitsPreTrainedModel:()=>eg,VoxtralForConditionalGeneration:()=>FI,VoxtralRealtimeForConditionalGeneration:()=>rg,VoxtralRealtimePreTrainedModel:()=>tg,Wav2Vec2BertForCTC:()=>RI,Wav2Vec2BertForSequenceClassification:()=>GI,Wav2Vec2BertModel:()=>BI,Wav2Vec2BertPreTrainedModel:()=>ya,Wav2Vec2ForAudioFrameClassification:()=>IS,Wav2Vec2ForCTC:()=>FS,Wav2Vec2ForSequenceClassification:()=>LS,Wav2Vec2Model:()=>PS,Wav2Vec2PreTrainedModel:()=>vr,WavLMForAudioFrameClassification:()=>qI,WavLMForCTC:()=>VI,WavLMForSequenceClassification:()=>UI,WavLMForXVector:()=>jI,WavLMModel:()=>$I,WavLMPreTrainedModel:()=>bn,WeSpeakerResNetModel:()=>WI,WeSpeakerResNetPreTrainedModel:()=>sg,WhisperForConditionalGeneration:()=>ag,WhisperModel:()=>QI,WhisperPreTrainedModel:()=>Oc,XLMForQuestionAnswering:()=>eO,XLMForSequenceClassification:()=>KI,XLMForTokenClassification:()=>ZI,XLMModel:()=>YI,XLMPreTrainedModel:()=>xn,XLMRobertaForMaskedLM:()=>rO,XLMRobertaForQuestionAnswering:()=>aO,XLMRobertaForSequenceClassification:()=>nO,XLMRobertaForTokenClassification:()=>sO,XLMRobertaModel:()=>tO,XLMRobertaPreTrainedModel:()=>Tn,XLMWithLMHeadModel:()=>JI,XVectorOutput:()=>ng,YolosForObjectDetection:()=>iO,YolosModel:()=>oO,YolosObjectDetectionOutput:()=>og,YolosPreTrainedModel:()=>Nc,YoutuForCausalLM:()=>cO,YoutuModel:()=>lO,YoutuPreTrainedModel:()=>Dc});var Xn=class extends A{},C2=class extends Xn{},A2=class extends Xn{async _call(e){return new ne(await super._call(e))}},S2=class extends Xn{async _call(e){return new it(await super._call(e))}},P2=class extends Xn{async _call(e){return new We(await super._call(e))}},Ni=class extends A{},F2=class extends Ni{},L2=class extends Ni{},Di=class extends A{},I2=class extends Di{},O2=class extends Di{},zi=class extends A{},N2=class extends zi{},D2=class extends zi{},Bi=class extends A{},z2=class extends Bi{},B2=class extends Bi{},na=class extends A{},R2=class extends na{},G2=class extends na{},$2=class extends na{async _call(e){return new ne(await super._call(e))}},Ri=class extends A{},V2=class extends Ri{},U2=class extends Ri{async _call(e){return new ne(await super._call(e))}},dn=class extends A{},j2=class extends dn{},q2=class extends dn{async _call(e){return new We(await super._call(e))}},W2=class extends dn{async _call(e){return new ne(await super._call(e))}},H2=class extends dn{async _call(e){return new $e(await super._call(e))}},Q2=class extends dn{async _call(e){return new it(await super._call(e))}},Gi=class extends A{},X2=class extends Gi{},Y2=class extends Gi{},$i=class extends A{},J2=class extends $i{},K2=class extends $i{},Vi=class extends A{},Z2=class extends Vi{},eC=class extends Vi{},hn=class extends A{},tC=class extends hn{},rC=class extends hn{async _call(e){return new We(await super._call(e))}},nC=class extends hn{async _call(e){return new ne(await super._call(e))}},sC=class extends hn{async _call(e){return new $e(await super._call(e))}},aC=class extends hn{async _call(e){return new it(await super._call(e))}},oC=4299n,uf=6561n,Vp=class extends A{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"]},Up=class extends Vp{async encode_speech(e){return ye(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:o=null,generation_config:i=null,logits_processor:l=null,audio_features:u=null,audio_tokens:d=null,speaker_embeddings:f=null,speaker_features:_=null,...g}){let w;if(!a){const x=this.sessions.embed_tokens.inputNames,b={input_ids:e};if(x.includes("exaggeration")){if(!(n instanceof U)){const k=e.dims[0];if(n==null)n=st([k],.5);else if(typeof n=="number")n=st([k],n);else if(Array.isArray(n))n=new U("float32",n,[k]);else throw new Error("Unsupported type for `exaggeration` input")}b.exaggeration=n}if(x.includes("position_ids")&&(b.position_ids=s),{inputs_embeds:a}=await ye(this.sessions.embed_tokens,b),u&&d&&f&&_&&(w={audio_features:u,audio_tokens:d,speaker_embeddings:f,speaker_features:_}),w||r)w??=await this.encode_speech(r),a=Ne([w.audio_features,a],1),t=dt([a.dims[0],a.dims[1]]);else{const k=a.dims[1];if(!o||k!==1)throw new Error("Incorrect state encountered during generation.");const C=o.get_seq_length();t=dt([a.dims[0],C+k])}}return{...await tr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...w}}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(o=>o==uf)-1);t.position_ids=new U("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=uf?0:o++)});t.position_ids=new U("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),Vn(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]),o=st([a.dims[0],3],oC),i=Ne([r,a,o],1),{waveform:l}=await ye(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:s,speaker_embeddings:n});return l}},jp=class extends A{},iC=class extends jp{},qp=class extends A{},lC=class extends qp{},sa=class extends A{},cC=class extends sa{},Wp=class extends sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Hp=class extends sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},zr=class extends A{},uC=class extends zr{},dC=class extends zr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Qp=class extends zr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},hC=class extends zr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},fC=class extends zr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ui=class extends A{},_C=class extends Ui{},pC=class extends Ui{},ji=class extends A{},mC=class extends ji{},gC=class extends ji{},qi=class extends A{},wC=class extends qi{},vC=class extends qi{},Wi=class extends A{},yC=class extends Wi{},MC=class extends Wi{},Hi=class extends A{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},bC=class extends Hi{},xC=class extends Hi{},fn=class extends A{},TC=class extends fn{},kC=class extends fn{async _call(e){return new We(await super._call(e))}},EC=class extends fn{async _call(e){return new ne(await super._call(e))}},CC=class extends fn{async _call(e){return new $e(await super._call(e))}},AC=class extends fn{async _call(e){return new it(await super._call(e))}},Qi=class extends A{},SC=class extends Qi{},PC=class extends Qi{async _call(e){return new ne(await super._call(e))}},Xi=class extends A{},FC=class extends Xi{},LC=class extends Xi{async _call(e){return new ne(await super._call(e))}},Yi=class extends A{},IC=class extends Yi{},OC=class extends Yi{async _call(e){return new Yn(await super._call(e))}},Yn=class extends qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ji=class extends A{},NC=class extends Ji{},DC=class extends Ji{async _call(e){return new Yn(await super._call(e))}},Xp=class extends qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},Yp=class extends qe{constructor({audio_values:e}){super(),this.audio_values=e}},aa=class extends A{main_input_name="input_values";forward_params=["input_values"]},zC=class extends aa{async encode(e){return new Xp(await ye(this.sessions.encoder_model,e))}async decode(e){return new Yp(await ye(this.sessions.decoder_model,e))}},Jp=class extends aa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Kp=class extends aa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},_n=class extends A{},BC=class extends _n{},RC=class extends _n{async _call(e){return new We(await super._call(e))}},GC=class extends _n{async _call(e){return new ne(await super._call(e))}},$C=class extends _n{async _call(e){return new $e(await super._call(e))}},VC=class extends _n{async _call(e){return new it(await super._call(e))}},Ki=class extends A{},UC=class extends Ki{},jC=class extends Ki{},pn=class extends A{},qC=class extends pn{},WC=class extends pn{async _call(e){return new We(await super._call(e))}},HC=class extends pn{async _call(e){return new ne(await super._call(e))}},QC=class extends pn{async _call(e){return new $e(await super._call(e))}},XC=class extends pn{async _call(e){return new it(await super._call(e))}},Zp=class extends A{},YC=class extends Zp{},Zi=class extends A{},JC=class extends Zi{},KC=class extends Zi{async _call(e){return new ne(await super._call(e))}},em=class extends A{},ZC=class extends em{},tm=class extends A{},eA=class extends tm{},oa=class extends A{},tA=class extends oa{},rA=class extends oa{async _call(e){return new el(await super._call(e))}},nA=class extends oa{async _call(e){return new rm(await super._call(e))}},el=class extends qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},rm=class extends qe{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},tl=class extends A{},sA=class extends tl{},aA=class extends tl{async _call(e){return new ne(await super._call(e))}},rl=class extends A{},oA=class extends rl{},iA=class extends rl{async _call(e){return new ne(await super._call(e))}},nm=class extends A{},lA=class extends nm{},sm=class extends A{},cA=class extends sm{},mn=class extends A{},uA=class extends mn{},dA=class extends mn{async _call(e){return new ne(await super._call(e))}},hA=class extends mn{async _call(e){return new $e(await super._call(e))}},fA=class extends mn{async _call(e){return new it(await super._call(e))}},_A=class extends mn{async _call(e){return new We(await super._call(e))}},am=class extends A{},pA=class extends am{},nl=class extends A{},mA=class extends nl{},gA=class extends nl{},sl=class extends A{},wA=class extends sl{},vA=class extends sl{async _call(e){return new ne(await super._call(e))}},gn=class extends A{},yA=class extends gn{},MA=class extends gn{async _call(e){return new We(await super._call(e))}},bA=class extends gn{async _call(e){return new ne(await super._call(e))}},xA=class extends gn{async _call(e){return new $e(await super._call(e))}},TA=class extends gn{async _call(e){return new it(await super._call(e))}},al=class extends A{},kA=class extends al{},EA=class extends al{},Jn=class extends A{},CA=class extends Jn{},AA=class extends Jn{async _call(e){return new We(await super._call(e))}},SA=class extends Jn{async _call(e){return new ne(await super._call(e))}},PA=class extends Jn{async _call(e){return new $e(await super._call(e))}},Kn=class extends A{},FA=class extends Kn{},LA=class extends Kn{async _call(e){return new We(await super._call(e))}},IA=class extends Kn{async _call(e){return new ne(await super._call(e))}},OA=class extends Kn{async _call(e){return new $e(await super._call(e))}},ol=class extends A{},NA=class extends ol{},DA=class extends ol{},il=class extends A{},zA=class extends il{},BA=class extends il{},ll=class extends A{},RA=class extends ll{},GA=class extends ll{},cl=class extends A{},$A=class extends cl{},VA=class extends cl{async _call(e){return new ne(await super._call(e))}},om=class extends A{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"},UA=class extends om{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Ne([t,e],1),attention_mask:Ne([dt(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:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:d}=await wr(this,{inputs_embeds:i,attention_mask:r});a=d}if(!l){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}return await tr(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},ul=class extends A{},jA=class extends ul{},qA=class extends ul{},dl=class extends A{},WA=class extends dl{},HA=class extends dl{},im=class extends A{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},rr=class extends im{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Ii({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},QA=class extends rr{},XA=class extends rr{},lm=class extends A{},YA=class extends lm{},cm=class extends rr{},JA=class extends cm{},um=class extends A{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},ia=class extends um{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:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,...f}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await ye(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:g}=await this._encode_vision({pixel_values:r,...f});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){const{audio_features:g}=await ye(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await tr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:u,logits_processor:d},!0)}_encode_vision(e){return ye(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 Ii({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 $p({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},KA=class extends ia{},hl=class extends ia{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 ye(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},ZA=class extends hl{},fl=class extends A{},eS=class extends fl{},tS=class extends fl{},_l=class extends A{},rS=class extends _l{},nS=class extends _l{},dm=class extends A{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},pl=class extends dm{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){const{data:r,dims:n}=Rp(t),s=BigInt64Array.from({length:3*r.length},(o,i)=>r[i%r.length]),a=Array.from({length:n[0]},(o,i)=>je(r.subarray(n[1]*i,n[1]*(i+1)))[0]+1n+BigInt(n[1]));return[new U("int64",s,[3,...n]),new U("int64",a,[a.length,1])]}else{const[r,n]=e.dims,s=BigInt64Array.from({length:3*r*n},(a,o)=>BigInt(Math.floor(o%n/r)));return[new U("int64",s,[3,...e.dims]),G_([r,1])]}}_reorder_and_write_positions(e,t,r,n){const s=e.reduce((l,u)=>l+u.length,0),a=new Array(s);let o=0;for(let l=0;l<3;++l)for(const u of e){const d=u.length/3;for(let f=l*d;f<(l+1)*d;++f)a[o++]=u[f]}let i=0;for(let l=0;l(k==i&&b.push(C),b),[]).map(b=>l[b+1]),f=d.filter(b=>b==a).length,_=d.filter(b=>b==o).length,g=[];let w=0,v=f,x=_;for(let b=0;bW>w&&B==a),C=l.findIndex((B,W)=>W>w&&B==o),E=v>0&&k!==-1?k:l.length+1,P=x>0&&C!==-1?C:l.length+1;let z,M,V,R;E0?je(g.at(-1))[0]+1:0;g.push(Array.from({length:3*O},(B,W)=>I+W%O));const $=O+I,H=q*K*Q,ee=Array.from({length:H},(B,W)=>$+Math.floor(W/(K*Q))),L=Array.from({length:H},(B,W)=>$+Math.floor(W/Q)%K),N=Array.from({length:H},(B,W)=>$+W%Q);g.push([ee,L,N].flat()),w=z+H}if(w0?je(g.at(-1))[0]+1:0,k=l.length-w;g.push(Array.from({length:3*k},(C,E)=>b+E%k))}return g}get_rope_index(e,t,r,n){const{vision_config:s}=this.config,a=s.spatial_merge_size??2;if(t||r){const o=e.tolist();n||(n=R_(e));const i=n.tolist(),l=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),u=t?t.tolist():[],d=r?r.tolist():[],f={image_index:0,video_index:0},_=[];for(let g=0;gi[g][k]==1),v=this._get_multimodal_rope_positions({filtered_ids:w,image_grid_thw_list:u,video_grid_thw_list:d,spatial_merge_size:a,state:f}),x=this._reorder_and_write_positions(v,i[g],l,g);_.push(je(x)[0]+1-o[g].length)}return[new U("int64",l.flat(1/0),[3,e.dims[0],e.dims[1]]),new U("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await ye(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Ii({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+i);t.position_ids=er([o,o,o],0)}}return t}},hm=class extends pl{},ml=class extends pl{image_grid_thw_name="image_grid_thw"},fm=class extends hm{image_grid_thw_name="image_grid_thw"},sS=class extends ml{get_vision_position_ids(e,t,r,n){const s=Math.floor(t[0]/r),a=Math.floor(t[1]/n),o=Math.floor(t[2]/n),i=a*o*s,l=Array.from({length:i},()=>e),u=Array.from({length:i},(f,_)=>e+Math.floor(_/(o*s))),d=Array.from({length:i},(f,_)=>e+_%o);return[...l,...u,...d]}_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,o=[];let i=0,l=e[0]==a?1:0;for(let f=1;f<=e.length;++f){const _=fu+x%w)),u+=w}else{const w=t[s.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(u,w,v,n)),u+=Math.max(w[1],w[2])/n}return d}},gl=class extends A{},aS=class extends gl{},oS=class extends gl{},wl=class extends A{},iS=class extends wl{},lS=class extends wl{},vl=class extends A{},cS=class extends vl{},uS=class extends vl{},yl=class extends A{},dS=class extends yl{},hS=class extends yl{},Ml=class extends A{},fS=class extends Ml{},_S=class extends Ml{},bl=class extends A{},pS=class extends bl{},mS=class extends bl{},xl=class extends A{},gS=class extends xl{},wS=class extends xl{},Tl=class extends A{},vS=class extends Tl{},yS=class extends Tl{},kl=class extends A{},MS=class extends kl{},bS=class extends kl{},_m=class extends A{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},El=class extends _m{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return $p({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},xS=class extends El{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},pm=class extends A{},TS=class extends pm{},mm=class extends A{},kS=class extends mm{},Cl=class extends A{},ES=class extends Cl{},CS=class extends Cl{},Al=class extends A{},AS=class extends Al{},SS=class extends Al{async _call(e){return new ne(await super._call(e))}},vr=class extends A{},PS=class extends vr{},FS=class extends vr{async _call(e){return new Dr(await super._call(e))}},LS=class extends vr{async _call(e){return new ne(await super._call(e))}},IS=class extends vr{async _call(e){return new $e(await super._call(e))}},OS=class extends A{},NS=class extends vr{},DS=class extends vr{async _call(e){return new Dr(await super._call(e))}},zS=class extends vr{async _call(e){return new ne(await super._call(e))}},Sl=class extends A{},BS=class extends Sl{},RS=class extends Sl{},gm=class extends rr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},Pl=class extends A{},GS=class extends Pl{},$S=class extends Pl{async _call(e){return new ne(await super._call(e))}},Fl=class extends A{},VS=class extends Fl{},US=class extends Fl{},la=class extends A{},jS=class extends la{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=dt([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=st([0,3,l,l],0)}const{text_embeddings:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=n,i.l2norm_text_embeddings=a),r||(i.image_embeddings=s,i.l2norm_image_embeddings=o),i}},wm=class extends la{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},qS=class extends la{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ll=class extends A{},WS=class extends Ll{},HS=class extends Ll{},QS=class extends rr{},Il=class extends A{},XS=class extends Il{},YS=class extends Il{},JS=class extends rr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},Ol=class extends A{},KS=class extends Ol{},ZS=class extends Ol{},vm=class extends A{},eP=class extends vm{},Nl=class extends A{},tP=class extends Nl{},rP=class extends Nl{},Dl=class extends A{},nP=class extends Dl{},sP=class extends Dl{},zl=class extends A{},aP=class extends zl{},oP=class extends zl{},Bl=class extends A{},iP=class extends Bl{},lP=class extends Bl{},Zn=class extends A{},cP=class extends Zn{},uP=class extends Zn{},dP=class extends Zn{async _call(e){return new ne(await super._call(e))}},hP=class extends Zn{},ym=class extends A{},fP=class extends ym{},Mm=class extends A{},_P=class extends Mm{},bm=class extends qe{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]}},xm=class extends A{},pP=class extends xm{async _call(e){return new bm(await super._call(e))}},Tm=class extends qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},km=class extends qe{constructor({audio_values:e}){super(),this.audio_values=e}},ca=class extends A{main_input_name="input_values";forward_params=["input_values"]},mP=class extends ca{async encode(e){return new Tm(await ye(this.sessions.encoder_model,e))}async decode(e){return new km(await ye(this.sessions.decoder_model,e))}},Em=class extends ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Cm=class extends ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Rl=class extends A{},gP=class extends Rl{},wP=class extends Rl{},Gl=class extends A{},vP=class extends Gl{},yP=class extends Gl{},es=class extends A{},MP=class extends es{},bP=class extends es{async _call(e){return new We(await super._call(e))}},xP=class extends es{async _call(e){return new ne(await super._call(e))}},TP=class extends es{async _call(e){return new it(await super._call(e))}},$l=class extends A{},kP=class extends $l{},EP=class extends $l{},ua=class extends A{},CP=class extends ua{},AP=class extends ua{async _call(e){return new ne(await super._call(e))}},SP=class extends ua{},da=class extends A{},PP=class extends da{},FP=class extends da{async _call(e){return new ne(await super._call(e))}},LP=class extends da{},ha=class extends A{},IP=class extends ha{},OP=class extends ha{async _call(e){return new ne(await super._call(e))}},NP=class extends ha{},fa=class extends A{},DP=class extends fa{},zP=class extends fa{async _call(e){return new ne(await super._call(e))}},BP=class extends fa{},Vl=class extends A{},RP=class extends Vl{},GP=class extends Vl{async _call(e){return new ne(await super._call(e))}},Ul=class extends A{},$P=class extends Ul{},VP=class extends Ul{async _call(e){return new ne(await super._call(e))}},ts=class extends A{},UP=class extends ts{},jP=class extends ts{async _call(e){return new We(await super._call(e))}},qP=class extends ts{async _call(e){return new ne(await super._call(e))}},WP=class extends ts{async _call(e){return new $e(await super._call(e))}},jl=class extends A{},HP=class extends jl{},QP=class extends jl{},ql=class extends A{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},XP=class extends ql{},YP=class extends ql{},wn=class extends A{},JP=class extends wn{},KP=class extends wn{async _call(e){return new We(await super._call(e))}},ZP=class extends wn{async _call(e){return new ne(await super._call(e))}},eF=class extends wn{async _call(e){return new $e(await super._call(e))}},tF=class extends wn{async _call(e){return new it(await super._call(e))}},Wl=class extends A{},rF=class extends Wl{},nF=class extends Wl{},Hl=class extends A{},sF=class extends Hl{},aF=class extends Hl{},Am=class extends A{},oF=class extends Am{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 i=this.sessions.prepare_inputs_embeds,l=Ze(e,i.inputNames);r=await ye(i,l)}else{const i=this.sessions.gen_img_embeds,l=Ze({image_ids:e.input_ids},i.inputNames);r=await ye(i,l)}const n={...e,...r},s=await tr(this,n),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);const o=await ye(a,Ze(s,a.inputNames));return{...r,...s,...o}}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=Ne([t.input_ids,t.input_ids],0):(t.input_ids=Ne([t.input_ids,Ro(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=Ne([t.attention_mask,Ro(t.attention_mask,0n)],0))),(n||!t.pixel_values)&&(t.pixel_values=st([0,0,3,384,384],1)),n&&(t.images_seq_mask=new U("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new U("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 ye(s,{generated_tokens:n}),o=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const l of o){const u=qn.fromTensor(l);i.push(u)}return i}},Ql=class extends A{},iF=class extends Ql{},lF=class extends Ql{},Sm=class extends A{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 l=0;l0&&f<=s&&(e.data[a++]=e.data[l])}const o=Math.floor(t/n),i=a/(o*n);return new U(e.type,e.data.slice(0,a),[o,n,i])}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=o&&(s[a][o]=n);return r.guidance_scale!==null&&r.guidance_scale>1&&(s=s.concat(s)),Ws(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 ye(this.sessions.encodec_decode,{audio_codes:r});return n}},Xl=class extends A{},cF=class extends Xl{},uF=class extends Xl{},Yl=class extends A{},dF=class extends Yl{},hF=class extends Yl{},vn=class extends A{},fF=class extends vn{},_F=class extends vn{async _call(e){return new We(await super._call(e))}},pF=class extends vn{async _call(e){return new ne(await super._call(e))}},mF=class extends vn{async _call(e){return new $e(await super._call(e))}},gF=class extends vn{async _call(e){return new it(await super._call(e))}},Pm=class extends A{},wF=class extends Pm{},Jl=class extends A{},vF=class extends Jl{},yF=class extends Jl{},Kl=class extends A{},MF=class extends Kl{},bF=class extends Kl{},Zl=class extends A{},xF=class extends Zl{},TF=class extends Zl{},ec=class extends A{},kF=class extends ec{},EF=class extends ec{},tc=class extends A{},CF=class extends tc{},AF=class extends tc{async _call(e){return new ne(await super._call(e))}},rc=class extends A{},SF=class extends rc{},PF=class extends rc{},nc=class extends A{},FF=class extends nc{},LF=class extends nc{},sc=class extends A{},IF=class extends sc{},OF=class extends sc{},ac=class extends A{},NF=class extends ac{},DF=class extends ac{},zF=class extends rr{},Fm=class extends A{},BF=class extends Fm{async _call(e){return new Dr(await super._call(e))}},oc=class extends A{},RF=class extends oc{},GF=class extends oc{},ic=class extends A{},$F=class extends ic{},VF=class extends ic{},lc=class extends A{},UF=class extends lc{},jF=class extends lc{},cc=class extends A{},qF=class extends cc{},WF=class extends cc{},Lm=class extends A{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Im=class extends Lm{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:o=null,generation_config:i=null,logits_processor:l=null,...u}){if(!a){let f;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:f}=await ye(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const _=this.config.normalized_config.hidden_size;f=new U("float32",[],[0,_])}({inputs_embeds:a}=await ye(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:f}))}return await tr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l},!1)}},uc=class extends A{},HF=class extends uc{},QF=class extends uc{async _call(e){return new ne(await super._call(e))}},dc=class extends A{},XF=class extends dc{},YF=class extends dc{async _call(e){return new $e(await super._call(e))}},hc=class extends A{},JF=class extends hc{},KF=class extends hc{},fc=class extends A{},ZF=class extends fc{},eL=class extends fc{},_c=class extends A{},tL=class extends _c{},rL=class extends _c{},pc=class extends A{},nL=class extends pc{},sL=class extends pc{},mc=class extends A{},aL=class extends mc{},oL=class extends mc{},gc=class extends ml{},Om=class extends fm{},iL=class extends gc{},lL=class extends Om{},wc=class extends gc{},Nm=class extends wc{},cL=class extends wc{},uL=class extends Nm{},vc=class extends A{},dL=class extends vc{},hL=class extends vc{async _call(e){return new ne(await super._call(e))}},yc=class extends A{},fL=class extends yc{},_L=class extends yc{async _call(e){return new Dm(await super._call(e))}},Dm=class extends Yn{},yn=class extends A{},pL=class extends yn{},mL=class extends yn{async _call(e){return new We(await super._call(e))}},gL=class extends yn{async _call(e){return new ne(await super._call(e))}},wL=class extends yn{async _call(e){return new $e(await super._call(e))}},vL=class extends yn{async _call(e){return new it(await super._call(e))}},Mn=class extends A{},yL=class extends Mn{},ML=class extends Mn{async _call(e){return new We(await super._call(e))}},bL=class extends Mn{async _call(e){return new ne(await super._call(e))}},xL=class extends Mn{async _call(e){return new $e(await super._call(e))}},TL=class extends Mn{async _call(e){return new it(await super._call(e))}},Mc=class extends A{},kL=class extends Mc{},EL=class extends Mc{async _call(e){return new zm(await super._call(e))}},zm=class extends Yn{},Bm=class extends qe{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Rm=class extends A{},CL=class extends Rm{async get_image_embeddings({pixel_values:e}){return await wr(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??=dt(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 ye(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new Bm(await super._call(e))}},Gm=class extends qe{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}},$m=class extends A{},bc=class extends $m{async get_image_embeddings({pixel_values:e}){return await wr(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).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??=dt(a.slice(0,-1)),e.input_boxes??=st([a[0],0,4],0)}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=st([a[0],a[1],0],-1n),e.input_points=st([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=Ze(e,n.inputNames);return await ye(n,s)}async _call(e){return new Gm(await super._call(e))}},AL=class extends bc{},SL=class extends bc{},_a=class extends A{},PL=class extends _a{},FL=class extends _a{},LL=class extends _a{},pa=class extends A{},IL=class extends pa{},OL=class extends pa{},NL=class extends pa{},xc=class extends A{},DL=class extends xc{},Vm=class extends xc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},zL=class extends zr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Tc=class extends A{},BL=class extends Tc{},RL=class extends Tc{},GL=class extends gm{},ma=class extends A{main_input_name="input_values";forward_params=["input_values"]},$L=class extends ma{async encode(e){return await ye(this.sessions.encoder_model,e)}async decode(e){return await ye(this.sessions.decoder_model,e)}},Um=class extends ma{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},jm=class extends ma{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},kc=class extends A{},VL=class extends kc{},UL=class extends kc{},ga=class extends A{},jL=class extends ga{},qL=class extends ga{},WL=class extends ga{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await wr(this,o),u=i.dims[1]/this.config.reduction_factor,d=Math.floor(u*s),f=Math.floor(u*n),_=this.config.num_mel_bins;let g=[],w=null,v=null,x=0;for(;;){++x;const C=Dp(!!v);let E;v?E=v.output_sequence_out:E=new U("float32",new Float32Array(_),[1,1,_]);let P={use_cache_branch:C,output_sequence:E,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};Li(this,P,w),v=await ye(this.sessions.decoder_model_merged,P),w=qo(v,w);const{prob:z,spectrum:M}=v;if(g.push(M),x>=f&&(Array.from(z.data).filter(V=>V>=r).length>0||x>=d))break}const b=Ne(g),{waveform:k}=await ye(a.sessions.model,{spectrogram:b});return{spectrogram:b,waveform:k}}},HL=class extends A{main_input_name="spectrogram"},rs=class extends A{},QL=class extends rs{},XL=class extends rs{async _call(e){return new We(await super._call(e))}},YL=class extends rs{async _call(e){return new ne(await super._call(e))}},JL=class extends rs{async _call(e){return new it(await super._call(e))}},Ec=class extends A{},KL=class extends Ec{},ZL=class extends Ec{},Cc=class extends A{},eI=class extends Cc{},tI=class extends Cc{},qm=class extends A{},rI=class extends qm{},Wm=class extends A{},Hm=class extends Wm{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:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:u,durations:d}=await ye(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),f=d.div(s).mul_(a),_=i*o,g=f.data,w=Int32Array.from(g,R=>Math.ceil(R/_)),v=Math.max(...w),x=e.dims[0],b=new BigInt64Array(x*v);for(let R=0;RC*E,1),k=jn[v.type];l[v.name]=new U(v.type,new k(b),x)}const _=jn[f],g=new U(f,new _(i*df),[1,i,df]),w=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:s,enc_kv_cache:l,enc_padding_cache:g,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:w,text_hidden_size:r.hidden_size}}async function OI(e,t){const r=t.dims[2],n=Math.floor((LI+r-3)/2)+1,s=new U("int64",BigInt64Array.from({length:n},(d,f)=>BigInt(e.enc_past_seq_len+f)),[1,n]),a=e.enc_past_seq_len+n,o=dt([1,a]),{audio_embeds:i,present_padding_cache:l,...u}=await ye(e.encoder_session,{input_features:t,attention_mask:o,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=l;for(const d in u)if(d.startsWith("present.")){const f=d.replace("present","past_key_values"),_=e.enc_kv_cache[f];_?.location==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[f]=u[d]}return e.enc_past_seq_len=a,i}async function NI(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){const o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),u=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}var zI=class extends ta{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)}},tg=class extends A{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},rg=class extends tg{async forward({input_ids:e,past_key_values:t,...r}){const n=e.dims[1],s=So.get(this);s&&await NI(s,s.audio_consumed+n);const{inputs_embeds:a}=await ye(this.sessions.embed_tokens,{input_ids:e});s&&DI(s,a,n);const o={inputs_embeds:a,...r};Li(this,o,t);const i=this.sessions.decoder_model_merged,l=Ze(o,i.inputNames);return await ye(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const n=II(this,e);So.set(this,n);const s=new Op;s.push(new zI(n)),t&&s.extend(t);try{return await super.generate({...r,stopping_criteria:s})}finally{n.enc_kv_cache.dispose(),So.delete(this)}}},ya=class extends A{},BI=class extends ya{},RI=class extends ya{async _call(e){return new Dr(await super._call(e))}},GI=class extends ya{async _call(e){return new ne(await super._call(e))}},ng=class extends qe{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},bn=class extends A{},$I=class extends bn{},VI=class extends bn{async _call(e){return new Dr(await super._call(e))}},UI=class extends bn{async _call(e){return new ne(await super._call(e))}},jI=class extends bn{async _call(e){return new ng(await super._call(e))}},qI=class extends bn{async _call(e){return new $e(await super._call(e))}},sg=class extends A{},WI=class extends sg{},HI=class extends Ip{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},Oc=class extends A{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},QI=class extends Oc{},ag=class extends Oc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,HI)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const n=e.task;if(e.is_multilingual){r||(de.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${kT(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&&(de.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 U?bi(s.decoder_input_ids):s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new Uo,r.push(new r2(t,a))),t.begin_suppress_tokens&&(r??=new Uo,r.push(new Lp(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"&&de.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 o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}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,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,i=t.return_token_timestamps,l=e,u=l.dims[2],d=2,f=this.config.max_source_positions,_=d*f;let g=0;const w=[],v=[];for(;gee+H)}if(M.length>0&&M.at(-1)===o&&M.pop(),M.length===0)break;const R=M.map(H=>H>=a),q=M.length>=2&&R[M.length-1]&&!R[M.length-2],K=[];for(let H=0;H0)if(q)Q=b-g;else{const H=K.at(-1);Q=(M[H-1]-a)*d,O=H}else Q=b-g;const I=Math.floor(g/d),$=a+1500;for(let H=0;H=a&&(M[H]=Math.min(M[H]+I,$));w.push(...M.slice(0,O)),V&&v.push(...V.slice(0,O)),g+=Q}w.push(o);const x=[...n,...w];if(i){const b=new U("int64",x.map(BigInt),[1,x.length]),k=[...new Array(n.length).fill(0),...v,0],C=new U("float32",new Float32Array(k),[1,k.length]);return{sequences:b,token_timestamps:C}}return new U("int64",x.map(BigInt),[1,x.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&&de.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&&(de.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(x,b)=>Ne(o.map(k=>k[b]),2)),l=er(t.map(([x,b])=>{if(x>=i.length)throw new Error(`Layer index ${x} is out of bounds for cross attentions (length ${i.length}).`);return r?i[x].slice(null,b,null,[0,r]):i[x].slice(null,b)})).transpose(1,0,2,3),[u,d]=S1(l,-2,0,!0),f=l.clone();for(let x=0;x0?f.slice(null,null,[s,f.dims[2]],null):f,g=[yi(_,1)],w=e.sequences.dims,v=new U("float32",new Float32Array(w[0]*w[1]),w);for(let x=0;xk[R+1]-k[R]),P=Vt([1],E).map(V=>!!V),z=[];for(let V=0;V0&&M.push(z.at(-1)),v[x].data.set(M)}return v}},XI=class extends ag{},xn=class extends A{},YI=class extends xn{},JI=class extends xn{async _call(e){return new We(await super._call(e))}},KI=class extends xn{async _call(e){return new ne(await super._call(e))}},ZI=class extends xn{async _call(e){return new $e(await super._call(e))}},eO=class extends xn{async _call(e){return new it(await super._call(e))}},Tn=class extends A{},tO=class extends Tn{},rO=class extends Tn{async _call(e){return new We(await super._call(e))}},nO=class extends Tn{async _call(e){return new ne(await super._call(e))}},sO=class extends Tn{async _call(e){return new $e(await super._call(e))}},aO=class extends Tn{async _call(e){return new it(await super._call(e))}},Nc=class extends A{},oO=class extends Nc{},iO=class extends Nc{async _call(e){return new og(await super._call(e))}},og=class extends qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Dc=class extends A{},lO=class extends Dc{},cO=class extends Dc{},uO=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"]]),dO=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"]]),hO=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),fO=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"]]),ig=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),lg=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),cg=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),ug=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"]]),dg=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"]]),hg=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),fg=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"]]),_O=new Map([["multi_modality","MultiModalityCausalLM"]]),_g=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"]]),pg=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"]]),mg=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),gg=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"]]),wg=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),pO=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),vg=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"]]),yg=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Mg=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),en=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),bg=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),xg=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Tg=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),kg=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Eg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Cg=new Map([["wavlm","WavLMForXVector"]]),Ag=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),Sg=new Map([["vitmatte","VitMatteForImageMatting"]]),mO=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),Pg=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),Fg=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),Lg=new Map([["sapiens","SapiensForNormalEstimation"]]),Ig=new Map([["vitpose","VitPoseForPoseEstimation"]]),Og=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),Ng=[[uO,j.EncoderOnly],[dO,j.EncoderDecoder],[fO,j.DecoderOnlyWithoutHead],[hO,j.AutoEncoder],[ug,j.EncoderOnly],[dg,j.EncoderOnly],[hg,j.Seq2Seq],[ig,j.Seq2Seq],[fg,j.DecoderOnly],[_O,j.MultiModality],[_g,j.EncoderOnly],[pg,j.EncoderOnly],[mg,j.Vision2Seq],[gg,j.ImageTextToText],[wg,j.AudioTextToText],[vg,j.EncoderOnly],[en,j.EncoderOnly],[xg,j.EncoderOnly],[bg,j.EncoderOnly],[Sg,j.EncoderOnly],[mO,j.EncoderOnly],[Pg,j.EncoderOnly],[Fg,j.EncoderOnly],[Lg,j.EncoderOnly],[Ig,j.EncoderOnly],[yg,j.EncoderOnly],[Mg,j.EncoderOnly],[Tg,j.MaskGeneration],[kg,j.EncoderOnly],[Eg,j.EncoderOnly],[lg,j.Seq2Seq],[cg,j.EncoderOnly],[Cg,j.EncoderOnly],[Ag,j.EncoderOnly],[Og,j.EncoderOnly]];for(const[e,t]of Ng)for(const r of e.values()){Zt.set(r,t);const n=Oi[r];sn.set(n,r),Fi.set(r,n)}var gO=[["MusicgenForConditionalGeneration",Sm,j.Musicgen],["Phi3VForCausalLM",Im,j.Phi3V],["CLIPTextModelWithProjection",Qp,j.EncoderOnly],["SiglipTextModel",Vm,j.EncoderOnly],["JinaCLIPTextModel",wm,j.EncoderOnly],["ClapTextModelWithProjection",Wp,j.EncoderOnly],["ClapAudioModelWithProjection",Hp,j.EncoderOnly],["DacEncoderModel",Jp,j.EncoderOnly],["DacDecoderModel",Kp,j.EncoderOnly],["MimiEncoderModel",Em,j.EncoderOnly],["MimiDecoderModel",Cm,j.EncoderOnly],["SnacEncoderModel",Um,j.EncoderOnly],["SnacDecoderModel",jm,j.EncoderOnly],["Gemma3nForConditionalGeneration",ia,j.ImageAudioTextToText],["Gemma4ForConditionalGeneration",hl,j.ImageAudioTextToText],["SupertonicForConditionalGeneration",Hm,j.Supertonic],["ChatterboxModel",Up,j.Chatterbox],["VoxtralRealtimeForConditionalGeneration",rg,j.VoxtralRealtime]];for(const[e,t,r]of gO)Zt.set(e,r),sn.set(t,e),Fi.set(e,t);var Dg=new Map([["modnet",en],["birefnet",en],["isnet",en],["ben",en]]);for(const[e,t]of Dg.entries())t.set(e,"PreTrainedModel"),Zt.set(e,j.EncoderOnly),Fi.set(e,A);var wO=new Set(Dg.keys());Zt.set("PreTrainedModel",j.EncoderOnly);sn.set(A,"PreTrainedModel");var Ee={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:ug,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:dg,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:lg,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:cg,MODEL_FOR_MASKED_LM_MAPPING_NAMES:_g,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:pg,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:vg,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:en,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:bg,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:xg,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:yg,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Mg,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Tg,MODEL_FOR_CTC_MAPPING_NAMES:kg,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Eg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Cg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Ag,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:pO,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:Sg,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:Pg,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:Fg,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:Lg,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:Ig,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:Og,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:gg,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:wg,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:hg,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:ig,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:fg,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:mg};y2(Ee);var Ce=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:o=null,subfolder:i="onnx",device:l=null,dtype:u=null,use_external_data_format:d=null,session_options:f={}}={}){const _={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:u,use_external_data_format:d,session_options:f};if(_.config=await qs.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const{model_type:g}=_.config;for(const w of this.MODEL_CLASS_MAPPINGS){let v=w.get(g);if(!v){for(const x of w.values())if(x[0]===g){v=x;break}if(!v)continue}return await Oi[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return wO.has(g)||de.warn(`Unknown model class "${g}", attempting to construct from base class.`),await A.from_pretrained(e,_);throw Error(`Unsupported model type: ${g}`)}};(class extends Ce{static MODEL_CLASS_MAPPINGS=Ng.map(e=>e[0]);static BASE_IF_FAIL=!0});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]});var vO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_MASKED_LM_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_CTC_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ee.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});ue.IS_PROCESS_AVAILABLE;pe.allowRemoteModels=!1;pe.allowLocalModels=!0;pe.localModelPath="/model/";const hf="moxhi",yO=2;async function xO({device:e,dtype:t,sources:r,batchSize:n,onStatus:s=()=>{}}){s(`loading ${e}/${t} ...`);const a=performance.now(),o=await ke.from_pretrained(hf),i=await vO.from_pretrained(hf,{device:e,dtype:t}),l=performance.now()-a;s(`loaded in ${l.toFixed(0)}ms; translating ${r.length} in batches of ${n}`);try{const u=[];let d=0,f=0;const _=performance.now();for(let w=0;wOy(P.length))),k=await i.generate({...x,max_new_tokens:b,num_beams:1,repetition_penalty:1.2,return_dict_in_generate:!1}),[C,E]=k.dims;for(let P=0;P=0&&(z=z.slice(0,M+1)),d+=z.length-1,u.push(o.decode(z,{skip_special_tokens:!0}).trim())}f+=v.reduce((P,z)=>P+z.length,0),s(`batch ${w/n+1}: ${d} tokens so far`)}const g=performance.now()-_;return{loadMs:l,translateMs:g,tokens:d,tokPerSec:d/g*1e3,charsPerSec:f/g*1e3,texts:u}}finally{try{for(const u of Object.values(i?.sessions??{}))await u?.release?.()}catch{}try{await i?.dispose?.()}catch{}}}export{xO as runReference};