@infekted11/stillnote 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +109 -2
- package/bin/stillnote.cjs +25 -0
- package/dist/assets/index-KzrG6n7D.css +1 -0
- package/dist/assets/index-SyIZ-CG1.js +4483 -0
- package/dist/assets/ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm +0 -0
- package/dist/assets/pdf-q-5ow4VI.js +57 -0
- package/dist/assets/pdf.worker.min-DDoUyrVu.js +1 -0
- package/dist/assets/pdf.worker.min-Dkey6ZUl.mjs +27 -0
- package/dist/assets/whisper-worker-DcYN39bN.js +44 -0
- package/dist/english-words-LICENSE.txt +104 -0
- package/dist/english-words-SOURCE.txt +8 -0
- package/dist/english-words.txt +109902 -0
- package/dist/index.html +14 -0
- package/dist/vendor/license.occt-import-js.txt +504 -0
- package/dist/vendor/license.occt.txt +502 -0
- package/dist/vendor/occt-import-js.js +19 -0
- package/dist/vendor/occt-import-js.wasm +0 -0
- package/electron/main.cjs +747 -0
- package/electron/preload.cjs +50 -0
- package/main-logo.icns +0 -0
- package/package.json +97 -4
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
var iB=Object.defineProperty;var Dy=De=>{throw TypeError(De)};var lB=(De,We,nt)=>We in De?iB(De,We,{enumerable:!0,configurable:!0,writable:!0,value:nt}):De[We]=nt;var T=(De,We,nt)=>lB(De,typeof We!="symbol"?We+"":We,nt),zy=(De,We,nt)=>We.has(De)||Dy("Cannot "+nt);var pt=(De,We,nt)=>(zy(De,We,"read from private field"),nt?nt.call(De):We.get(De)),No=(De,We,nt)=>We.has(De)?Dy("Cannot add the same private member more than once"):We instanceof WeakSet?We.add(De):We.set(De,nt),Do=(De,We,nt,qs)=>(zy(De,We,"write to private field"),qs?qs.call(De,nt):We.set(De,nt),nt);(function(){"use strict";/*!
|
|
2
|
+
* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0
|
|
3
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
|
+
* Licensed under the MIT License.
|
|
5
|
+
*/var mw,gw,As,Ru,Cs,_t,ww,vw,$u,Ss,ao,Ps,oo,io,Wn,sn,Fs,Gu,Is,lo,Ls,Os,co,uo,Ns,ho,fo,_o,Ds,po,zs,Vu,Uu,mo,Bs,Rs,$s,go,wo,vo,yo,bo,ju,Wu,qu,Hu,Qu,Xu,Yu,Ju,Ku,Zu,ed,td,rd,nd,sd,ad,od,id,ld,cd,ud,dd,hd,fd,_d,pd,md,gd,wd,vd;var De=Object.defineProperty,We=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyNames,qs=Object.prototype.hasOwnProperty,Uy=(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')}),ge=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}},Jn=(e,t)=>{for(var r in t)De(e,r,{get:t[r],enumerable:!0})},jy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nt(t))!qs.call(e,s)&&s!==r&&De(e,s,{get:()=>t[s],enumerable:!(n=We(t,s))||n.enumerable});return e},Hs=e=>jy(De({},"__esModule",{value:!0}),e),Kn,Tr,Ur,Xd,Yd,Jd=ge(()=>{"use strict";Kn=new Map,Tr=[],Ur=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=Kn.get(e);if(n===void 0)Kn.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=Tr.indexOf(e);s!==-1&&Tr.splice(s,1);for(let a=0;a<Tr.length;a++)if(Kn.get(Tr[a]).priority<=r){Tr.splice(a,0,e);return}Tr.push(e)}return}throw new TypeError("not a valid backend")},Xd=async e=>{let t=Kn.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}}},Yd=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?Tr:r,s,a=[],o=new Set;for(let l of n){let c=await Xd(l);typeof c=="string"?a.push({name:l,err:c}):(s||(s=c),s===c&&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:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Wy=ge(()=>{"use strict";Jd()}),Kd,qy=ge(()=>{"use strict";Kd="1.31.0-dev.20260911-2a43ec07e"}),zo,tt,Zd=ge(()=>{"use strict";qy(),zo="warning",tt={wasm:{},webgl:{},webgpu:{},versions:{common:Kd},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}`);zo=e}},get logLevel(){return zo}},Object.defineProperty(tt,"logLevel",{enumerable:!0})}),$e,Hy=ge(()=>{"use strict";Zd(),$e=tt}),eh,th,Qy=ge(()=>{"use strict";eh=(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==null?void 0: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==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm,l,c;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?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*s,h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<s;y++){let x=(e.data[h++]-c[0])*l[0],k=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],S=w===-1?255:(e.data[w++]-c[3])*l[3];n.fillStyle="rgba("+x+","+k+","+A+","+S+")",n.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},th=(e,t)=>{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==null?void 0: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==null?void 0:t.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[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 h=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,p=0,w=1,v=2,y=3,x=0,k=h,A=h*2,S=-1;i==="RGBA"?(x=0,k=h,A=h*2,S=h*3):i==="RGB"?(x=0,k=h,A=h*2):i==="RBG"&&(x=0,A=h,k=h*2),n=r.createImageData(s,a);for(let C=0;C<a*s;p+=_,w+=_,v+=_,y+=_,C++)n.data[p]=(e.data[x++]-d[0])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[y]=S===-1?255:(e.data[S++]-d[3])*c[3]}else throw new Error("Can not access image data");return n}}),Qs,rh,nh,sh,ah,oh,Xy=ge(()=>{"use strict";Ro(),Qs=(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",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,v=3,y=0,x=c,k=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,k=c,x=c*2):l==="BGR"&&(k=0,x=c,y=c*2);for(let S=0;S<c;S++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[x++]=(e[p]+o[1])/a[1],d[k++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new kt("float32",d,[1,4,r,n]):new kt("float32",d,[1,3,r,n])},rh=async(e,t)=>{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")},c=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 h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=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=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let _=l();_.width=h,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,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 h=c(d);if(h!=null){let _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,Qs(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{let _=l(),p=c(_);if(!e||!p)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);let v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(Qs(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Qs(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},nh=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new kt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},sh=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new kt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},ah=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new kt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},oh=(e,t,r)=>new kt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),jr,Zn,Bo,ih,Yy=ge(()=>{"use strict";jr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Zn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Bo=!1,ih=()=>{if(!Bo){Bo=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(jr.set("int64",BigInt64Array),Zn.set(BigInt64Array,"int64")),t&&(jr.set("uint64",BigUint64Array),Zn.set(BigUint64Array,"uint64")),n?(jr.set("float16",r),Zn.set(r,"float16")):jr.set("float16",Uint16Array)}}}),lh,ch,Jy=ge(()=>{"use strict";Ro(),lh=e=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},ch=(e,t)=>{switch(e.location){case"cpu":return new kt(e.type,e.data,t);case"cpu-pinned":return new kt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new kt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new kt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new kt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),kt,Ro=ge(()=>{"use strict";Qy(),Xy(),Yy(),Jy(),kt=class{constructor(e,t,r){ih();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=jr.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=jr.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=Zn.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=lh(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 rh(e,t)}static fromTexture(e,t){return nh(e,t)}static fromGpuBuffer(e,t){return sh(e,t)}static fromMLTensor(e,t){return ah(e,t)}static fromPinnedBuffer(e,t,r){return oh(e,t,r)}toDataURL(e){return eh(this,e)}toImageData(e){return th(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 ch(this,e)}}}),Bt,uh=ge(()=>{"use strict";Ro(),Bt=kt}),Xs,$o,Wr,qr,Er,Ar,dh=ge(()=>{"use strict";Zd(),Xs=(e,t)=>{(typeof tt.trace>"u"?!tt.wasm.trace:!tt.trace)||console.timeStamp(`${e}::ORT::${t}`)},$o=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a<r.length;a++){if(n&&!r[a].includes("TRACE_FUNC")){let o=`FUNC_${e}::${r[a].trim().split(" ")[1]}`;t&&(o+=`::${t}`),Xs("CPU",o);return}r[a].includes("TRACE_FUNC")&&(n=!0)}},Wr=e=>{(typeof tt.trace>"u"?!tt.wasm.trace:!tt.trace)||$o("BEGIN",e)},qr=e=>{(typeof tt.trace>"u"?!tt.wasm.trace:!tt.trace)||$o("END",e)},Er=e=>{(typeof tt.trace>"u"?!tt.wasm.trace:!tt.trace)||console.time(`ORT::${e}`)},Ar=e=>{(typeof tt.trace>"u"?!tt.wasm.trace:!tt.trace)||console.timeEnd(`ORT::${e}`)}}),hh,Ky=ge(()=>{"use strict";Jd(),uh(),dh(),hh=class By{constructor(t){this.handler=t}async run(t,r,n){Wr(),Er("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Bt||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 Bt)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 c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let _=r[h];(_===null||_ instanceof Bt)&&(c=!0,o=!1,s[h]=_)}if(c){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 c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)s[c]=null;let i=await this.handler.run(t,s,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof Bt?l[c]=d:l[c]=new Bt(d.type,d.data,d.dims)}return Ar("InferenceSession.run"),qr(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Wr(),Er("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,h=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-h,typeof n=="number"){if(_=n,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);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,h,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Yd(o),c=await i.createInferenceSessionHandler(a,l);return Ar("InferenceSession.create"),qr(),new By(c)}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}}}),Go,Zy=ge(()=>{"use strict";Ky(),Go=hh}),eb=ge(()=>{"use strict"}),tb=ge(()=>{"use strict"}),rb=ge(()=>{"use strict"}),nb=ge(()=>{"use strict"}),fh={};Jn(fh,{InferenceSession:()=>Go,TRACE:()=>Xs,TRACE_EVENT_BEGIN:()=>Er,TRACE_EVENT_END:()=>Ar,TRACE_FUNC_BEGIN:()=>Wr,TRACE_FUNC_END:()=>qr,Tensor:()=>Bt,env:()=>$e,registerBackend:()=>Ur});var Hr=ge(()=>{"use strict";Wy(),Hy(),Zy(),uh(),eb(),tb(),dh(),rb(),nb()}),Vo=ge(()=>{"use strict"}),_h={};Jn(_h,{default:()=>ph});var Uo,jo,ph,sb=ge(()=>{"use strict";var e;tf(),Qr(),Yo(),Uo="ort-wasm-proxy-worker",jo=((e=globalThis.self)==null?void 0:e.name)===Uo,jo&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Zo(n.wasm).then(()=>{di(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;hi(a,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=n,a=ta(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;_i(s,a).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":pi(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:o,outputIndices:i,options:l}=n;gi(s,a,o,i,new Array(i.length).fill(null),l).then(c=>{c.some(d=>d[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:c},vi([...o,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":wi(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),ph=jo?null:t=>new Worker(t??Tt,{type:"module",name:Uo})}),mh={};Jn(mh,{default:()=>wh});async function gh(e={}){var Oy,Ny;var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&((Oy=self.name)==null?void 0:Oy.startsWith("em-pthread"));t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.ed||(t.ed=new Map)).set(u,f)},t.unmountExternalData=()=>{delete t.ed,delete t.Te,delete t.Se,delete t.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let u=f=>(...m)=>{let g=ur;return m=f(...m),ur!=g?new Promise((b,E)=>{Sd={resolve:b,reject:E}}):m};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=u(t[f])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a==null||a()};var o,i,l=(u,f)=>{throw f},c=self.location.href,d="";if(r||n){try{d=new URL(".",c).href}catch{}n&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async u=>{if(O(u))return new Promise((m,g)=>{var b=new XMLHttpRequest;b.open("GET",u,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?m(b.response):g(b.status)},b.onerror=g,b.send(null)});var f=await fetch(u,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}var h,_,p,w,v,y,x=console.log.bind(console),k=console.error.bind(console),A=x,S=k,C=!1,O=u=>u.startsWith("file://");function M(){Gr.buffer!=G.buffer&&D()}if(s){let u=function(f){try{var m=f.data,g=m.$c;if(g==="load"){let b=[];self.onmessage=E=>b.push(E),y=()=>{postMessage({$c:"loaded"});for(let E of b)u(E);self.onmessage=u};for(let E of m.ue)t[E]&&!t[E].proxy||(t[E]=(...F)=>{postMessage({$c:"callHandler",te:E,args:F})},E=="print"&&(A=t[E]),E=="printErr"&&(S=t[E]));Gr=m.Me,D(),_=m.Ne,Me(),Oo()}else if(g==="run"){(function(b){var E=(M(),L)[b+52>>>2>>>0];b=(M(),L)[b+56>>>2>>>0],Vv(E,E-b),se(E)})(m.Xc),Gd(m.Xc,0,0,1,0,0),Mw(),Ed(m.Xc),V||(xv(),V=!0);try{KN(m.ze,m.kd)}catch(b){if(b!="unwind")throw b}}else m.target!=="setimmediate"&&(g==="checkMailbox"?V&&ko():g&&(S(`worker: received unknown command ${g}`),S(m)))}catch(b){throw zv(),b}};var V=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var G,U,J,Q,B,L,ee,H,ne,Se,Y,N=!1;function D(){var u=Gr.buffer;t.HEAP8=G=new Int8Array(u),J=new Int16Array(u),t.HEAPU8=U=new Uint8Array(u),Q=new Uint16Array(u),t.HEAP32=B=new Int32Array(u),t.HEAPU32=L=new Uint32Array(u),ee=new Float32Array(u),H=new Float64Array(u),ne=new BigInt64Array(u),Se=new BigUint64Array(u)}function R(){N=!0,s?y():kr.hc()}function re(u){throw S(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v==null||v(u),u}function Z(){return{a:{qa:yz,f:ZN,K:e3,k:t3,p:r3,l:n3,fa:s3,b:a3,da:o3,gc:Cw,q:i3,ea:Iw,Ua:Lw,cc:Ow,ec:Nw,Va:Dw,Sa:zw,La:Bw,Ra:Rw,oa:$w,dc:Gw,ac:Vw,Ta:Uw,bc:jw,_a:l3,Ba:c3,Xb:u3,Vb:h3,Aa:_3,O:p3,J:m3,Wb:g3,ka:k3,Yb:T3,Oa:E3,_b:C3,Ea:S3,Tb:P3,Ca:F3,Na:Ed,Xa:I3,U:D3,n:G3,c:kd,qb:V3,w:U3,N:j3,A:W3,j:q3,o:Kw,rb:H3,H:Q3,T:X3,g:Y3,u:J3,m:K3,i:Z3,Ia:eD,Ja:tD,Ka:rD,Ga:rv,Ha:nv,Ub:sv,ab:sD,Za:oD,Z:iD,pb:lD,Da:cD,Ya:aD,X:uD,Wa:dD,$b:hD,G:nD,db:fD,_:_D,pa:So,Zb:mD,cb:pD,bb:gD,lb:PD,z:FD,sa:ID,ra:LD,nb:OD,Y:ND,v:DD,kb:zD,jb:BD,ib:RD,mb:$D,gb:GD,fb:VD,eb:UD,Pa:pv,Qa:mv,fc:lr,W:gv,Fa:wv,ma:vv,Ma:yv,la:bv,Fb:sB,va:Kz,Gb:nB,wa:Jz,E:Bz,e:kz,r:Mz,x:bz,C:Oz,Ib:Qz,ca:Hz,D:Az,xa:Xz,aa:Zz,ha:qz,Jb:Wz,Kb:jz,za:$z,Lb:Vz,ya:Uz,Mb:Gz,ua:rB,ba:Yz,d:xz,B:Ez,s:Tz,Eb:aB,t:Sz,y:Dz,F:Cz,I:Pz,L:zz,Nb:Rz,R:eB,ia:Lz,$:tB,Pb:Iz,Rb:Fz,Ob:Nz,h:WD,a:Gr,$a:Fe,Hb:qD,V:HD,M:QD,na:XD,Db:YD,ja:JD,S:KD,Ab:ZD,Bb:ez,vb:tz,wb:rz,P:nz,xb:sz,yb:az,ta:oz,Sb:iz,ob:lz,Q:cz,hb:uz,Cb:dz,sb:hz,tb:_z,ub:pz,ga:mz,zb:gz,Qb:wz}}}async function Me(){function u(g,b){var E=kr=g.exports;g={};for(let[F,P]of Object.entries(E))typeof P=="function"?(E=L3(P),g[F]=E):g[F]=P;return kr=g,kr=(function(){var F=kr,P=W=>X=>W(X)>>>0,z=W=>()=>W()>>>0;return(F=Object.assign({},F)).ic=P(F.ic),F.Nc=z(F.Nc),F.Pc=P(F.Pc),F.Bd=(W=>(X,oe)=>W(X,oe)>>>0)(F.Bd),F.Gd=P(F.Gd),F.Hd=z(F.Hd),F.Ld=P(F.Ld),F})(),yw.push(kr.sd),Mv=(g=kr).ic,xv=g.jc,t._OrtInit=g.kc,t._OrtGetLastError=g.lc,t._OrtCreateSessionOptions=g.mc,t._OrtAppendExecutionProvider=g.nc,t._OrtAddFreeDimensionOverride=g.oc,t._OrtAddSessionConfigEntry=g.pc,t._OrtReleaseSessionOptions=g.qc,t._OrtCreateSession=g.rc,t._OrtReleaseSession=g.sc,t._OrtGetInputOutputCount=g.tc,t._OrtGetInputOutputMetadata=g.uc,t._OrtFree=g.vc,t._OrtCreateTensor=g.wc,t._OrtGetTensorData=g.xc,t._OrtReleaseTensor=g.yc,t._OrtCreateRunOptions=g.zc,t._OrtAddRunConfigEntry=g.Ac,t._OrtReleaseRunOptions=g.Bc,t._OrtCreateBinding=g.Cc,t._OrtBindInput=g.Dc,t._OrtBindOutput=g.Ec,t._OrtClearBoundOutputs=g.Fc,t._OrtReleaseBinding=g.Gc,t._OrtRunWithBinding=g.Hc,t._OrtRun=g.Ic,t._OrtEndProfiling=g.Jc,kv=t._OrtCreateWebGpuInstance=g.Kc,t._wgpuCreateInstance=g.Lc,Nd=t._OrtGetWebGpuDevice=g.Mc,Io=g.Nc,zt=t._free=g.Oc,cn=t._malloc=g.Pc,Tv=t._wgpuBufferRelease=g.Qc,Ev=g.Rc,Av=g.Sc,Cv=g.Tc,Sv=g.Uc,Pv=g.Vc,Fv=g.Yc,Iv=g.Zc,Lv=g.hd,Ov=g.id,Nv=g.jd,Dd=g.ld,zd=g.md,Bd=g.nd,Rd=g.od,Us=g.pd,$d=g.qd,Dv=g.rd,Gd=g.ud,zv=g.vd,Bv=g.wd,Rv=g.xd,Vd=g.yd,$v=g.zd,Gv=g.Ad,Ud=g.Bd,_e=g.Cd,js=g.Dd,Vv=g.Ed,se=g.Fd,Lo=g.Gd,ae=g.Hd,Uv=g.Id,jd=g.Jd,jv=g.Kd,Wv=g.Ld,qv=g.Md,Wd=g.Nd,Hv=g.Od,Qv=g.Pd,Xv=g.Qd,Yv=g.Rd,Jv=g.Sd,Kv=g.Td,Zv=g.Ud,ey=g.Vd,ty=g.Wd,ry=g.Xd,ny=g.Yd,sy=g.Zd,ay=g._d,oy=g.$d,iy=g.ae,ly=g.be,cy=g.ce,uy=g.de,dy=g.fe,hy=g.ge,fy=g.he,_y=g.ie,py=g.je,my=g.ke,gy=g.le,wy=g.me,vy=g.Ae,yy=g.Be,by=g.Ce,My=g.De,xy=g.Ee,ky=g.Fe,Ty=g.Ge,Ey=g.He,Ay=g.Ie,Cy=g.Je,Sy=g.Ke,Py=g.nf,Fy=g.of,Iy=g.pf,Ly=g.qf,_=b,kr}var f,m=Z();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(m,(b,E)=>{g(u(b,E))})}):s?u(new WebAssembly.Instance(_,Z()),_):(Y??(Y=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL(""+new URL("ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm",self.location.href).href,self.location.href).href),f=await(async function(g){var b=Y;if(!h&&!O(b))try{var E=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(E,g)}catch(F){S(`wasm streaming compile failed: ${F}`),S("falling back to ArrayBuffer instantiation")}return(async function(F,P){try{var z=await(async function(W){if(!h)try{var X=await o(W);return new Uint8Array(X)}catch{}if(W==Y&&h)W=new Uint8Array(h);else{if(!i)throw"both async and sync fetching of the wasm failed";W=i(W)}return W})(F);return await WebAssembly.instantiate(z,P)}catch(W){S(`failed to asynchronously prepare wasm: ${W}`),re(W)}})(b,g)})(m),u(f.instance,f.module))}class Ne{constructor(f){T(this,"name","ExitStatus");this.message=`Program terminated with exit(${f})`,this.status=f}}var Oe=u=>{u.terminate(),u.onmessage=()=>{}},Ke=[],Ot=0,Ze=null,wt=u=>{Nt.length==0&&(kw(),xw(Nt[0]));var f=Nt.pop();if(!f)return 6;Gs.push(f),an[u.Xc]=f,f.Xc=u.Xc;var m={$c:"run",ze:u.ye,kd:u.kd,Xc:u.Xc};return f.postMessage(m,u.oe),0},be=0,ue=(u,f,...m)=>{var g,b=16*m.length,E=ae(),F=Lo(b),P=F>>>3;for(g of m)typeof g=="bigint"?((M(),ne)[P++>>>0]=1n,(M(),ne)[P++>>>0]=g):((M(),ne)[P++>>>0]=0n,(M(),H)[P++>>>0]=g);return u=Bv(u,0,b,F,f),se(E),u};function Fe(u){if(s)return ue(0,1,u);if(p=u,!(0<be)){for(var f of Gs)Oe(f);for(f of Nt)Oe(f);Nt=[],Gs=[],an={},C=!0}l(0,new Ne(u))}function vt(u){if(s)return ue(1,0,u);lr(u)}var lr=u=>{if(p=u,s)throw vt(u),"unwind";Fe(u)},Nt=[],Gs=[],yw=[],an={},bw=u=>{var f=u.Xc;delete an[f],Nt.push(u),Gs.splice(Gs.indexOf(u),1),u.Xc=0,Rv(f)};function Mw(){yw.forEach(u=>u())}var xw=u=>new Promise(f=>{u.onmessage=b=>{var E=b.data;if(b=E.$c,E.gd&&E.gd!=Io()){var F=an[E.gd];F?F.postMessage(E,E.oe):S(`Internal error! Worker sent a message "${b}" to target pthread ${E.gd}, but that thread no longer exists!`)}else b==="checkMailbox"?ko():b==="spawnThread"?wt(E):b==="cleanupThread"?yt(()=>{bw(an[E.Le])}):b==="loaded"?(u.loaded=!0,f(u)):E.target==="setimmediate"?u.postMessage(E):b==="uncaughtException"?u.onerror(E.error):b==="callHandler"?t[E.te](...E.args):b&&S(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw S(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var m,g=[];for(m of[])t.propertyIsEnumerable(m)&&g.push(m);u.postMessage({$c:"load",ue:g,Me:Gr,Ne:_})});function kw(){var u=new Worker((()=>{let f=URL;return self.location.href>"file:"&&self.location.href<"file;"?new f("ort.webgpu.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Nt.push(u)}var Gr,KN=(u,f)=>{be=0,u=Wd(u,f),0<be?p=u:Vd(u)},Mo=[],xo=0,lt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function ZN(u){var f=new yd(u>>>=0);return(M(),G)[f.ad+12>>>0]==0&&(Tw(f,!0),xo--),Ew(f,!1),Mo.push(f),Wv(u)}var qn=0,e3=()=>{_e(0,0);var u=Mo.pop();Uv(u.td),qn=0};function Tw(u,f){f=f?1:0,(M(),G)[u.ad+12>>>0]=f}function Ew(u,f){f=f?1:0,(M(),G)[u.ad+13>>>0]=f}class yd{constructor(f){this.td=f,this.ad=f-24}}var bd=u=>{var f=qn;if(!f)return js(0),0;var m=new yd(f);(M(),L)[m.ad+16>>>2>>>0]=f;var g=(M(),L)[m.ad+4>>>2>>>0];if(!g)return js(0),f;for(var b of u){if(b===0||b===g)break;if(jv(b,g,m.ad+16))return js(b),f}return js(g),f};function t3(){return bd([])}function r3(u){return bd([u>>>0])}function n3(u,f,m,g){return bd([u>>>0,f>>>0,m>>>0,g>>>0])}var s3=()=>{var u=Mo.pop();u||re("no exception to throw");var f=u.td;throw(M(),G)[u.ad+13>>>0]==0&&(Mo.push(u),Ew(u,!0),Tw(u,!1),xo++),jd(f),qn=f};function a3(u,f,m){var g=new yd(u>>>=0);throw f>>>=0,m>>>=0,(M(),L)[g.ad+16>>>2>>>0]=0,(M(),L)[g.ad+4>>>2>>>0]=f,(M(),L)[g.ad+8>>>2>>>0]=m,jd(u),xo++,qn=u}var o3=()=>xo;function Aw(u,f,m,g){return s?ue(2,1,u,f,m,g):Cw(u,f,m,g)}function Cw(u,f,m,g){if(u>>>=0,f>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return s&&b.length===0?Aw(u,f,m,g):(u={ye:m,Xc:u,kd:g,oe:b},s?(u.$c="spawnThread",postMessage(u,b),0):wt(u))}function i3(u){throw qn||(qn=u>>>0),qn}var Sw=globalThis.TextDecoder&&new TextDecoder,Pw=(u,f,m,g)=>{if(m=f+m,g)return m;for(;u[f]&&!(f>=m);)++f;return f},Fw=(u,f=0,m,g)=>{if(16<(m=Pw(u,f>>>=0,m,g))-f&&u.buffer&&Sw)return Sw.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,m):u.slice(f,m));for(g="";f<m;){var b=u[f++];if(128&b){var E=63&u[f++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|E);else{var F=63&u[f++];65536>(b=(240&b)==224?(15&b)<<12|E<<6|F:(7&b)<<18|E<<12|F<<6|63&u[f++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Hn=(u,f,m)=>(u>>>=0)?Fw((M(),U),u,f,m):"";function Iw(u,f,m){return s?ue(3,1,u,f,m):0}function Lw(u,f){if(s)return ue(4,1,u,f)}function Ow(u,f){if(s)return ue(5,1,u,f)}function Nw(u,f,m){if(s)return ue(6,1,u,f,m)}function Dw(u,f,m){return s?ue(7,1,u,f,m):0}function zw(u,f){if(s)return ue(8,1,u,f)}function Bw(u,f,m){if(s)return ue(9,1,u,f,m)}function Rw(u,f,m,g){if(s)return ue(10,1,u,f,m,g)}function $w(u,f,m,g){if(s)return ue(11,1,u,f,m,g)}function Gw(u,f,m,g){if(s)return ue(12,1,u,f,m,g)}function Vw(u){if(s)return ue(13,1,u)}function Uw(u,f){if(s)return ue(14,1,u,f)}function jw(u,f,m){if(s)return ue(15,1,u,f,m)}var l3=()=>re(""),cr=u=>{u>>>=0;for(var f="";;){var m=(M(),U)[u++>>>0];if(!m)return f;f+=String.fromCharCode(m)}},Md={},xd={},Qn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function yr(u,f,m={}){return(function(g,b,E={}){var F=b.name;if(!g)throw new Qn(`type "${F}" must have a positive integer typeid pointer`);if(xd.hasOwnProperty(g)){if(E.ve)return;throw new Qn(`Cannot register type '${F}' twice`)}xd[g]=b,Md.hasOwnProperty(g)&&(b=Md[g],delete Md[g],b.forEach(P=>P()))})(u,f,m)}var Ww=(u,f,m)=>{switch(f){case 1:return m?g=>(M(),G)[g>>>0]:g=>(M(),U)[g>>>0];case 2:return m?g=>(M(),J)[g>>>1>>>0]:g=>(M(),Q)[g>>>1>>>0];case 4:return m?g=>(M(),B)[g>>>2>>>0]:g=>(M(),L)[g>>>2>>>0];case 8:return m?g=>(M(),ne)[g>>>3>>>0]:g=>(M(),Se)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function c3(u,f,m,g,b){u>>>=0,m>>>=0,f=cr(f>>>0);let E=F=>F;if(g=g===0n){let F=8*m;E=P=>BigInt.asUintN(F,P),b=E(b)}yr(u,{name:f,Wc:E,cd:(F,P)=>(typeof P=="number"&&(P=BigInt(P)),P),bd:Ww(f,m,!g),dd:null})}function u3(u,f,m,g){yr(u>>>=0,{name:f=cr(f>>>0),Wc:function(b){return!!b},cd:function(b,E){return E?m:g},bd:function(b){return this.Wc((M(),U)[b>>>0])},dd:null})}var qw=[],on=[0,1,,1,null,1,!0,1,!1,1];function kd(u){9<(u>>>=0)&&--on[u+1]===0&&(on[u]=void 0,qw.push(u))}var Dt=u=>{if(!u)throw new Qn(`Cannot use deleted val. handle = ${u}`);return on[u]},Yt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=qw.pop()||on.length;return on[f]=u,on[f+1]=1,f}};function Td(u){return this.Wc((M(),L)[u>>>2>>>0])}var d3={name:"emscripten::val",Wc:u=>{var f=Dt(u);return kd(u),f},cd:(u,f)=>Yt(f),bd:Td,dd:null};function h3(u){return yr(u>>>0,d3)}var f3=(u,f)=>{switch(f){case 4:return function(m){return this.Wc((M(),ee)[m>>>2>>>0])};case 8:return function(m){return this.Wc((M(),H)[m>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function _3(u,f,m){m>>>=0,yr(u>>>=0,{name:f=cr(f>>>0),Wc:g=>g,cd:(g,b)=>b,bd:f3(f,m),dd:null})}function p3(u,f,m,g,b){u>>>=0,m>>>=0,f=cr(f>>>0);let E=P=>P;if(g===0){var F=32-8*m;E=P=>P<<F>>>F,b=E(b)}yr(u,{name:f,Wc:E,cd:(P,z)=>z,bd:Ww(f,m,g!==0),dd:null})}function m3(u,f,m){function g(E){var F=(M(),L)[E>>>2>>>0];return E=(M(),L)[E+4>>>2>>>0],new b((M(),G).buffer,E,F)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];yr(u>>>=0,{name:m=cr(m>>>0),Wc:g,bd:g},{ve:!0})}var br=(u,f,m)=>{var g=(M(),U);if(f>>>=0,0<m){var b=f;m=f+m-1;for(var E=0;E<u.length;++E){var F=u.codePointAt(E);if(127>=F){if(f>=m)break;g[f++>>>0]=F}else if(2047>=F){if(f+1>=m)break;g[f++>>>0]=192|F>>6,g[f++>>>0]=128|63&F}else if(65535>=F){if(f+2>=m)break;g[f++>>>0]=224|F>>12,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F}else{if(f+3>=m)break;g[f++>>>0]=240|F>>18,g[f++>>>0]=128|F>>12&63,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F,E++}}g[f>>>0]=0,u=f-b}else u=0;return u},Mr=u=>{for(var f=0,m=0;m<u.length;++m){var g=u.charCodeAt(m);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++m):f+=3}return f};function g3(u,f){yr(u>>>=0,{name:f=cr(f>>>0),Wc(m){var g=(M(),L)[m>>>2>>>0];return g=Hn(m+4,g,!0),zt(m),g},cd(m,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Qn("Cannot pass non-string to std::string");var E=b?Mr(g):g.length,F=cn(4+E+1),P=F+4;return(M(),L)[F>>>2>>>0]=E,b?br(g,P,E+1):(M(),U).set(g,P>>>0),m!==null&&m.push(zt,F),F},bd:Td,dd(m){zt(m)}})}var Hw=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,w3=(u,f,m)=>{if(u>>>=1,16<(f=Pw((M(),Q),u,f/2,m))-u&&Hw)return Hw.decode((M(),Q).slice(u,f));for(m="";u<f;++u){var g=(M(),Q)[u>>>0];m+=String.fromCharCode(g)}return m},v3=(u,f,m)=>{if(m??(m=2147483647),2>m)return 0;var g=f;m=(m-=2)<2*u.length?m/2:u.length;for(var b=0;b<m;++b){var E=u.charCodeAt(b);(M(),J)[f>>>1>>>0]=E,f+=2}return(M(),J)[f>>>1>>>0]=0,f-g},y3=u=>2*u.length,b3=(u,f,m)=>{var g="";u>>>=2;for(var b=0;!(b>=f/4);b++){var E=(M(),L)[u+b>>>0];if(!E&&!m)break;g+=String.fromCodePoint(E)}return g},M3=(u,f,m)=>{if(f>>>=0,m??(m=2147483647),4>m)return 0;var g=f;m=g+m-4;for(var b=0;b<u.length;++b){var E=u.codePointAt(b);if(65535<E&&b++,(M(),B)[f>>>2>>>0]=E,(f+=4)+4>m)break}return(M(),B)[f>>>2>>>0]=0,f-g},x3=u=>{for(var f=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,f+=4;return f};function k3(u,f,m){if(u>>>=0,f>>>=0,m=cr(m>>>=0),f===2)var g=w3,b=v3,E=y3;else g=b3,b=M3,E=x3;yr(u,{name:m,Wc:F=>{var P=(M(),L)[F>>>2>>>0];return P=g(F+4,P*f,!0),zt(F),P},cd:(F,P)=>{if(typeof P!="string")throw new Qn(`Cannot pass non-string to C++ string type ${m}`);var z=E(P),W=cn(4+z+f);return(M(),L)[W>>>2>>>0]=z/f,b(P,W+4,z+f),F!==null&&F.push(zt,W),W},bd:Td,dd(F){zt(F)}})}function T3(u,f){yr(u>>>=0,{we:!0,name:f=cr(f>>>0),Wc:()=>{},cd:()=>{}})}function E3(u){Gd(u>>>0,!n,1,!r,131072,!1),Mw()}var yt=u=>{if(!C)try{if(u(),!(0<be))try{s?Io()&&Vd(p):lr(p)}catch(f){f instanceof Ne||f=="unwind"||l(0,f)}}catch(f){f instanceof Ne||f=="unwind"||l(0,f)}},A3=!Atomics.waitAsync||((Ny=globalThis.navigator)==null?void 0:Ny.userAgent)&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ed(u){u>>>=0,A3||(Atomics.waitAsync((M(),B),u>>>2,u).value.then(ko),u+=128,Atomics.store((M(),B),u>>>2,1))}var ko=()=>yt(()=>{var u=Io();u&&(Ed(u),Gv())});function C3(u,f){(u>>>=0)==f>>>0?setTimeout(ko):s?postMessage({gd:u,$c:"checkMailbox"}):(u=an[u])&&u.postMessage({$c:"checkMailbox"})}var Ad=[];function S3(u,f,m,g,b){for(f>>>=0,b>>>=0,Ad.length=0,m=b>>>3,g=b+g>>>3;m<g;){var E;E=(M(),ne)[m++>>>0]?(M(),ne)[m++>>>0]:(M(),H)[m++>>>0],Ad.push(E)}return(f?qd[f]:vz[u])(...Ad)}var P3=()=>{be=0};function F3(u){u>>>=0,s?postMessage({$c:"cleanupThread",Le:u}):bw(an[u])}function I3(u){}var To=u=>{try{u()}catch(f){re(f)}};function L3(u){var f=(...m)=>{Eo.push(u);try{return u(...m)}finally{C||(Eo.pop(),ur&&Vr===1&&Eo.length===0&&(Vr=0,be+=1,To(Fy),typeof Fibers<"u"&&Fibers.We()))}};return Yw.set(u,f),f}var Vr=0,ur=null,Qw=0,Eo=[],Cd=new Map,Xw=new Map,Yw=new Map,O3=0,Sd=null,N3=[],Jw=u=>(function(f){if(!C){if(Vr===0){var m=!1,g=!1;f((b=0)=>{if(!C&&(Qw=b,m=!0,g)){Vr=2,To(()=>Iy(ur)),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.resume(),b=!1;try{var E=(function(){var z=(M(),B)[ur+8>>>2>>>0];return z=Xw.get(z),z=Yw.get(z),--be,z()})()}catch(z){E=z,b=!0}var F=!1;if(!ur){var P=Sd;P&&(Sd=null,(b?P.reject:P.resolve)(E),F=!0)}if(b&&!F)throw E}}),g=!0,m||(Vr=1,ur=(function(){var b=cn(65548),E=b+12;if((M(),L)[b>>>2>>>0]=E,(M(),L)[b+4>>>2>>>0]=E+65536,E=Eo[0],!Cd.has(E)){var F=O3++;Cd.set(E,F),Xw.set(F,E)}return E=Cd.get(E),(M(),B)[b+8>>>2>>>0]=E,b})(),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.pause(),To(()=>Py(ur)))}else Vr===2?(Vr=0,To(Ly),zt(ur),ur=null,N3.forEach(yt)):re(`invalid state: ${Vr}`);return Qw}})(f=>{u().then(f)});function D3(u){return u>>>=0,Jw(async()=>{var f=await Dt(u);return Yt(f)})}var Pd=[],z3=u=>{var f=Pd.length;return Pd.push(u),f},B3=(u,f)=>{for(var m=Array(u),g=0;g<u;++g){var b=g,E=(M(),L)[f+4*g>>>2>>>0],F=xd[E];if(F===void 0)throw u=`parameter ${g}`,E=Mv(E),f=cr(E),zt(E),new Qn(`${u} has unknown type ${f}`);m[b]=F}return m},R3=(u,f,m)=>{var g=[];return u=u(g,m),g.length&&((M(),L)[f>>>2>>>0]=Yt(g)),u},$3={},Ao=u=>{var f=$3[u];return f===void 0?cr(u):f};function G3(u,f,m){var[g,...b]=B3(u,f>>>0);f=g.cd.bind(g);var E=b.map(z=>z.bd.bind(z));u--;var F={toValue:Dt};switch(u=E.map((z,W)=>{var X=`argFromPtr${W}`;return F[X]=z,`${X}(args${W?"+"+8*W:""})`}),m){case 0:var P="toValue(handle)";break;case 2:P="new (toValue(handle))";break;case 3:P="";break;case 1:F.getStringOrSymbol=Ao,P="toValue(handle)[getStringOrSymbol(methodName)]"}return P+=`(${u})`,g.we||(F.toReturnWire=f,F.emval_returnValue=R3,P=`return emval_returnValue(toReturnWire, destructorsRef, ${P})`),P=`return function (handle, methodName, destructorsRef, args) {
|
|
6
|
+
${P}
|
|
7
|
+
}`,m=new Function(Object.keys(F),P)(...Object.values(F)),P=`methodCaller<(${b.map(z=>z.name)}) => ${g.name}>`,z3(Object.defineProperty(m,"name",{value:P}))}function V3(u,f){return f>>>=0,(u=Dt(u>>>0))==Dt(f)}function U3(u){return(u>>>=0)?(u=Ao(u),Yt(globalThis[u])):Yt(globalThis)}function j3(u){return u=Ao(u>>>0),Yt(t[u])}function W3(u,f){return f>>>=0,u=Dt(u>>>0),f=Dt(f),Yt(u[f])}function q3(u){9<(u>>>=0)&&(on[u+1]+=1)}function Kw(u,f,m,g,b){return Pd[u>>>0](f>>>0,m>>>0,g>>>0,b>>>0)}function H3(u,f,m,g,b){return Kw(u>>>0,f>>>0,m>>>0,g>>>0,b>>>0)}function Q3(){return Yt([])}function X3(u){u=Dt(u>>>0);for(var f=Array(u.length),m=0;m<u.length;m++)f[m]=u[m];return Yt(f)}function Y3(u){return Yt(Ao(u>>>0))}function J3(){return Yt({})}function K3(u){for(var f=Dt(u>>>=0);f.length;){var m=f.pop();f.pop()(m)}kd(u)}function Z3(u,f,m){f>>>=0,m>>>=0,u=Dt(u>>>0),f=Dt(f),m=Dt(m),u[f]=m}function eD(u,f){u=lt(u),f>>>=0,u=new Date(1e3*u),(M(),B)[f>>>2>>>0]=u.getUTCSeconds(),(M(),B)[f+4>>>2>>>0]=u.getUTCMinutes(),(M(),B)[f+8>>>2>>>0]=u.getUTCHours(),(M(),B)[f+12>>>2>>>0]=u.getUTCDate(),(M(),B)[f+16>>>2>>>0]=u.getUTCMonth(),(M(),B)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(M(),B)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(M(),B)[f+28>>>2>>>0]=u}var Zw=u=>u%4==0&&(u%100!=0||u%400==0),ev=[0,31,60,91,121,152,182,213,244,274,305,335],tv=[0,31,59,90,120,151,181,212,243,273,304,334];function tD(u,f){u=lt(u),f>>>=0,u=new Date(1e3*u),(M(),B)[f>>>2>>>0]=u.getSeconds(),(M(),B)[f+4>>>2>>>0]=u.getMinutes(),(M(),B)[f+8>>>2>>>0]=u.getHours(),(M(),B)[f+12>>>2>>>0]=u.getDate(),(M(),B)[f+16>>>2>>>0]=u.getMonth(),(M(),B)[f+20>>>2>>>0]=u.getFullYear()-1900,(M(),B)[f+24>>>2>>>0]=u.getDay();var m=(Zw(u.getFullYear())?ev:tv)[u.getMonth()]+u.getDate()-1|0;(M(),B)[f+28>>>2>>>0]=m,(M(),B)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),m=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(m!=g&&u.getTimezoneOffset()==Math.min(g,m)),(M(),B)[f+32>>>2>>>0]=u}function rD(u){u>>>=0;var f=new Date((M(),B)[u+20>>>2>>>0]+1900,(M(),B)[u+16>>>2>>>0],(M(),B)[u+12>>>2>>>0],(M(),B)[u+8>>>2>>>0],(M(),B)[u+4>>>2>>>0],(M(),B)[u>>>2>>>0],0),m=(M(),B)[u+32>>>2>>>0],g=f.getTimezoneOffset(),b=new Date(f.getFullYear(),6,1).getTimezoneOffset(),E=new Date(f.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(E,b);return 0>m?(M(),B)[u+32>>>2>>>0]=+(b!=E&&F==g):0<m!=(F==g)&&(b=Math.max(E,b),f.setTime(f.getTime()+6e4*((0<m?F:b)-g))),(M(),B)[u+24>>>2>>>0]=f.getDay(),m=(Zw(f.getFullYear())?ev:tv)[f.getMonth()]+f.getDate()-1|0,(M(),B)[u+28>>>2>>>0]=m,(M(),B)[u>>>2>>>0]=f.getSeconds(),(M(),B)[u+4>>>2>>>0]=f.getMinutes(),(M(),B)[u+8>>>2>>>0]=f.getHours(),(M(),B)[u+12>>>2>>>0]=f.getDate(),(M(),B)[u+16>>>2>>>0]=f.getMonth(),(M(),B)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function rv(u,f,m,g,b,E,F){return s?ue(16,1,u,f,m,g,b,E,F):-52}function nv(u,f,m,g,b,E){if(s)return ue(17,1,u,f,m,g,b,E)}var Vs={},nD=()=>performance.timeOrigin+performance.now();function sv(u,f){if(s)return ue(18,1,u,f);if(Vs[u]&&(clearTimeout(Vs[u].id),delete Vs[u]),!f)return 0;var m=setTimeout(()=>{delete Vs[u],yt(()=>$v(u,performance.timeOrigin+performance.now()))},f);return Vs[u]={id:m,Ve:f},0}function sD(u,f,m,g){u>>>=0,f>>>=0,m>>>=0,g>>>=0;var b=new Date().getFullYear(),E=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var F=Math.max(E,b);(M(),L)[u>>>2>>>0]=60*F,(M(),B)[f>>>2>>>0]=+(E!=b),u=(f=P=>{var z=Math.abs(P);return`UTC${0<=P?"-":"+"}${String(Math.floor(z/60)).padStart(2,"0")}${String(z%60).padStart(2,"0")}`})(E),f=f(b),b<E?(br(u,m,17),br(f,g,17)):(br(u,g,17),br(f,m,17))}var aD=()=>Date.now();function oD(u,f,m){return m>>>=0,0<=u&&3>=u?(u===0?u=Date.now():u=performance.timeOrigin+performance.now(),u=Math.round(1e6*u),(M(),ne)[m>>>3>>>0]=BigInt(u),0):28}var Fd=[],av=(u,f)=>{Fd.length=0;for(var m;m=(M(),U)[u++>>>0];){var g=m!=105;f+=(g&=m!=112)&&f%8?4:0,Fd.push(m==112?(M(),L)[f>>>2>>>0]:m==106?(M(),ne)[f>>>3>>>0]:m==105?(M(),B)[f>>>2>>>0]:(M(),H)[f>>>3>>>0]),f+=g?8:4}return Fd};function iD(u,f,m){return u>>>=0,f=av(f>>>0,m>>>0),qd[u](...f)}function lD(u,f,m){return u>>>=0,f=av(f>>>0,m>>>0),qd[u](...f)}var cD=()=>{};function uD(u,f){return S(Hn(u>>>0,f>>>0))}var dD=()=>{throw be+=1,"unwind"};function hD(){return 4294901760}var fD=()=>1,_D=()=>navigator.hardwareConcurrency,ln={},ov=u=>{var f=Mr(u)+1,m=cn(f);return m&&br(u,m,f),m},Co=u=>{var f;return(f=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(u))?+f[1]:(f=/:(\d+):\d+(?:\)|$)/.exec(u))?2147483648|+f[1]:0},iv=u=>{for(var f of u)(u=Co(f))&&(ln[u]=f)};function pD(){var u=Error().stack.toString().split(`
|
|
8
|
+
`);return u[0]=="Error"&&u.shift(),iv(u),ln.ee=Co(u[3]),ln.xe=u,ln.ee}function So(u){if(!(u=ln[u>>>0]))return 0;var f;if(f=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(u))u=f[1];else if(f=/^\s+at (.*) \(.*\)$/.exec(u))u=f[1];else{if(!(f=/^(.+?)@/.exec(u)))return 0;u=f[1]}return zt(So.ne??0),So.ne=ov(u),So.ne}function mD(u){u>>>=0;var f=(M(),U).length;if(u<=f||4294901760<u)return!1;for(var m=1;4>=m;m*=2){var g=f*(1+.2/m);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Gr.buffer.byteLength+65535)/65536|0;try{Gr.grow(g),D();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}function gD(u,f,m){if(u>>>=0,f>>>=0,ln.ee==u)var g=ln.xe;else(g=Error().stack.toString().split(`
|
|
9
|
+
`))[0]=="Error"&&g.shift(),iv(g);for(var b=3;g[b]&&Co(g[b])!=u;)++b;for(u=0;u<m&&g[u+b];++u)(M(),B)[f+4*u>>>2>>>0]=Co(g[u+b]);return u}var dr=u=>{var f=Mr(u)+1,m=Lo(f);return br(u,m,f),m},Xn=u=>(M(),L)[u>>>2>>>0]+4294967296*(M(),B)[u+4>>>2>>>0],ct=[],lv=(u,f)=>{ct[u>>>0]=f},xr=[],Po=[],Yn=(u,f)=>{Po[u]=new Promise(m=>f.finally(()=>m(u)))},te=u=>{if(u)return ct[u>>>0]},Id=(u,f)=>{for(u=(M(),L)[u>>>2>>>0];u;u=(M(),L)[u>>>2>>>0])f[(M(),B)[u+4>>>2>>>0]](u)},Fo=(u,f,m)=>{(M(),L)[u>>>2>>>0]=f,(M(),L)[u+4>>>2>>>0]=m},cv=u=>{var f=(M(),L)[u>>>2>>>0];return u=(M(),L)[u+4>>>2>>>0],Hn(f,u)},Jt=u=>{var f=(M(),L)[u>>>2>>>0];return u=(M(),L)[u+4>>>2>>>0],f?Hn(f,u):u===0?"":void 0},wD=u=>{var f=Jt(u+4),m=(m=(M(),L)[u+12>>>2>>>0])?te(m):"auto";if(u+=16){var g=te((M(),L)[u+4>>>2>>>0]),b=(M(),L)[u+16>>>2>>>0],E=(M(),L)[u+20>>>2>>>0];if(b){for(var F={},P=0;P<b;++P){var z=E+24*P;F[cv(z+4)]=(M(),H)[z+16>>>3>>>0]}b=F}else b=void 0;u={module:g,constants:b,entryPoint:Jt(u+8)}}else u=void 0;return{label:f,layout:m,compute:u}},uv=(u,f)=>{function m(E,F,P,z=0){E=u[E]??z,(M(),L)[F+P>>>2>>>0]=E}function g(E,F,P,z=0){F+=P,E=u[E]??z,(M(),L)[F>>>2>>>0]=E,z=(M(),L)[F>>>2>>>0],(M(),L)[F+4>>>2>>>0]=(E-z)/4294967296}var b=(M(),L)[f>>>2>>>0];m("maxTextureDimension1D",f,4),m("maxTextureDimension2D",f,8),m("maxTextureDimension3D",f,12),m("maxTextureArrayLayers",f,16),m("maxBindGroups",f,20),m("maxBindGroupsPlusVertexBuffers",f,24),m("maxBindingsPerBindGroup",f,28),m("maxDynamicUniformBuffersPerPipelineLayout",f,32),m("maxDynamicStorageBuffersPerPipelineLayout",f,36),m("maxSampledTexturesPerShaderStage",f,40),m("maxSamplersPerShaderStage",f,44),m("maxStorageBuffersPerShaderStage",f,48),m("maxStorageTexturesPerShaderStage",f,52),m("maxUniformBuffersPerShaderStage",f,56),m("minUniformBufferOffsetAlignment",f,80),m("minStorageBufferOffsetAlignment",f,84),g("maxUniformBufferBindingSize",f,64),g("maxStorageBufferBindingSize",f,72),m("maxVertexBuffers",f,88),g("maxBufferSize",f,96),m("maxVertexAttributes",f,104),m("maxVertexBufferArrayStride",f,108),m("maxInterStageShaderVariables",f,112),m("maxColorAttachments",f,116),m("maxColorAttachmentBytesPerSample",f,120),m("maxComputeWorkgroupStorageSize",f,124),m("maxComputeInvocationsPerWorkgroup",f,128),m("maxComputeWorkgroupSizeX",f,132),m("maxComputeWorkgroupSizeY",f,136),m("maxComputeWorkgroupSizeZ",f,140),m("maxComputeWorkgroupsPerDimension",f,144),m("maxImmediateSize",f,148),b!==0&&(M(),m("maxStorageBuffersInVertexStage",b,8,u.maxStorageBuffersPerShaderStage),m("maxStorageBuffersInFragmentStage",b,16,u.maxStorageBuffersPerShaderStage),m("maxStorageTexturesInVertexStage",b,12,u.maxStorageTexturesPerShaderStage),m("maxStorageTexturesInFragmentStage",b,20,u.maxStorageTexturesPerShaderStage))},vD=(u,f)=>{(M(),L)[f+52>>>2>>>0]=u.subgroupMinSize,(M(),L)[f+56>>>2>>>0]=u.subgroupMaxSize;var m=ov(u.vendor+u.architecture+u.device+u.description),g=Mr(u.vendor);Fo(f+4,m,g),m+=g,g=Mr(u.architecture),Fo(f+12,m,g),m+=g,g=Mr(u.device),Fo(f+20,m,g),m+=g,g=Mr(u.description),Fo(f+28,m,g),m+=g,(M(),B)[f+36>>>2>>>0]=2,m=u.isFallbackAdapter?3:4,(M(),B)[f+40>>>2>>>0]=m,(M(),L)[f+44>>>2>>>0]=0,(M(),L)[f+48>>>2>>>0]=0,Id(f,{327739:b=>{let E=0,F=0;if(u.subgroupMatrixConfigs){E=u.subgroupMatrixConfigs.length,F=cn(20*E);for(let[P,z]of u.subgroupMatrixConfigs.entries()){let W=F+20*P,X=hv.indexOf(z.componentType),oe=hv.indexOf(z.resultComponentType);(M(),B)[W>>>2>>>0]=X,(M(),B)[W+4>>>2>>>0]=oe,(M(),L)[W+8>>>2>>>0]=z.M,(M(),L)[W+12>>>2>>>0]=z.N,(M(),L)[W+16>>>2>>>0]=z.K}}(M(),L)[b+12>>>2>>>0]=F,(M(),L)[b+8>>>2>>>0]=E}})},yD=[,,"uniform","storage","read-only-storage"],bD=[,"validation","out-of-memory","internal"],MD=[,"compatibility","core"],dv={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",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},xD=[,"low-power","high-performance"],kD=[,"occlusion","timestamp"],TD=[,,"filtering","non-filtering","comparison"],ED=[,,"write-only","read-only","read-write"],hv=[,"f32","f16","u32","i32","u8","i8"],AD=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],CD=[,,"float","unfilterable-float","depth","sint","uint"],fv=[,"1d","2d","2d-array","cube","cube-array","3d"],SD={undefined:1,unknown:1,destroyed:2};function PD(u,f,m,g,b,E){f=lt(f),m=lt(m),g>>>=0,b>>>=0,E>>>=0;var F=te(u>>>0);if(u={},E){var P=(M(),L)[E+12>>>2>>>0];if(P){var z=(M(),L)[E+16>>>2>>>0];u.requiredFeatures=Array.from((M(),L).subarray(z>>>2>>>0,z+4*P>>>2>>>0),X=>dv[X])}if(P=(M(),L)[E+20>>>2>>>0]){let X=function(we,Ie,un,Ws=!1){Ie+=un,(Ie=(M(),L)[Ie>>>2>>>0])==4294967295||Ws&&Ie==0||(W[we]=Ie)},oe=function(we,Ie,un){Ie+=un,un=(M(),L)[Ie>>>2>>>0];var Ws=(M(),L)[Ie+4>>>2>>>0];un==4294967295&&Ws==4294967295||(W[we]=Xn(Ie))};z=(M(),L)[P>>>2>>>0];var W={};X("maxTextureDimension1D",P,4),X("maxTextureDimension2D",P,8),X("maxTextureDimension3D",P,12),X("maxTextureArrayLayers",P,16),X("maxBindGroups",P,20),X("maxBindGroupsPlusVertexBuffers",P,24),X("maxBindingsPerBindGroup",P,28),X("maxDynamicUniformBuffersPerPipelineLayout",P,32),X("maxDynamicStorageBuffersPerPipelineLayout",P,36),X("maxSampledTexturesPerShaderStage",P,40),X("maxSamplersPerShaderStage",P,44),X("maxStorageBuffersPerShaderStage",P,48),X("maxStorageTexturesPerShaderStage",P,52),X("maxUniformBuffersPerShaderStage",P,56),X("minUniformBufferOffsetAlignment",P,80),X("minStorageBufferOffsetAlignment",P,84),oe("maxUniformBufferBindingSize",P,64),oe("maxStorageBufferBindingSize",P,72),X("maxVertexBuffers",P,88),oe("maxBufferSize",P,96),X("maxVertexAttributes",P,104),X("maxVertexBufferArrayStride",P,108),X("maxInterStageShaderVariables",P,112),X("maxColorAttachments",P,116),X("maxColorAttachmentBytesPerSample",P,120),X("maxComputeWorkgroupStorageSize",P,124),X("maxComputeInvocationsPerWorkgroup",P,128),X("maxComputeWorkgroupSizeX",P,132),X("maxComputeWorkgroupSizeY",P,136),X("maxComputeWorkgroupSizeZ",P,140),X("maxComputeWorkgroupsPerDimension",P,144),X("maxImmediateSize",P,148,!0),z!==0&&(M(),"maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype&&(X("maxStorageBuffersInVertexStage",z,8),X("maxStorageTexturesInVertexStage",z,12),X("maxStorageBuffersInFragmentStage",z,16),X("maxStorageTexturesInFragmentStage",z,20))),u.requiredLimits=W}(P=(M(),L)[E+24>>>2>>>0])&&(P={label:Jt(P+4)},u.defaultQueue=P),u.label=Jt(E+4)}be+=1,Yn(f,F.requestDevice(u).then(X=>{--be,yt(()=>{ct[b>>>0]=X.queue,ct[g>>>0]=X,be+=1,Yn(m,X.lost.then(oe=>{yt(()=>{X.onuncapturederror=()=>{};var we=ae(),Ie=dr(oe.message);zd(m,SD[oe.reason],Ie),se(we)}),--be})),X.onuncapturederror=oe=>{var we=5;oe.error instanceof GPUValidationError?we=2:oe.error instanceof GPUOutOfMemoryError?we=3:oe.error instanceof GPUInternalError&&(we=4);var Ie=ae();oe=dr(oe.error.message),Dv(g,we,oe),se(Ie)},"adapterInfo"in X||(X.adapterInfo=F.info),$d(f,1,g,0)})},X=>{--be,yt(()=>{var oe=ae(),we=dr(X.message);$d(f,3,g,we),m&&zd(m,4,we),se(oe)})}))}function FD(u){var f=te(u>>>=0),m=xr[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete xr[u]}f.destroy()}function ID(u,f,m){m>>>=0;var g=te(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=Ud(16,b.byteLength);return(M(),U).set(new Uint8Array(b),E>>>0),xr[u].push(()=>zt(E)),E}function LD(u,f,m){m>>>=0;var g=te(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=Ud(16,b.byteLength);return(M(),U).fill(0,E,b.byteLength),xr[u].push(()=>{new Uint8Array(b).set((M(),U).subarray(E>>>0,E+b.byteLength>>>0)),zt(E)}),E}function OD(u,f,m,g,b){u>>>=0,f=lt(f),m=lt(m),b>>>=0;var E=te(u);xr[u]=[],b==4294967295&&(b=void 0),be+=1,Yn(f,E.mapAsync(m,g>>>0,b).then(()=>{--be,yt(()=>{Bd(f,1,0)})},F=>{--be,yt(()=>{ae();var P=dr(F.message);Bd(f,F.name==="AbortError"?4:F.name==="OperationError"?3:0,P),delete xr[u]})}))}function ND(u){var f=te(u>>>=0),m=xr[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete xr[u],f.unmap()}}function DD(u){delete ct[u>>>0]}function zD(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=!!(M(),L)[f+32>>>2>>>0];f={label:Jt(f+4),usage:(M(),L)[f+16>>>2>>>0],size:Xn(f+24),mappedAtCreation:g},u=te(u);try{var b=u.createBuffer(f)}catch{return!1}return ct[m>>>0]=b,g&&(xr[m]=[]),!0}function BD(u,f,m,g){u>>>=0,f=lt(f),g>>>=0,m=wD(m>>>0),u=te(u),be+=1,Yn(f,u.createComputePipelineAsync(m).then(b=>{--be,yt(()=>{ct[g>>>0]=b,Dd(f,1,g,0)})},b=>{--be,yt(()=>{var E=ae(),F=dr(b.message);Dd(f,b.reason==="validation"?3:b.reason==="internal"?4:0,g,F),se(E)})}))}function RD(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=(M(),L)[f>>>2>>>0],b=(M(),B)[g+4>>>2>>>0];f={label:Jt(f+4),code:""},b===2&&(f.code=cv(g+8)),u=te(u).createShaderModule(f),ct[m>>>0]=u}var $D=u=>{(u=te(u)).onuncapturederror=null,u.destroy()};function GD(u,f){f=lt(f),u=te(u>>>0),be+=1,Yn(f,u.popErrorScope().then(m=>{--be,yt(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var b=ae(),E=m?dr(m.message):0;Rd(f,1,g,E),se(b)})},m=>{--be,yt(()=>{var g=ae(),b=dr(m.message);Rd(f,1,5,b),se(g)})}))}function VD(u,f,m,g){if(f=lt(f),g>>>=0,m>>>=0){var b={featureLevel:MD[(M(),B)[m+4>>>2>>>0]],powerPreference:xD[(M(),B)[m+8>>>2>>>0]],forceFallbackAdapter:!!(M(),L)[m+12>>>2>>>0]};(u=(M(),L)[m>>>2>>>0])!==0&&(M(),b.Ye=!!(M(),L)[u+8>>>2>>>0])}"gpu"in navigator?(be+=1,Yn(f,navigator.gpu.requestAdapter(b).then(E=>{--be,yt(()=>{if(E)ct[g>>>0]=E,Us(f,1,g,0);else{var F=ae(),P=dr("WebGPU not available on this browser (requestAdapter returned null)");Us(f,3,g,P),se(F)}})},E=>{--be,yt(()=>{var F=ae(),P=dr(E.message);Us(f,4,g,P),se(F)})}))):(b=ae(),u=dr("WebGPU not available on this browser (navigator.gpu is not available)"),Us(f,3,g,u),se(b))}function UD(u,f,m){return u>>>=0,f>>>=0,m>>>=0,Jw(async()=>{var g=[];if(m){var b=(M(),B)[m>>>2>>>0];g.length=f+1,g[f]=new Promise(P=>setTimeout(P,b,0))}else g.length=f;for(var E=0;E<f;++E){var F=Xn(u+8*E);if(!(F in Po))return F;g[E]=Po[F]}return g=await Promise.race(g),delete Po[g],g})}var Ld,Od={},_v=()=>{var g;if(!Ld){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(((g=globalThis.navigator)==null?void 0:g.language)??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Od)Od[u]===void 0?delete f[u]:f[u]=Od[u];var m=[];for(u in f)m.push(`${u}=${f[u]}`);Ld=m}return Ld};function pv(u,f){if(s)return ue(19,1,u,f);u>>>=0,f>>>=0;var m,g=0,b=0;for(m of _v()){var E=f+g;(M(),L)[u+b>>>2>>>0]=E,g+=br(m,E,1/0)+1,b+=4}return 0}function mv(u,f){if(s)return ue(20,1,u,f);u>>>=0,f>>>=0;var m=_v();for(var g of((M(),L)[u>>>2>>>0]=m.length,u=0,m))u+=Mr(g)+1;return(M(),L)[f>>>2>>>0]=u,0}function gv(u){return s?ue(21,1,u):52}function wv(u,f,m,g,b){return s?ue(22,1,u,f,m,g,b):52}function vv(u,f,m,g){return s?ue(23,1,u,f,m,g):52}function yv(u,f,m,g){return s?ue(24,1,u,f,m,g):70}var jD=[null,[],[]];function bv(u,f,m,g){if(s)return ue(25,1,u,f,m,g);f>>>=0,m>>>=0,g>>>=0;for(var b=0,E=0;E<m;E++){var F=(M(),L)[f>>>2>>>0],P=(M(),L)[f+4>>>2>>>0];f+=8;for(var z=0;z<P;z++){var W=u,X=(M(),U)[F+z>>>0],oe=jD[W];X===0||X===10?((W===1?A:S)(Fw(oe)),oe.length=0):oe.push(X)}b+=P}return(M(),L)[g>>>2>>>0]=b,0}function WD(u){return u>>>0}function qD(u,f){return uv(te(u>>>0).limits,f>>>0),1}function HD(u,f){return te(u>>>0).features.has(dv[f])}function QD(u){return BigInt(te(u>>>0).size)}function XD(u){return BigInt(te(u>>>0).usage)}function YD(u,f){if(u>>>=0,f>>>=0){var m=Jt(f+4);m={label:m,timestampWrites:f=(f=(M(),L)[f+12>>>2>>>0])!==0?{querySet:te((M(),L)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(M(),L)[f+8>>>2>>>0],endOfPassWriteIndex:(M(),L)[f+12>>>2>>>0]}:void 0}}return f=te(u),u=Pv(0),m=f.beginComputePass(m),ct[u>>>0]=m,u}function JD(u,f,m,g){m=lt(m),(g=lt(g))==-1&&(g=void 0),(u=te(u>>>0)).clearBuffer(te(f>>>0),m,g)}function KD(u,f,m,g,b,E){m=lt(m),b=lt(b),E=lt(E),te(u>>>0).copyBufferToBuffer(te(f>>>0),m,te(g>>>0),b,E)}function ZD(u){var f=te(u>>>0);return u=Cv(0),f=f.finish(),ct[u>>>0]=f,u}function ez(u,f,m,g,b,E){E=lt(E),te(u>>>0).resolveQuerySet(te(f>>>0),m,g,te(b>>>0),E)}function tz(u,f,m,g){te(u>>>0).dispatchWorkgroups(f,m,g)}function rz(u,f,m){m=lt(m),te(u>>>0).dispatchWorkgroupsIndirect(te(f>>>0),m)}function nz(u){te(u>>>0).end()}function sz(u,f,m,g,b){g>>>=0,b>>>=0,u=te(u>>>0),m=te(m>>>0),g==0?u.setBindGroup(f,m):u.setBindGroup(f,m,(M(),L),b>>>2,g)}function az(u,f){te(u>>>0).setPipeline(te(f>>>0))}function oz(u,f,m){te(u>>>0).Xe(te(f>>>0),m)}function iz(u,f){function m(b){var E=(M(),L)[b+8>>>2>>>0],F=(M(),L)[b+32>>>2>>>0],P=(M(),L)[b+36>>>2>>>0],z=0;return Id(b,{14:W=>{z=(M(),L)[W+8>>>2>>>0]}}),E?((F=Xn(b+24))==-1&&(F=void 0),E={buffer:te(E),offset:Xn(b+16),size:F}):E=te(F||P||z),{binding:(M(),L)[b+4>>>2>>>0],resource:E}}u>>>=0,f={label:Jt((f>>>=0)+4),layout:te((M(),L)[f+12>>>2>>>0]),entries:(function(b,E){for(var F=[],P=0;P<b;++P)F.push(m(E+40*P));return F})((M(),L)[f+16>>>2>>>0],(M(),L)[f+20>>>2>>>0])},u=te(u);var g=Ev(0);return lv(g,u.createBindGroup(f)),g}function lz(u,f){function m(z){var W=(M(),L)[z+4>>>2>>>0];if(W)return{type:yD[W],hasDynamicOffset:!!(M(),L)[z+8>>>2>>>0],minBindingSize:Xn(z+16)}}function g(z){if(z=(M(),L)[z+4>>>2>>>0])return{type:TD[z]}}function b(z){var W=(M(),L)[z+4>>>2>>>0];if(W)return{sampleType:CD[W],viewDimension:fv[(M(),B)[z+8>>>2>>>0]],multisampled:!!(M(),L)[z+12>>>2>>>0]}}function E(z){var W=(M(),L)[z+4>>>2>>>0];if(W)return{access:ED[W],format:AD[(M(),B)[z+8>>>2>>>0]],viewDimension:fv[(M(),B)[z+12>>>2>>>0]]}}function F(z){var W={binding:(M(),L)[z+4>>>2>>>0],visibility:(M(),L)[z+8>>>2>>>0],buffer:m(z+24),sampler:g(z+48),texture:b(z+56),storageTexture:E(z+72)};return Id(z,{13:()=>{W.externalTexture={}}}),W}u>>>=0,f={label:Jt((f>>>=0)+4),entries:(function(z,W){for(var X=[],oe=0;oe<z;++oe)X.push(F(W+88*oe));return X})((M(),L)[f+12>>>2>>>0],(M(),L)[f+16>>>2>>>0])},u=te(u);var P=Av(0);return lv(P,u.createBindGroupLayout(f)),P}function cz(u,f){var m;return u>>>=0,(f>>>=0)&&(m={label:Jt(f+4)}),f=te(u),u=Sv(0),m=f.createCommandEncoder(m),ct[u>>>0]=m,u}function uz(u,f){u>>>=0,f>>>=0;for(var m=(M(),L)[f+12>>>2>>>0],g=(M(),L)[f+16>>>2>>>0],b=[],E=0;E<m;++E)b.push(te((M(),L)[g+4*E>>>2>>>0]));return f={label:Jt(f+4),bindGroupLayouts:b,immediateSize:(M(),L)[f+20>>>2>>>0]},m=te(u),u=Fv(0),f=m.createPipelineLayout(f),ct[u>>>0]=f,u}function dz(u,f){u>>>=0,f>>>=0,f={type:kD[(M(),B)[f+12>>>2>>>0]],count:(M(),L)[f+16>>>2>>>0]};var m=te(u);return u=Iv(0),f=m.createQuerySet(f),ct[u>>>0]=f,u}function hz(u,f){return vD(te(u>>>0).adapterInfo,f>>>0),1}var fz={"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,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function _z(u,f){f>>>=0;var m=te(u>>>0);u=cn(4*m.features.size);var g=0,b=0;for(let E of m.features)0<=(m=fz[E])&&((M(),B)[u+g>>>2>>>0]=m,g+=4,b++);(M(),L)[f+4>>>2>>>0]=u,(M(),L)[f>>>2>>>0]=b}function pz(u,f){return uv(te(u>>>0).limits,f>>>0),1}function mz(u,f){te(u>>>0).pushErrorScope(bD[f])}function gz(u,f,m){f>>>=0,m>>>=0,u=te(u>>>0),f=Array.from((M(),B).subarray(m>>>2>>>0,m+4*f>>>2>>>0),g=>te(g)),u.submit(f)}function wz(u,f,m,g,b){m=lt(m),g>>>=0,b>>>=0,u=te(u>>>0),f=te(f>>>0),g=(M(),U).subarray(g>>>0,g+b>>>0),u.writeBuffer(f,m,g,0,b)}s||(function(){for(var u=t.numThreads-1;u--;)kw();Ke.push(async()=>{var f=(async function(){if(!s)return Promise.all(Nt.map(xw))})();Ot++,await f,--Ot==0&&Ze&&(f=Ze,Ze=null,f())})})(),s||(Gr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),D()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>ae(),t.stackRestore=u=>se(u),t.stackAlloc=u=>Lo(u),t.setValue=function(u,f,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":(M(),G)[u>>>0]=f;break;case"i16":(M(),J)[u>>>1>>>0]=f;break;case"i32":(M(),B)[u>>>2>>>0]=f;break;case"i64":(M(),ne)[u>>>3>>>0]=BigInt(f);break;case"float":(M(),ee)[u>>>2>>>0]=f;break;case"double":(M(),H)[u>>>3>>>0]=f;break;case"*":(M(),L)[u>>>2>>>0]=f;break;default:re(`invalid type for setValue: ${m}`)}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(M(),G)[u>>>0];case"i16":return(M(),J)[u>>>1>>>0];case"i32":return(M(),B)[u>>>2>>>0];case"i64":return(M(),ne)[u>>>3>>>0];case"float":return(M(),ee)[u>>>2>>>0];case"double":return(M(),H)[u>>>3>>>0];case"*":return(M(),L)[u>>>2>>>0];default:re(`invalid type for getValue: ${f}`)}},t.UTF8ToString=Hn,t.stringToUTF8=br,t.lengthBytesUTF8=Mr;var Mv,xv,kv,Nd,Io,zt,cn,Tv,Ev,Av,Cv,Sv,Pv,Fv,Iv,Lv,Ov,Nv,Dd,zd,Bd,Rd,Us,$d,Dv,Gd,zv,Bv,Rv,Vd,$v,Gv,Ud,_e,js,Vv,se,Lo,ae,Uv,jd,jv,Wv,qv,Wd,Hv,Qv,Xv,Yv,Jv,Kv,Zv,ey,ty,ry,ny,sy,ay,oy,iy,ly,cy,uy,dy,hy,fy,_y,py,my,gy,wy,vy,yy,by,My,xy,ky,Ty,Ey,Ay,Cy,Sy,Py,Fy,Iy,Ly,kr,vz=[Fe,vt,Aw,Iw,Lw,Ow,Nw,Dw,zw,Bw,Rw,$w,Gw,Vw,Uw,jw,rv,nv,sv,pv,mv,gv,wv,vv,yv,bv],qd={1280444:(u,f,m,g,b)=>{if(t===void 0||!t.ed)return 1;if((u=Hn(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.ed.get(u)))return 2;if(f=Number(f>>>0),m=Number(m>>>0),g=Number(g>>>0),f+m>u.byteLength)return 3;try{let E=u.subarray(f,f+m);switch(b){case 0:(M(),U).set(E,g>>>0);break;case 1:t.pe?t.pe(g,E):t.Re(g,E);break;default:return 4}return 0}catch{return 4}},1281268:(u,f,m)=>{t.re(u,(M(),U).subarray(f>>>0,f+m>>>0))},1281332:()=>t.Pe(),1281374:u=>{t.qe(u)},1281411:()=>typeof wasmOffsetConverter<"u"};function yz(){return typeof wasmOffsetConverter<"u"}function bz(u,f,m,g){var b=ae();try{return ey(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Mz(u,f,m){var g=ae();try{return Jv(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;_e(1,0)}}function xz(u){var f=ae();try{Hv(u)}catch(m){if(se(f),m!==m+0)throw m;_e(1,0)}}function kz(u,f){var m=ae();try{return Wd(u,f)}catch(g){if(se(m),g!==g+0)throw g;_e(1,0)}}function Tz(u,f,m){var g=ae();try{qv(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;_e(1,0)}}function Ez(u,f){var m=ae();try{ty(u,f)}catch(g){if(se(m),g!==g+0)throw g;_e(1,0)}}function Az(u,f,m,g,b,E,F){var P=ae();try{return Yv(u,f,m,g,b,E,F)}catch(z){if(se(P),z!==z+0)throw z;_e(1,0)}}function Cz(u,f,m,g,b,E){var F=ae();try{Qv(u,f,m,g,b,E)}catch(P){if(se(F),P!==P+0)throw P;_e(1,0)}}function Sz(u,f,m,g){var b=ae();try{Zv(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Pz(u,f,m,g,b,E,F){var P=ae();try{ny(u,f,m,g,b,E,F)}catch(z){if(se(P),z!==z+0)throw z;_e(1,0)}}function Fz(u,f,m,g,b,E,F){var P=ae();try{sy(u,f,m,g,b,E,F)}catch(z){if(se(P),z!==z+0)throw z;_e(1,0)}}function Iz(u,f,m,g,b,E,F,P){var z=ae();try{_y(u,f,m,g,b,E,F,P)}catch(W){if(se(z),W!==W+0)throw W;_e(1,0)}}function Lz(u,f,m,g,b,E,F,P,z,W,X,oe){var we=ae();try{ay(u,f,m,g,b,E,F,P,z,W,X,oe)}catch(Ie){if(se(we),Ie!==Ie+0)throw Ie;_e(1,0)}}function Oz(u,f,m,g,b){var E=ae();try{return ry(u,f,m,g,b)}catch(F){if(se(E),F!==F+0)throw F;_e(1,0)}}function Nz(u,f,m,g,b,E){var F=ae();try{py(u,f,m,g,b,E)}catch(P){if(se(F),P!==P+0)throw P;_e(1,0)}}function Dz(u,f,m,g,b){var E=ae();try{Xv(u,f,m,g,b)}catch(F){if(se(E),F!==F+0)throw F;_e(1,0)}}function zz(u,f,m,g,b,E,F,P){var z=ae();try{Kv(u,f,m,g,b,E,F,P)}catch(W){if(se(z),W!==W+0)throw W;_e(1,0)}}function Bz(u){var f=ae();try{return my(u)}catch(m){if(se(f),m!==m+0)throw m;_e(1,0)}}function Rz(u,f,m,g,b,E,F,P,z){var W=ae();try{iy(u,f,m,g,b,E,F,P,z)}catch(X){if(se(W),X!==X+0)throw X;_e(1,0)}}function $z(u,f,m){var g=ae();try{return gy(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;_e(1,0)}}function Gz(u,f){var m=ae();try{return Sy(u,f)}catch(g){if(se(m),g!==g+0)throw g;return _e(1,0),0n}}function Vz(u,f,m,g){var b=ae();try{return wy(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Uz(u){var f=ae();try{return oy(u)}catch(m){if(se(f),m!==m+0)throw m;return _e(1,0),0n}}function jz(u,f,m,g){var b=ae();try{return vy(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Wz(u,f,m,g,b){var E=ae();try{return yy(u,f,m,g,b)}catch(F){if(se(E),F!==F+0)throw F;_e(1,0)}}function qz(u,f,m,g,b,E){var F=ae();try{return by(u,f,m,g,b,E)}catch(P){if(se(F),P!==P+0)throw P;_e(1,0)}}function Hz(u,f,m,g,b,E){var F=ae();try{return hy(u,f,m,g,b,E)}catch(P){if(se(F),P!==P+0)throw P;_e(1,0)}}function Qz(u,f,m,g,b,E){var F=ae();try{return My(u,f,m,g,b,E)}catch(P){if(se(F),P!==P+0)throw P;_e(1,0)}}function Xz(u,f,m,g,b,E,F,P){var z=ae();try{return fy(u,f,m,g,b,E,F,P)}catch(W){if(se(z),W!==W+0)throw W;_e(1,0)}}function Yz(u,f,m,g,b){var E=ae();try{return xy(u,f,m,g,b)}catch(F){if(se(E),F!==F+0)throw F;return _e(1,0),0n}}function Jz(u,f,m,g){var b=ae();try{return ky(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Kz(u,f,m,g){var b=ae();try{return Ty(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Zz(u,f,m,g,b,E,F,P,z,W,X,oe){var we=ae();try{return Ey(u,f,m,g,b,E,F,P,z,W,X,oe)}catch(Ie){if(se(we),Ie!==Ie+0)throw Ie;_e(1,0)}}function eB(u,f,m,g,b,E,F,P,z,W,X){var oe=ae();try{Ay(u,f,m,g,b,E,F,P,z,W,X)}catch(we){if(se(oe),we!==we+0)throw we;_e(1,0)}}function tB(u,f,m,g,b,E,F,P,z,W,X,oe,we,Ie,un,Ws){var oB=ae();try{Cy(u,f,m,g,b,E,F,P,z,W,X,oe,we,Ie,un,Ws)}catch(Hd){if(se(oB),Hd!==Hd+0)throw Hd;_e(1,0)}}function rB(u,f,m){var g=ae();try{return cy(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;return _e(1,0),0n}}function nB(u,f,m){var g=ae();try{return ly(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;_e(1,0)}}function sB(u,f,m){var g=ae();try{return uy(u,f,m)}catch(b){if(se(g),b!==b+0)throw b;_e(1,0)}}function aB(u,f,m,g){var b=ae();try{dy(u,f,m,g)}catch(E){if(se(b),E!==E+0)throw E;_e(1,0)}}function Oo(){if(0<Ot)Ze=Oo;else if(s)w==null||w(t),R();else{for(var u=Ke;0<u.length;)u.shift()(t);0<Ot?Ze=Oo:(t.calledRun=!0,C||(R(),w==null||w(t)))}}return s||(kr=await Me(),Oo()),t.PTR_SIZE=4,t.webgpuInit=u=>{let f=new WeakMap,m,g,b=1;t.webgpuRegisterDevice=P=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(P){var z=f.get(P);if(!z){let W=((X,oe=0)=>{var we=Nv(oe);return oe=Ov(oe,we),ct[we>>>0]=X.queue,ct[oe>>>0]=X,oe})(P,z=kv());z=[b++,z,W],f.set(P,z)}return m=P,g=z[0],z}m=void 0,g=0};let E=new Map;t.webgpuOnCreateSession=P=>{if(g!==void 0){var z=g;if(g=void 0,P){let W=Nd(z);E.set(P,W),z===0&&u(m??te(W))}m=void 0}},t.webgpuOnReleaseSession=P=>{E.delete(P)};let F=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(P,z,W)=>{if(W)return P[F]=[W,NaN],W;if(W=P[F])return W[1]++,W[0];if((z=E.get(z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return z=((X,oe=0)=>(X.mapState==="unmapped"||re(),oe=Lv(oe),ct[oe>>>0]=X,oe))(P,z),P[F]=[z,1],z},t.webgpuUnregisterBuffer=P=>{let z=P[F];if(!z)throw Error("Buffer is not registered");z[1]--,z[1]===0&&(Tv(z[0]),delete P[F])},t.webgpuGetBuffer=P=>te(P),t.webgpuCreateDownloader=(P,z,W)=>{if((W=E.get(W))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let X=te(W),oe=16*Math.ceil(Number(z)/16);return async()=>{let we=X.createBuffer({size:oe,usage:9});try{let Ie=X.createCommandEncoder();return Ie.copyBufferToBuffer(P,0,we,0,oe),X.queue.submit([Ie.finish()]),await we.mapAsync(GPUMapMode.READ),we.getMappedRange().slice(0,z)}finally{we.destroy()}}},t.pe=(P,z)=>{var W=z.buffer;let X=z.byteOffset,oe=z.byteLength;if(z=16*Math.ceil(Number(oe)/16),P=te(P),!m){var we=Nd(g);m=te(we)}let Ie=(we=m.createBuffer({mappedAtCreation:!0,size:z,usage:6})).getMappedRange();new Uint8Array(Ie).set(new Uint8Array(W,X,oe)),we.unmap(),(W=m.createCommandEncoder()).copyBufferToBuffer(we,0,P,0,z),m.queue.submit([W.finish()]),we.destroy()}},t.webnnInit=u=>{let f=u[0];[t.Pe,t.qe,t.webnnEnsureTensor,t.re,t.webnnDownloadTensor,t.Oe,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.qe,t.webnnUploadTensor=t.re,t.webnnRegisterMLContext=t.Oe,t.webnnOnRunStart=m=>f.onRunStart(m),t.webnnOnRunEnd=f.onRunEnd.bind(f),t.webnnOnReleaseSession=m=>{f.onReleaseSession(m)},t.webnnCreateMLTensorDownloader=(m,g)=>f.createMLTensorDownloader(m,g),t.webnnRegisterMLTensor=(m,g,b,E)=>f.registerMLTensor(m,g,b,E),t.webnnCreateMLContext=m=>f.createMLContext(m),t.webnnRegisterGraphInput=f.registerGraphInput.bind(f),t.webnnIsGraphInput=f.isGraphInput.bind(f),t.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),t.webnnIsGraphOutput=f.isGraphOutput.bind(f),t.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),t.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f)},N?t:new Promise((u,f)=>{w=u,v=f})}var wh,vh,ab=ge(()=>{"use strict";var e,t;wh=gh,vh=(t=(e=globalThis.self)==null?void 0:e.name)==null?void 0:t.startsWith("em-pthread"),vh&&gh()}),Wo,qo,yh,Tt,bh,Ys,Mh,xh,Ho,kh,Qo,Th,Xo,Eh,Yo=ge(()=>{"use strict";Vo(),Wo=typeof location>"u"?void 0:location.origin,qo=self.location.href>"file:"&&self.location.href<"file;",yh=()=>{if(qo){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",self.location.href).href,Wo).href}return self.location.href},Tt=yh(),bh=()=>{if(Tt&&!Tt.startsWith("blob:"))return Tt.substring(0,Tt.lastIndexOf("/")+1)},Ys=(e,t)=>{try{let r=t??Tt;return(r?new URL(e,r):new URL(e)).origin===Wo}catch{return!1}},Mh=(e,t)=>{let r=t??Tt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},xh=(e,t)=>`${t??"./"}${e}`,Ho=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},kh=async e=>(await import(e)).default,Qo=(sb(),Hs(_h)).default,Th=async()=>{if(!Tt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ys(Tt))return[void 0,Qo()];let e=await Ho(Tt);return[e,Qo(e)]},Xo=(ab(),Hs(mh)).default,Eh=async(e,t,r,n)=>{let s=Xo&&!(e||t);if(s)if(Tt)s=Ys(Tt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,Xo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Mh(a,t),i=r&&o&&!Ys(o,t),l=i?await Ho(o):o??xh(a,t);return[i?l:void 0,await kh(l)]}}}),Jo,Js,es,Ko,Ah,Ch,Sh,Zo,Pe,Qr=ge(()=>{"use strict";Yo(),Js=!1,es=!1,Ko=!1,Ah=()=>{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}},Ch=()=>{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}},Sh=()=>{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}},Zo=async e=>{if(Js)return Promise.resolve();if(es)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ko)throw new Error("previous call to 'initializeWebAssembly()' failed.");es=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Sh())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ch())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Ah();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==null?void 0:s.mjs,i=(o==null?void 0:o.href)??o,l=s==null?void 0:s.wasm,c=(l==null?void 0:l.href)??l,d=e.wasmBinary,[h,_]=await Eh(i,a,r>1,!!d||!!c),p=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{p=!0,v()},t)})),w.push(new Promise((v,y)=>{let x={numThreads:r};if(d)x.wasmBinary=d,x.locateFile=k=>k;else if(c||a)x.locateFile=k=>c??a+k;else if(i&&i.indexOf("blob:")!==0)x.locateFile=k=>new URL(k,i).href;else if(h){let k=bh();k&&(x.locateFile=A=>k+A)}_(x).then(k=>{es=!1,Js=!0,Jo=k,v(),h&&URL.revokeObjectURL(h)},k=>{es=!1,Ko=!0,y(k)})})),await Promise.race(w),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(Js&&Jo)return Jo;throw new Error("WebAssembly is not initialized yet.")}}),Et,Ks,xe,ei=ge(()=>{"use strict";Qr(),Et=(e,t)=>{let r=Pe(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ks=(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")Ks(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)}}}),Ph,ob=ge(()=>{"use strict";Qr(),ei(),Ph=e=>{let t=Pe(),r=0,n=[],s=e||{};try{if((e==null?void 0: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==null?void 0: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==null?void 0:e.terminate)===void 0&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Et(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&xe("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Ks(e.extra,"",new WeakSet,(o,i)=>{let l=Et(o,n),c=Et(i,n);t._OrtAddRunConfigEntry(r,l,c)!==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}}}),Fh,Ih,Lh,dn,Kt,Oh,Nh,ib=ge(()=>{"use strict";Qr(),ei(),Fh=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}`)}},Ih=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Lh=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)},dn=(e,t,r,n)=>{let s=Et(t,n),a=Et(r,n);Pe()._OrtAddSessionConfigEntry(e,s,a)!==0&&xe(`Can't set a session config entry: ${t} - ${r}.`)},Kt=(e,t,r,n)=>{let s=Et(t,n),a=Et(r,n);e.push([s,a])},Oh=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",dn(e,"session.disable_quant_qdq","1",r),dn(e,"session.disable_qdq_constant_folding","1",r),typeof s!="string"){let h=s==null?void 0:s.deviceType;h&&dn(e,"deviceType",h,r)}break;case"webgpu":{a="WebGPU";let h;if(typeof s!="string"){let p=s;if(p.device)if(typeof GPUDevice<"u"&&p.device instanceof GPUDevice)h=p.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&Kt(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&Kt(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let v=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];Kt(o,"forceCpuNodeNames",v.join(`
|
|
10
|
+
`),r)}p.validationMode&&Kt(o,"validationMode",p.validationMode,r),typeof p.enableMatmulFp32Accumulation=="boolean"&&Kt(o,"enableMatmulFp32Accumulation",p.enableMatmulFp32Accumulation?"1":"0",r);for(let v of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let y=p[v];if(y){if(y!=="disabled"&&y!=="lazyRelease"&&y!=="simple"&&y!=="bucket")throw new Error(`${v} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${y}`);Kt(o,v,y,r)}}}let _=Pe().webgpuRegisterDevice(h);if(_){let[p,w,v]=_;Kt(o,"deviceId",p.toString(),r),Kt(o,"webgpuInstance",w.toString(),r),Kt(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=Et(a,r),l=o.length,c=0,d=0;if(l>0){c=Pe()._malloc(l*Pe().PTR_SIZE),r.push(c),d=Pe()._malloc(l*Pe().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Pe().setValue(c+h*Pe().PTR_SIZE,o[h][0],"*"),Pe().setValue(d+h*Pe().PTR_SIZE,o[h][1],"*")}await Pe()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&xe(`Can't append execution provider: ${a}.`)}},Nh=async e=>{let t=Pe(),r=0,n=[],s=e||{};Lh(s);try{let a=Fh(s.graphOptimizationLevel??"all"),o=Ih(s.executionMode??"sequential"),i=typeof s.logId=="string"?Et(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 c=s.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof s.optimizedModelFilePath=="string"?Et(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,c,d),r===0&&xe("Can't create session options."),s.executionProviders&&await Oh(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);dn(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[h,_]of Object.entries(s.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let p=Et(h,n);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&xe(`Can't set a free dimension override: ${h} - ${_}.`)}return s.extra!==void 0&&Ks(s.extra,"",new WeakSet,(h,_)=>{dn(r,h,_,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}}}),Xr,Zs,hn,ts,ea,ti,ri,ni,fn=ge(()=>{"use strict";Xr=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}`)}},Zs=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}`)}},hn=(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},ts=e=>{switch(e){case"float16":return typeof Float16Array<"u"?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}`)}},ea=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}`)}},ti=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ri=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ni=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}`)}}}),si,Dh=ge(()=>{"use strict";Vo(),si=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 c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zh,lb=ge(()=>{"use strict";fn(),zh=(e,t)=>new(ts(t))(e)}),Bh,Rh,$h,Gh,Vh,Uh,mt,jh=ge(()=>{"use strict";fn(),Bh=["V","I","W","E","F"],Rh=(e,t)=>{console.log(`[${Bh[e]},${new Date().toISOString()}]${t}`)},Vh=(e,t)=>{$h=e,Gh=t},Uh=(e,t)=>{let r=ea(e),n=ea($h);r>=n&&Rh(r,typeof t=="function"?t():t)},mt=(...e)=>{Gh&&Uh(...e)}}),ai,Wh,oi,qh,ii,Hh,li,ci,ui,Qh,Xh,cb=ge(()=>{"use strict";fn(),jh(),ai=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Wh=(e,t)=>{if(t==="int32")return e;let r=ai.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(ts(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i<s;i++){let l=a[i];if(l>2147483647n||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'`)}},oi=(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}`)}},qh=1,ii=()=>qh++,Hh=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),li=(e,t)=>{let r=ai.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},ci=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 li(this.dataType,this.tensorShape)}destroy(){mt("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=oi(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 new Uint8Array(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}},ui=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!=null&&a.input.dataTypes.includes(t))){if(o=Hh.get(t),!o||!(a!=null&&a.input.dataTypes.includes(o)))throw new Error(`WebNN backend does not support data type: ${t}`);mt("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!==li(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=Wh(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 mt("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){var t,r;if(this.activeUpload){let n=(t=this.wrapper)!=null&&t.isDataConverted?oi(this.activeUpload,(r=this.wrapper)==null?void 0:r.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(n):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(n);return}else return n.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Qh=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=ii();return this.tensorTrackersById.set(e,new ui(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){mt("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){mt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0: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=ii(),o=new ci({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new ui(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){mt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(c,1)[0];return h.sessionId=e,h}mt("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 ci({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)}},Xh=(...e)=>new Qh(...e)}),Yh={};Jn(Yh,{WebNNBackend:()=>Kh});var rs,Jh,Kh,ub=ge(()=>{"use strict";fn(),Qr(),lb(),cb(),jh(),rs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Jh=(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])},Kh=class{constructor(e){this.tensorManager=Xh(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,Vh(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){mt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){mt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)mt("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=>Jh(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){mt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=rs.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){mt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=rs.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");mt("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 zh(r,t)}}registerMLTensor(e,t,r,n){let s=rs.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return mt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}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=rs.get(Xr(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!(s!=null&&s.input.dataTypes.includes(n)):!!(s!=null&&s.output.dataTypes.includes(n))}flush(){}}}),Zh,di,hi,Cr,ef,fi,ta,_i,pi,mi,gi,wi,vi,tf=ge(()=>{"use strict";Hr(),ob(),ib(),fn(),Qr(),ei(),Dh(),Zh=(e,t)=>{Pe()._OrtInit(e,t)!==0&&xe("Can't initialize onnxruntime.")},di=async e=>{Zh(e.wasm.numThreads,ea(e.logLevel))},hi=async(e,t)=>{var n,s;(s=(n=Pe()).asyncInit)==null||s.call(n);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 a=e.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:o}),!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(a=>{e.webgpu.device=a}),t==="webnn"){let a=new(ub(),Hs(Yh)).WebNNBackend(e);Pe().webnnInit([a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,i,l,c,d)=>a.ensureTensor(o,i,l,c,d),(o,i)=>{a.uploadTensor(o,i)},async(o,i)=>a.downloadTensor(o,i),(o,i)=>a.registerMLContext(o,i),!!e.trace])}},Cr=new Map,ef=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)}},fi=(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 c=r.HEAPU32[s/4+1],d=[];for(let h=0;h<c;h++){let _=Number(r.getValue(s+8+h*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(s+8+(h+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},ta=e=>{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]},_i=async(e,t)=>{var h,_,p,w;let r,n,s=Pe();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=ta(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await Nh(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let V=[];for(let G of t.externalData){let U=typeof G=="string"?G:G.path,J=typeof G=="string"?G:G.data;V.push(si(J).then(Q=>{s.mountExternalData(U,Q)}))}await Promise.all(V)}for(let V of(t==null?void 0:t.executionProviders)??[])if((typeof V=="string"?V:V.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof V!="string"){let G=V,U=G==null?void 0:G.context,J=G==null?void 0:G.gpuDevice,Q=G==null?void 0:G.deviceType,B=G==null?void 0:G.powerPreference;U?s.currentContext=U:J?s.currentContext=await s.webnnCreateMLContext(J):s.currentContext=await s.webnnCreateMLContext({deviceType:Q,powerPreference:B})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),(h=s.webgpuOnCreateSession)==null||h.call(s,a),a===0&&xe("Can't create a session."),(_=s.jsepOnCreateSession)==null||_.call(s),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[v,y]=ef(a),x=!!(t!=null&&t.enableGraphCapture),k=[],A=[],S=[],C=[],O=[];for(let V=0;V<v;V++){let[G,U,J]=fi(a,V);G===0&&xe("Can't get an input name."),c.push(G);let Q=s.UTF8ToString(G);k.push(Q),S.push(U===0?{name:Q,isTensor:!1}:{name:Q,isTensor:!0,type:Zs(U),shape:J})}for(let V=0;V<y;V++){let[G,U,J]=fi(a,V+v);G===0&&xe("Can't get an output name."),d.push(G);let Q=s.UTF8ToString(G);A.push(Q),C.push(U===0?{name:Q,isTensor:!1}:{name:Q,isTensor:!0,type:Zs(U),shape:J});{if(x&&(t==null?void 0:t.preferredOutputLocation)===void 0){O.push("gpu-buffer");continue}let B=typeof(t==null?void 0:t.preferredOutputLocation)=="string"?t.preferredOutputLocation:((p=t==null?void 0:t.preferredOutputLocation)==null?void 0:p[Q])??"cpu",L=s.webnnIsGraphOutput;if(B==="cpu"&&L&&L(a,Q)){O.push("ml-tensor-cpu-output");continue}if(B!=="cpu"&&B!=="cpu-pinned"&&B!=="gpu-buffer"&&B!=="ml-tensor")throw new Error(`Not supported preferred output location: ${B}.`);if(x&&B!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${B}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);O.push(B)}}let M=null;return O.some(V=>V==="gpu-buffer"||V==="ml-tensor"||V==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&xe("Can't create IO binding."),M={handle:i,outputPreferredLocations:O,outputPreferredLocationsEncoded:O.map(V=>V==="ml-tensor-cpu-output"?"ml-tensor":V).map(V=>ni(V))}),Cr.set(a,[a,c,d,M,x,!1]),[a,k,A,S,C]}catch(v){throw c.forEach(y=>s._OrtFree(y)),d.forEach(y=>s._OrtFree(y)),i!==0&&s._OrtReleaseBinding(i)!==0&&xe("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&xe("Can't release session."),v}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&xe("Can't release session options."),l.forEach(v=>s._free(v)),(w=s.unmountExternalData)==null||w.call(s)}},pi=e=>{var l,c,d;let t=Pe(),r=Cr.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.")),(l=t.jsepOnReleaseSession)==null||l.call(t,e),(c=t.webnnOnReleaseSession)==null||c.call(t,e),(d=t.webgpuOnReleaseSession)==null||d.call(t,e),s.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&xe("Can't release session."),Cr.delete(e)},mi=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Pe(),l=i.PTR_SIZE,c=e[0],d=e[1],h=e[3],_=h,p,w;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let x=e[2].gpuBuffer;w=hn(Xr(c),d);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=k(x,n)}}else if(h==="ml-tensor"){let x=e[2].mlTensor;w=hn(Xr(c),d);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=k(n,x,Xr(c),d)}else{let x=e[2];if(Array.isArray(x)){w=l*x.length,p=i._malloc(w),r.push(p);for(let k=0;k<x.length;k++){if(typeof x[k]!="string")throw new TypeError(`tensor data at index ${k} is not a string`);i.setValue(p+k*l,Et(x[k],r),"*")}}else{let k=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(c!=="string"&&k&&A){let S=i.UTF8ToString(s);if(k(n,S)||A(n,S)){let C=Xr(c);w=hn(C,d),_="ml-tensor";let O=i.webnnCreateTemporaryTensor,M=i.webnnUploadTensor;if(!O||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let V=await O(n,C,d);M(V,new Uint8Array(x.buffer,x.byteOffset,x.byteLength)),p=V}else w=x.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(x.buffer,x.byteOffset,w),p)}else w=x.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(x.buffer,x.byteOffset,w),p)}}let v=i.stackSave(),y=i.stackAlloc(4*d.length);try{d.forEach((k,A)=>i.setValue(y+A*l,k,l===4?"i32":"i64"));let x=i._OrtCreateTensor(Xr(c),p,w,y,d.length,ni(_));x===0&&xe(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(x)}finally{i.stackRestore(v)}},gi=async(e,t,r,n,s,a)=>{var Q,B,L,ee;let o=Pe(),i=o.PTR_SIZE,l=Cr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],h=l[2],_=l[3],p=l[4],w=l[5],v=t.length,y=n.length,x=0,k=[],A=[],S=[],C=[],O=[],M=o.stackSave(),V=o.stackAlloc(v*i),G=o.stackAlloc(v*i),U=o.stackAlloc(y*i),J=o.stackAlloc(y*i);try{[x,k]=Ph(a),Er("wasm prepareInputOutputTensor");for(let Y=0;Y<v;Y++)await mi(r[Y],A,C,e,d[t[Y]],t[Y],p);for(let Y=0;Y<y;Y++)await mi(s[Y],S,C,e,h[n[Y]],v+n[Y],p);Ar("wasm prepareInputOutputTensor");for(let Y=0;Y<v;Y++)o.setValue(V+Y*i,A[Y],"*"),o.setValue(G+Y*i,d[t[Y]],"*");for(let Y=0;Y<y;Y++)o.setValue(U+Y*i,S[Y],"*"),o.setValue(J+Y*i,h[n[Y]],"*");if(_&&!w){let{handle:Y,outputPreferredLocations:N,outputPreferredLocationsEncoded:D}=_;if(d.length!==v)throw new Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${d.length}).`);Er("wasm bindInputsOutputs");for(let R=0;R<v;R++){let re=t[R];await o._OrtBindInput(Y,d[re],A[R])!==0&&xe(`Can't bind input[${R}] for session=${e}.`)}for(let R=0;R<y;R++){let re=n[R];(Q=s[R])!=null&&Q[3]?(O.push(S[R]),o._OrtBindOutput(Y,h[re],S[R],0)!==0&&xe(`Can't bind pre-allocated output[${R}] for session=${e}.`)):o._OrtBindOutput(Y,h[re],0,D[re])!==0&&xe(`Can't bind output[${R}] to ${N[R]} for session=${e}.`)}Ar("wasm bindInputsOutputs"),Cr.set(e,[c,d,h,_,p,!0])}(B=o.jsepOnRunStart)==null||B.call(o,c),(L=o.webnnOnRunStart)==null||L.call(o,c);let H;_?H=await o._OrtRunWithBinding(c,_.handle,y,U,x):H=await o._OrtRun(c,G,V,v,J,y,U,x),H!==0&&xe("failed to call OrtRun().");let ne=[],Se=[];Er("wasm ProcessOutputTensor");for(let Y=0;Y<y;Y++){let N=Number(o.getValue(U+Y*i,"*"));if(N===S[Y]||O.includes(S[Y])){ne.push(s[Y]),N!==S[Y]&&o._OrtReleaseTensor(N)!==0&&xe("Can't release tensor.");continue}let D=o.stackSave(),R=o.stackAlloc(4*i),re=!1,Z,Me=0;try{o._OrtGetTensorData(N,R,R+i,R+2*i,R+3*i)!==0&&xe(`Can't access output tensor data on index ${Y}.`);let Ne=i===4?"i32":"i64",Oe=Number(o.getValue(R,Ne));Me=o.getValue(R+i,"*");let Ke=o.getValue(R+i*2,"*"),Ot=Number(o.getValue(R+i*3,Ne)),Ze=[];for(let ue=0;ue<Ot;ue++)Ze.push(Number(o.getValue(Ke+ue*i,Ne)));o._OrtFree(Ke)!==0&&xe("Can't free memory for tensor dims.");let wt=Ze.reduce((ue,Fe)=>ue*Fe,1);Z=Zs(Oe);let be=_==null?void 0:_.outputPreferredLocations[n[Y]];if(Z==="string"){if(be==="gpu-buffer"||be==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ue=[];for(let Fe=0;Fe<wt;Fe++){let vt=o.getValue(Me+Fe*i,"*"),lr=o.getValue(Me+(Fe+1)*i,"*"),Nt=Fe===wt-1?void 0:lr-vt;ue.push(o.UTF8ToString(vt,Nt))}ne.push([Z,Ze,ue,"cpu"])}else if(be==="gpu-buffer"&&wt>0){let ue=o.webgpuGetBuffer;if(!ue)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Fe=ue(Me),vt=hn(Oe,wt);if(vt===void 0||!ti(Z))throw new Error(`Unsupported data type: ${Z}`);re=!0;{o.webgpuRegisterBuffer(Fe,e,Me);let lr=o.webgpuCreateDownloader(Fe,vt,e);ne.push([Z,Ze,{gpuBuffer:Fe,download:async()=>{let Nt=await lr();return new(ts(Z))(Nt)},dispose:()=>{o._OrtReleaseTensor(N)!==0&&xe("Can't release tensor.")}},"gpu-buffer"])}}else if(be==="ml-tensor"&&wt>0){let ue=o.webnnEnsureTensor,Fe=o.webnnIsGraphInputOutputTypeSupported;if(!ue||!Fe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(hn(Oe,wt)===void 0||!ri(Z))throw new Error(`Unsupported data type: ${Z}`);if(!Fe(e,Z,!1))throw new Error(`preferredLocation "ml-tensor" for ${Z} output is not supported by current WebNN Context.`);let vt=await ue(e,Me,Oe,Ze,!1);re=!0,ne.push([Z,Ze,{mlTensor:vt,download:o.webnnCreateMLTensorDownloader(Me,Z),dispose:()=>{o.webnnReleaseTensorId(Me),o._OrtReleaseTensor(N)}},"ml-tensor"])}else if(be==="ml-tensor-cpu-output"&&wt>0){let ue=o.webnnCreateMLTensorDownloader(Me,Z)(),Fe=ne.length;re=!0,Se.push((async()=>{let vt=[Fe,await ue];return o.webnnReleaseTensorId(Me),o._OrtReleaseTensor(N),vt})()),ne.push([Z,Ze,[],"cpu"])}else{let ue=ts(Z),Fe=new ue(wt);new Uint8Array(Fe.buffer,Fe.byteOffset,Fe.byteLength).set(o.HEAPU8.subarray(Me,Me+Fe.byteLength)),ne.push([Z,Ze,Fe,"cpu"])}}finally{o.stackRestore(D),Z==="string"&&Me&&o._free(Me),re||o._OrtReleaseTensor(N)}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&xe("Can't clear bound outputs."),Cr.set(e,[c,d,h,_,p,!1]));for(let[Y,N]of await Promise.all(Se))ne[Y][2]=N;return Ar("wasm ProcessOutputTensor"),ne}finally{(ee=o.webnnOnRunEnd)==null||ee.call(o,c),o.stackRestore(M),r.forEach(H=>{H&&H[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(H[2].gpuBuffer)}),s.forEach(H=>{H&&H[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(H[2].gpuBuffer)}),A.forEach(H=>o._OrtReleaseTensor(H)),S.forEach(H=>o._OrtReleaseTensor(H)),C.forEach(H=>o._free(H)),x!==0&&o._OrtReleaseRunOptions(x),k.forEach(H=>o._free(H))}},wi=e=>{let t=Pe(),r=Cr.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)},vi=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Sr,bt,_n,ns,ss,ra,yi,na,Yr,Jr,rf,nf,sf,af,of,lf,cf,uf,df=ge(()=>{"use strict";Hr(),tf(),Qr(),Yo(),Sr=()=>!!$e.wasm.proxy&&typeof document<"u",_n=!1,ns=!1,ss=!1,na=new Map,Yr=(e,t)=>{let r=na.get(e);r?r.push(t):na.set(e,[t])},Jr=()=>{if(_n||!ns||ss||!bt)throw new Error("worker not ready")},rf=e=>{switch(e.data.type){case"init-wasm":_n=!1,e.data.err?(ss=!0,yi[1](e.data.err)):(ns=!0,yi[0]()),ra&&(URL.revokeObjectURL(ra),ra=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=na.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},nf=async()=>{if(!ns){if(_n)throw new Error("multiple calls to 'initWasm()' detected.");if(ss)throw new Error("previous call to 'initWasm()' failed.");if(_n=!0,Sr())return new Promise((e,t)=>{bt==null||bt.terminate(),Th().then(([r,n])=>{try{bt=n,bt.onerror=a=>t(a),bt.onmessage=rf,yi=[e,t];let s={type:"init-wasm",in:$e};!s.in.wasm.wasmPaths&&(r||qo)&&(s.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.asyncify-CxOG5pUO.wasm",self.location.href).href,self.location.href).href}),bt.postMessage(s),ra=r}catch(s){t(s)}},t)});try{await Zo($e.wasm),await di($e),ns=!0}catch(e){throw ss=!0,e}finally{_n=!1}}},sf=async e=>{if(Sr())return Jr(),new Promise((t,r)=>{Yr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:$e}};bt.postMessage(n)});await hi($e,e)},af=async e=>Sr()?(Jr(),new Promise((t,r)=>{Yr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};bt.postMessage(n,[e.buffer])})):ta(e),of=async(e,t)=>{if(Sr()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Jr(),new Promise((r,n)=>{Yr("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),bt.postMessage(s,a)})}else return _i(e,t)},lf=async e=>{if(Sr())return Jr(),new Promise((t,r)=>{Yr("release",[t,r]);let n={type:"release",in:e};bt.postMessage(n)});pi(e)},cf=async(e,t,r,n,s,a)=>{if(Sr()){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 Jr(),new Promise((o,i)=>{Yr("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};bt.postMessage(c,vi(l))})}else return gi(e,t,r,n,s,a)},uf=async e=>{if(Sr())return Jr(),new Promise((t,r)=>{Yr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};bt.postMessage(n)});wi(e)}}),bi,hf,ff,db=ge(()=>{"use strict";Hr(),df(),fn(),Vo(),Dh(),bi=(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()}`)}},hf=e=>{switch(e[3]){case"cpu":return new Bt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ti(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Bt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!ri(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Bt.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},ff=class{async fetchModelAndCopyToWasmMemory(e){return af(await si(e))}async loadModel(e,t){Wr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await of(r,t),qr()}async dispose(){return lf(this.sessionId)}async run(e,t,r){Wr();let n=[],s=[];Object.entries(e).forEach(h=>{let _=h[0],p=h[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);n.push(p),s.push(w)});let a=[],o=[];Object.entries(t).forEach(h=>{let _=h[0],p=h[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(p),o.push(w)});let i=n.map((h,_)=>bi(h,()=>`input "${this.inputNames[s[_]]}"`)),l=a.map((h,_)=>h?bi(h,()=>`output "${this.outputNames[o[_]]}"`):null),c=await cf(this.sessionId,s,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??hf(c[h]);return qr(),d}startProfiling(){}endProfiling(){uf(this.sessionId)}}}),_f={};Jn(_f,{OnnxruntimeWebAssemblyBackend:()=>xi,initializeFlags:()=>Mi,wasmBackend:()=>pf});var Mi,xi,pf,hb=ge(()=>{"use strict";Hr(),df(),db(),Mi=()=>{(typeof $e.wasm.initTimeout!="number"||$e.wasm.initTimeout<0)&&($e.wasm.initTimeout=0);let e=$e.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.`),$e.wasm.simd=!1),typeof $e.wasm.proxy!="boolean"&&($e.wasm.proxy=!1),typeof $e.wasm.trace!="boolean"&&($e.wasm.trace=!1),typeof $e.wasm.numThreads!="number"||!Number.isInteger($e.wasm.numThreads)||$e.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)$e.wasm.numThreads=1;else{let t=typeof navigator>"u"?Uy("node:os").cpus().length:navigator.hardwareConcurrency;$e.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},xi=class{async init(e){Mi(),await nf(),await sf(e)}async createInferenceSessionHandler(e,t){let r=new ff;return await r.loadModel(e,t),r}},pf=new xi});Hr(),Hr(),Hr();var fb="1.31.0-dev.20260914-8d85527a0",_b=fh;{let e=(hb(),Hs(_f)).wasmBackend;Ur("webgpu",e,5),Ur("webnn",e,5),Ur("cpu",e,10),Ur("wasm",e,10)}Object.defineProperty($e.versions,"web",{value:fb,enumerable:!0});var pb=Object.freeze({__proto__:null,get InferenceSession(){return Go},get TRACE(){return Xs},get TRACE_EVENT_BEGIN(){return Er},get TRACE_EVENT_END(){return Ar},get TRACE_FUNC_BEGIN(){return Wr},get TRACE_FUNC_END(){return qr},get Tensor(){return Bt},default:_b,get env(){return $e},get registerBackend(){return Ur}});const mb=(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==null?void 0: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==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm;let l,c;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?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));const d=a*s;let h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<s;y++){const x=(e.data[h++]-c[0])*l[0],k=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],S=w===-1?255:(e.data[w++]-c[3])*l[3];n.fillStyle="rgba("+x+","+k+","+A+","+S+")",n.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},gb=(e,t)=>{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==null?void 0: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==null?void 0:t.norm;let c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[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 h=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 p=0,w=1,v=2,y=3,x=0,k=h,A=h*2,S=-1;i==="RGBA"?(x=0,k=h,A=h*2,S=h*3):i==="RGB"?(x=0,k=h,A=h*2):i==="RBG"&&(x=0,A=h,k=h*2),n=r.createImageData(s,a);for(let C=0;C<a*s;p+=_,w+=_,v+=_,y+=_,C++)n.data[p]=(e.data[x++]-d[0])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[y]=S===-1?255:(e.data[S++]-d[3])*c[3]}else throw new Error("Can not access image data");return n},ki=(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");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",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let h=4,_=0,p=1,w=2,v=3,y=0,x=c,k=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,k=c,x=c*2):l==="BGR"&&(k=0,x=c,y=c*2);for(let C=0;C<c;C++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[x++]=(e[p]+o[1])/a[1],d[k++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new St("float32",d,[1,4,r,n]):new St("float32",d,[1,3,r,n])},wb=async(e,t)=>{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")},c=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 h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=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=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){const _=l();_.width=h,_.height=d;const p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,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 h=c(d);if(h!=null){const _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,ki(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{const _=l(),p=c(_);if(!e||!p)return h();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);const v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(ki(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ki(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},vb=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new St({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},yb=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new St({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},bb=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new St({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},Mb=(e,t,r)=>new St({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),pn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),sa=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let mf=!1;const xb=()=>{if(!mf){mf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(pn.set("int64",BigInt64Array),sa.set(BigInt64Array,"int64")),t&&(pn.set("uint64",BigUint64Array),sa.set(BigUint64Array,"uint64")),n?(pn.set("float16",r),sa.set(r,"float16")):pn.set("float16",Uint16Array)}},kb=e=>{let t=1;for(let r=0;r<e.length;r++){const n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},Tb=(e,t)=>{switch(e.location){case"cpu":return new St(e.type,e.data,t);case"cpu-pinned":return new St({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new St({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new St({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new St({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let St=class{constructor(t,r,n){xb();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=pn.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 c=pn.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)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&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof t[0];if(c==="string")s="string",i=t;else if(c==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{const c=sa.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=c,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=kb(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 wb(t,r)}static fromTexture(t,r){return vb(t,r)}static fromGpuBuffer(t,r){return yb(t,r)}static fromMLTensor(t,r){return bb(t,r)}static fromPinnedBuffer(t,r,n){return Mb(t,r,n)}toDataURL(t){return mb(this,t)}toImageData(t){return gb(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 Tb(this,t)}};const Eb=St;var fr={},Ab=Object.defineProperty,as=(e,t)=>{for(var r in t)Ab(e,r,{get:t[r],enumerable:!0})},At={},Zt={},Cb={},Sb="4.3.1",Ti=typeof self<"u",mn=!Mf(At),gf=!Mf(Zt),aa=Ti&&"caches"in self,Pb=typeof globalThis.Deno<"u",oa=Pb&&aa&&!mn,wf=typeof process<"u",vf=wf&&((mw=process==null?void 0:process.release)==null?void 0:mw.name)==="node"&&!oa,Ei=typeof window<"u"&&typeof window.document<"u",Ai=Ti&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((gw=self.constructor)==null?void 0:gw.name),Fb=Ei||Ai||oa,Ib=vf||typeof navigator<"u"&&"gpu"in navigator,Lb=typeof navigator<"u"&&"ml"in navigator,Ob=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",Nb=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",Db=typeof ServiceWorkerGlobalScope<"u"&&Ti&&self instanceof ServiceWorkerGlobalScope,zb=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent;if(!((navigator.vendor||"").indexOf("Apple")>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android")))return!1;const r=e.match(/Version\/(\d+)/);return r?parseInt(r[1],10)<26:!1},Bb=zb(),pe=Object.freeze({IS_BROWSER_ENV:Ei,IS_WEBWORKER_ENV:Ai,IS_WEB_ENV:Fb,IS_SERVICE_WORKER_ENV:Db,IS_DENO_WEB_RUNTIME:oa,IS_WEB_CACHE_AVAILABLE:aa,IS_WEBGPU_AVAILABLE:Ib,IS_WEBNN_AVAILABLE:Lb,IS_SAFARI_BELOW_26:Bb,IS_PROCESS_AVAILABLE:wf,IS_NODE_ENV:vf,IS_FS_AVAILABLE:mn,IS_PATH_AVAILABLE:gf,IS_CRYPTO_AVAILABLE:Ob,IS_CHROME_AVAILABLE:Nb}),Ci=mn&&gf,ia="./";if(Ci){const e=self.location.href;e?ia=Zt.dirname(Zt.dirname(Cb.fileURLToPath(e))):typeof __dirname<"u"&&(ia=Zt.dirname(__dirname))}var Rb=Ci?Zt.join(ia,"/.cache/"):null,yf="/models/",$b=Ci?Zt.join(ia,yf):yf,Gb=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Rt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),bf=Rt.WARNING,ve={version:Sb,backends:{onnx:{}},get logLevel(){return bf},set logLevel(e){var t,r;bf=e,(r=(t=ve.backends.onnx)==null?void 0:t.setLogLevel)==null||r.call(t,e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Ei||Ai||oa),localModelPath:$b,useFS:mn,useBrowserCache:aa,useFSCache:mn,cacheDir:Rb,useCustomCache:!1,customCache:null,useWasmCache:aa||mn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:Gb};function Mf(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 Pr(e,t){e&&e(t)}var la=class extends gt{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=new Map}_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 Vb(e){return Number.isInteger(e)||typeof e=="bigint"}function xf(e){return e==null||e===-1}function kf(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function er(...e){return Array.prototype.concat.apply([],e)}function Ub(...e){return e.reduce((t,r)=>t.flatMap(n=>r.map(s=>[n,s])))}function ca(e,t){return Math.abs((e+t)%(2*t)-t)}function rt(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function jb(e,t){let r=0;for(const n of e)n===t&&++r;return r}var he={error(...e){ve.logLevel<=Rt.ERROR&&console.error(...e)},warn(...e){ve.logLevel<=Rt.WARNING&&console.warn(...e)},info(...e){ve.logLevel<=Rt.INFO&&console.log(...e)},debug(...e){ve.logLevel<=Rt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Wb=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;s<r.length;++s){const a=r[s];n=n[a]??(n[a]=Object.create(null))}n.end=r}return t}split(e){const t=[],r=e.length;let n=0,s=0;for(;s<r;){let a=this.trie,o=null,i=s;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(s>n&&t.push(e.slice(n,s)),t.push(o),s+=o.length,n=s):++s}return n<r&&t.push(e.slice(n)),t}},Tf=Wb,qb=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},Hb=qb,Ef=(e,t)=>{try{return new RegExp(e,t)}catch(r){if(!(r instanceof SyntaxError))throw r;const n=new Map,s=e.replace(/(\\[pP])\{([^}=]+)\}/g,(a,o,i,l)=>{let c=0;for(let h=l-1;h>=0&&e[h]==="\\";--h)++c;if(c%2===1)return a;let d=n.get(i);if(d===void 0){try{new RegExp(`\\p{${i}}`,"u"),d=i}catch{d=`Script=${i}`}n.set(i,d)}return`${o}{${d}}`});if(s===e)throw r;try{return new RegExp(s,t)}catch{throw r}}},Si=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"),ua=(e,t=!0)=>{if(e.Regex!==void 0){const r=u0(i0(e.Regex));return Ef(r,"gu")}else if(e.String!==void 0){const r=d0(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},gn="\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}",Af=`${gn}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,tr=`[${Af}]`,Cf=`[^${Af}]`,Qb=`(?:(?<!${tr})(?=${tr})|(?<=${tr})(?!${tr}))`,Xb=`(?:(?<!${tr})(?!${tr})|(?<=${tr})(?=${tr}))`,Yb="(?:(?<![\\s\\S])|(?<=\\n))",Jb="(?:(?=\\n)|(?![\\s\\S]))",os="0-9A-Fa-f",Kb=new Map([["A","(?<![\\s\\S])"],["z","(?![\\s\\S])"],["Z","(?=\\n?(?![\\s\\S]))"],["h",`[${os}]`],["H",`[^${os}]`],["w",tr],["W",Cf],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["b",Qb],["B",Xb],["a","\\x07"],["e","\\x1B"]]),Zb=new Map([["h",os],["w",gn],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["a","\\x07"],["e","\\x1B"]]),e0=new Map([["W",`[^${gn}]`],["H",`[^${os}]`]]),Sf=new Map([[`
|
|
11
|
+
`,"\\n"],["\r","\\r"],[" ","\\t"],["\f","\\f"],["\v","\\v"]]),t0=new Map([["alpha","\\p{Alphabetic}"],["alnum","\\p{Alphabetic}\\p{Nd}"],["digit","\\p{Nd}"],["lower","\\p{Lowercase}"],["upper","\\p{Uppercase}"],["space","\\p{White_Space}"],["blank","\\t\\p{Zs}"],["punct","\\p{P}\\p{S}"],["cntrl","\\p{Cc}"],["word",gn],["xdigit",os]]),Pf="^$\\.*+?()[]{}|/",r0=/^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,Ff=/^\\([pPxu])\{([^}]*)\}/,n0=/^\{(\d+(?:,\d*)?|,\d+)\}/,s0=new RegExp("^\\[:(\\^?)(\\p{Alphabetic}+):\\]","u"),a0=/^\[:\^:\]/,o0=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,If=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,Lf=e=>e>="A"&&e<="Z"||e>="a"&&e<="z",da=(e,t)=>String.fromCodePoint(e.codePointAt(t)),Of=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;const t=Number.parseInt(e,16);if(t>127)return null;const r=String.fromCharCode(t);return Lf(r)?`[${r.toLowerCase()}${r.toUpperCase()}]`:null},i0=e=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,"[^()|\\s$1]"),Nf="[\\s\\S]",Df=256,zf=()=>({fragment:"",alternatives:[],tail:null,contains_complex_set:!1}),Pi=e=>{throw new SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},ha=(e,t,r,n=!0)=>{e.tail==="range"&&Pi(r),e.alternatives.push(t),e.tail="set",e.contains_complex_set=e.contains_complex_set||n},Fr=(e,t,r=!1,n=-1)=>{if(r&&e.tail==="range"&&Pi(n),e.tail==="range"){e.fragment+=t,e.tail="complete_range";return}e.fragment+=t,e.tail=r?"set":"scalar",e.contains_complex_set=e.contains_complex_set||r},l0=(e,t,r)=>{const n=Ff.exec(e.slice(t));if(n){const[_,p,w]=n;if(p==="P"&&w==="Word")ha(r,`[^${gn}]`,t);else{const v=p==="x"?`\\u{${w}}`:p==="p"&&w==="Word"?gn:_;Fr(r,v,p==="p"||p==="P",t)}return t+_.length}const s=If.exec(e.slice(t));if(s)return Fr(r,s[0]),t+s[0].length;if(t+1>=e.length)throw new SyntaxError(`Unterminated escape in character class at index ${t}`);const a=da(e,t+1),o=t+1+a.length,i=Sf.get(a);if(i!==void 0)return Fr(r,i),o;const l=e0.get(a);if(l!==void 0)return ha(r,l,t),o;const c=Zb.get(a);let d,h=!1;return c!==void 0?(d=c,h=a!=="a"&&a!=="e"):/[A-Za-z0-9]/.test(a)?d=`\\${a}`:Pf.includes(a)||a==="-"?d=`\\${a}`:d=a,Fr(r,d,h,t),o},Bf=e=>e.length===1?e[0]:`(?:(?=(?:${e.join("|")}))${Nf})`,Rf=e=>{const t=e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives];return Bf(t)},c0=e=>{const t=Ef(`^(?:${e})$`,"u");let r="";for(let n=0;n<26;++n){const s=String.fromCharCode(65+n),a=String.fromCharCode(97+n),o=t.test(s),i=t.test(a);o!==i&&(r+=o?a:s)}return r},$f=(e,t,r,n=!0,s=1)=>{if(s>Df)throw new SyntaxError(`Maximum character-class nesting depth of ${Df} exceeded at index ${t}`);let a=t+1;const o=e[a]==="^";o&&++a;const i=a,l=[zf()];let c=l[0],d=!1;for(;a<e.length;){const h=da(e,a);if(h==="\\"){a=l0(e,a,c);continue}if(h==="]"){if(a===i){Fr(c,"\\]"),++a;continue}if(c.tail===null)throw l.length>1?new SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):new SyntaxError(`Empty character class at index ${t}`);const _=l.some(k=>k.contains_complex_set);if(o&&l.length>1&&d)throw new SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);const p=Rf(l[0]);let w=p;if(l.length>1){let k="";for(let A=1;A<l.length;++A)k+=`(?=${Rf(l[A])})`;w=`(?:${k}${p})`}const v=l.length===1&&c.alternatives.length===0;let y=c.fragment;if(r&&n){const k=c0(w);k.length>0&&(v?(y+=k,w=`[${y}]`):w=Bf([w,`[${k}]`]))}return{atom:o?v?`[^${y}]`:`(?:(?!${w})${Nf})`:w,end:a+1,negated:o,contains_complex_set:_,contains_nested_negated_complex_set:d}}if(e.startsWith("&&",a)){if(c.tail===null)throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);c=zf(),l.push(c),a+=2;continue}if(h==="["){const _=e.slice(a);if(a0.test(_))throw new SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);const p=s0.exec(_);if(p){const[,v,y]=p,x=t0.get(y);if(x===void 0)throw new SyntaxError(`Unsupported POSIX character class "${y}" at index ${a}`);if(r&&v&&(y==="lower"||y==="upper"))throw new SyntaxError(`Unsupported negated POSIX ${y} class inside an inline case-insensitive group`);v?ha(c,`[^${x}]`,a):Fr(c,x,!0,a),a+=p[0].length;continue}if(o0.test(_))throw new SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);const w=$f(e,a,r,!1,s+1);ha(c,w.atom,a,w.contains_complex_set),d||(d=w.contains_nested_negated_complex_set||w.negated&&w.contains_complex_set),a=w.end;continue}if(h==="-"){const _=e[a+1]==="]"||e.startsWith("&&",a+1);c.tail==="set"&&!_&&Pi(a),c.tail===null||c.tail==="range"||c.tail==="complete_range"||_?Fr(c,"\\-"):(c.fragment+="-",c.tail="range"),++a;continue}Fr(c,h==="^"&&c.fragment.length===0?"\\^":h),a+=h.length}throw new SyntaxError(`${l.length>1?"Unterminated character-class intersection":"Unterminated character class"} at index ${t}`)},u0=e=>{var i;let t="",r=-1,n=!1,s=!1;const a=[],o=l=>{r=t.length,t+=l,n=!1};for(let l=0;l<e.length;){const c=da(e,l);if(c==="\\"){const d=Ff.exec(e.slice(l));if(d){const[y,x,k]=d;let A=y;if(x==="x"){const S=`\\u{${k}}`;A=s?Of(k)??S:S}else k==="Word"&&(A=x==="p"?tr:Cf);o(A),l+=y.length;continue}const h=If.exec(e.slice(l));if(h){const y=h[0],x=s&&y[1]!=="c"?Of(y.slice(2))??y:y;o(x),l+=y.length;continue}if(l+1>=e.length){t+=c;break}const _=da(e,l+1);if(l+=1+_.length,_==="G")continue;const p=Sf.get(_);if(p!==void 0){o(p);continue}const w=Kb.get(_);let v;w!==void 0?v=w:/[A-Za-z0-9]/.test(_)?v=`\\${_}`:Pf.includes(_)?v=`\\${_}`:v=_,o(v);continue}switch(c){case"[":{const d=$f(e,l,s);o(d.atom),l=d.end;continue}case"]":o("\\]"),++l;continue;case".":o("[^\\n]"),++l;continue;case"^":o(Yb),++l;continue;case"$":o(Jb),++l;continue;case"(":{const d=e.startsWith("(?i:",l),h=d?"(?i:":((i=r0.exec(e.slice(l)))==null?void 0:i[0])??"(",_=d||h==="(?>"?"(?:":h;a.push([t.length,s]),d&&(s=!0),t+=_,n=!1,l+=h.length;continue}case")":t+=c,[r,s]=a.pop()??[-1,!1],n=!1,++l;continue;case"|":t+=c,r=-1,n=!1,++l;continue;case"{":{const d=n0.exec(e.slice(l));if(!d||r<0){o("\\{"),++l;continue}const h=d[1].startsWith(",")?`0${d[1]}`:d[1];l+=d[0].length;const _=e[l];_==="+"||_==="*"?(t=`${t.slice(0,r)}(?:${t.slice(r)}{${h}})${_}`,++l):t+=`{${h}}`,n=!0;continue}case"}":o("\\}"),++l;continue;case"+":if(n){++l;continue}t+=c,n=!0,++l;continue;case"*":case"?":t+=c,n=!0,++l;continue;default:o(s&&Lf(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),l+=c.length;continue}}return t},d0=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h0=(e,t,r)=>{const n=[];let s=0;for(;s<e.length;){if(n.push(e[s]),(t.get(e[s])??r)!==r){++s;continue}for(;++s<e.length&&(t.get(e[s])??r)===r;)t.get(n.at(-1))!==r&&(n[n.length-1]+=e[s])}return n},f0=e=>e>=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,_0=e=>Number.isInteger(e)||typeof e=="bigint",p0=e=>{let t=0;for(const r of e)++t;return t},m0=e=>Gf(e.toLowerCase()),$t=(...e)=>Array.prototype.concat.apply([],e),Fi=e=>new Map(Object.entries(e)),g0=(e,t)=>{const r=[];let n=0;for(const s of e.matchAll(t)){const a=s[0];n<s.index&&r.push(e.slice(n,s.index)),a.length>0&&r.push(a),n=s.index+a.length}return n<e.length&&r.push(e.slice(n)),r},Gf=e=>e.replace(new RegExp("\\p{M}","gu"),""),Vf=(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},w0=e=>e.match(/\S+/g)||[],v0=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},is=v0,y0=class extends is{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},_r=y0,b0=class extends _r{tokenize_chinese_chars(e){const t=[];for(let r=0;r<e.length;++r){const n=e[r],s=n.charCodeAt(0);f0(s)?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
|
|
12
|
+
`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){const t=[];for(const r of e){const n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},M0=b0,x0=class extends _r{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("~")?e=e.split("~").map(r=>r.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},k0=x0,T0=class extends _r{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Uf(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},E0=T0,A0=class extends _r{constructor(e){super(e),this.pattern=ua(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??"")}},C0=A0,S0=class extends _r{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},fa=S0,P0=class extends fa{constructor(){super(...arguments),this.form="NFC"}},F0=P0,I0=class extends fa{constructor(){super(...arguments),this.form="NFD"}},L0=I0,O0=class extends fa{constructor(){super(...arguments),this.form="NFKC"}},N0=O0,D0=class extends fa{constructor(){super(...arguments),this.form="NFKD"}},z0=D0,B0=class extends _r{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}},R0=B0,$0=class extends _r{normalize(e){return Gf(e)}},G0=$0,V0=class extends _r{normalize(e){return e.toLowerCase()}},U0=V0,j0=class extends _r{normalize(e){return e=this.config.prepend+e,e}},W0=j0;function q0(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new M0(e);case"Precompiled":return new k0(e);case"Sequence":return new E0(e);case"Replace":return new C0(e);case"NFC":return new F0(e);case"NFD":return new L0(e);case"NFKC":return new N0(e);case"NFKD":return new z0(e);case"Strip":return new R0(e);case"StripAccents":return new G0(e);case"Lowercase":return new U0(e);case"Prepend":return new W0(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Uf=q0,H0=class extends is{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)}},Gt=H0,jf=(()=>{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]]))})(),Q0=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),X0=Q0(jf),_a="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Y0=class extends Gt{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=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=jf,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(""))}},J0=Y0,K0=class extends Gt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Z0=K0,eM=class extends Gt{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]}},tM=eM,rM=class extends Gt{constructor(e){super(),this.config=e,this.pattern=ua(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){var t;return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(r=>r):((t=this.config.behavior)==null?void 0:t.toLowerCase())==="removed"?e.split(this.pattern).filter(r=>r):g0(e,this.pattern)}},nM=rM,sM=class extends Gt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${_a}]+|[${_a}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},aM=sM,oM=class extends Gt{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)||[]}},iM=oM,lM=class extends Gt{constructor(){super(),this.pattern=new RegExp(`[^\\s${_a}]+|[${_a}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},cM=lM,uM=class extends Gt{constructor(e){super(),this.config=e,this.pattern=ua(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},dM=uM,hM=class extends Gt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Wf(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},fM=hM,_M=class extends Gt{pre_tokenize_text(e){return w0(e)}},pM=_M,mM=class extends Gt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},gM=mM;function wM(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new cM;case"Sequence":return new fM(e);case"Whitespace":return new Z0;case"WhitespaceSplit":return new pM;case"Metaspace":return new tM(e);case"ByteLevel":return new J0(e);case"Split":return new nM(e);case"Punctuation":return new aM(e);case"Digits":return new iM(e);case"Replace":return new dM(e);case"FixedLength":return new gM(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var Wf=wM,vM=class extends is{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=h0(t,this.tokens_to_ids,this.unk_token_id)),t}},pa=vM,yM=class extends pa{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Fi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){const t=[];for(const r of e){const n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0;const o=[];for(;a<n.length;){let i=n.length,l=null;for(;a<i;){let c=n.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},qf=yM,Hf=class Ry{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new Ry(!1,new Map)}},bM=class{constructor(){this.root=Hf.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=Hf.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e,t=0){let r=this.root;if(r===void 0)return;let n="";for(let s=t;s<e.length;++s){const a=e[s];if(n+=a,r=r.children.get(a),r===void 0)return;r.is_leaf&&(yield n)}}},MM=bM,Ii=class $y{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new $y(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},xM=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 Ii(this.bos_token_id??0,0,0,0,0),s=new Ii(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 Ii(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 c of this.end_nodes[t]){const d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.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)}},kM=xM;function TM(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}var EM=class extends pa{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[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=TM(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new MM,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let n=0;for(;n<t.length;){let s=!1;const a=this.trie.common_prefix_search(t,n);for(const o of a){const i=this.tokens_to_ids.get(o),l=this.scores[i],c=p0(o);e.insert(n,c,l,i),!s&&c===r&&(s=!0)}s||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){const t=new kM(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const r of e){const n=this.tokenize(r);t.push(...n)}return t}},Qf=EM,AM=class{constructor(e=(r,n)=>r>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.size<this._max_size)this._heap.push(t),this._sift_up();else{const r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&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.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},CM=AM,SM=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},PM=SM,FM=class extends pa{constructor(e){super(e),this.tokens_to_ids=Fi(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 PM(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 CM((i,l)=>i.score<l.score);let a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){const l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(s,o),o=l}for(;!s.is_empty();){const i=s.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){const c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}const l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let i=a;i!==null;i=i.next)n.push(i.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){const r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){const t=[];for(const r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}const n=this.bpe(r);for(const s of n)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(s)).map(o=>`<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}},Xf=FM,IM=class extends pa{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=Fi(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}},LM=IM;function OM(e,t){switch(e.type){case"WordPiece":return new qf(e);case"Unigram":return new Qf(e,t.eos_token);case"BPE":return new Xf(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Qf(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Xf(e):new qf(e):new LM(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==null?void 0:e.type}`)}}var NM=OM,DM=class extends is{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ls=DM,zM=class extends ls{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=$t(s,e),a=$t(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=$t(s,t),a=$t(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},BM=zM,RM=class extends ls{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},$M=RM,GM=class extends ls{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=$t([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=$t(e,s,t,a),n=$t(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},VM=GM,UM=class extends ls{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=$t([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=$t(e,s,t,a),n=$t(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},jM=UM,WM=class extends ls{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>Yf(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}},qM=WM;function HM(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new BM(e);case"ByteLevel":return new $M(e);case"BertProcessing":return new VM(e);case"RobertaProcessing":return new jM(e);case"Sequence":return new qM(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var Yf=HM,QM=class extends is{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("")}},Vt=QM,XM=class extends Vt{constructor(e){super(e),this.byte_decoder=X0,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}},YM=XM,JM=class extends Vt{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=Si(t)),t})}},KM=JM,ZM=class extends Vt{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}},ex=ZM,tx=class extends Vt{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},rx=tx,nx=class extends Vt{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;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let n=t.filter(s=>s!==this.pad_token).join("");return this.cleanup&&(n=Si(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},sx=nx,ax=class extends Vt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Jf(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},ox=ax,ix=class extends Vt{constructor(e){super(e),this.pattern=ua(this.config.pattern)}decode_chain(e){const t=this.config.content??"",r=this.pattern;return r===null?e:e.map(n=>n.replaceAll(r,t))}},lx=ix,cx=class extends Vt{decode_chain(e){return[e.join("")]}},ux=cx,dx=class extends Vt{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<this.start&&t[s]===this.content;++s){r=s+1;continue}let n=t.length;for(let s=0;s<this.stop;++s){const a=t.length-s-1;if(t[a]===this.content){n=a;continue}else break}return t.slice(r,n)})}},hx=dx,fx=class extends Vt{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const n of e){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){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}},_x=fx;function px(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new YM(e);case"WordPiece":return new KM(e);case"Metaspace":return new ex(e);case"BPEDecoder":return new rx(e);case"CTC":return new sx(e);case"Sequence":return new ox(e);case"Replace":return new lx(e);case"Fuse":return new ux(e);case"Strip":return new hx(e);case"ByteFallback":return new _x(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Jf=px,mx=class{constructor(e,t){const r=Vf(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=Vf(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=Uf(this.tokenizer.normalizer),this.pre_tokenizer=Wf(this.tokenizer.pre_tokenizer),this.model=NM(this.tokenizer.model,this.config),this.post_processor=Yf(this.tokenizer.post_processor),this.decoder=Jf(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 Hb(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 Tf(s),this.splitter_normalized=new Tf(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=>{var c;return((c=this.added_tokens_map.get(l))==null?void 0:c.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||!_0(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=Si(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<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((r,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=m0(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<s.length-1&&(s[o+1]=s[o+1].trimStart()))}),s.flatMap(a=>{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:$t(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<this.model.vocab.length;++r){const n=this.model.vocab[r];(e||!this.added_tokens_map.has(n))&&t.set(n,r)}return t}},gx=mx,wx=Object.defineProperty,vx=(e,t,r)=>t in e?wx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,yx=(e,t,r)=>(vx(e,t+"",r),r),$=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ExponentiationBinaryOperator:"ExponentiationBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Pt=class{constructor(e,t){this.value=e,this.type=t}};function Kf(e){return/\w/.test(e)}function Kr(e){return/[0-9]/.test(e)}function Zf(e){return/\s/.test(e)}var bx=[["{%",$.OpenStatement],["%}",$.CloseStatement],["{{",$.OpenExpression],["}}",$.CloseExpression],["(",$.OpenParen],[")",$.CloseParen],["{",$.OpenCurlyBracket],["}",$.CloseCurlyBracket],["[",$.OpenSquareBracket],["]",$.CloseSquareBracket],[",",$.Comma],[".",$.Dot],[":",$.Colon],["|",$.Pipe],["<=",$.ComparisonBinaryOperator],[">=",$.ComparisonBinaryOperator],["==",$.ComparisonBinaryOperator],["!=",$.ComparisonBinaryOperator],["<",$.ComparisonBinaryOperator],[">",$.ComparisonBinaryOperator],["+",$.AdditiveBinaryOperator],["-",$.AdditiveBinaryOperator],["~",$.AdditiveBinaryOperator],["**",$.ExponentiationBinaryOperator],["*",$.MultiplicativeBinaryOperator],["//",$.MultiplicativeBinaryOperator],["/",$.MultiplicativeBinaryOperator],["%",$.MultiplicativeBinaryOperator],["=",$.Equals]],Mx=new Map([["n",`
|
|
13
|
+
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function xx(e,t={}){return e.endsWith(`
|
|
14
|
+
`)&&(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*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(r,n,s,a,o)=>(s?"":n)+(a?"":o))}function kx(e,t={}){var c,d,h;const r=[],n=xx(e,t);let s=0,a=0;const o=_=>{let p="";for(;_(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const w=n[s++],v=Mx.get(w);if(v===void 0)throw new SyntaxError(`Unexpected escaped character: ${w}`);p+=v;continue}if(p+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{const _=r.at(-1);_&&_.type===$.Text&&(_.value=_.value.trimEnd(),_.value===""&&r.pop())},l=()=>{for(;s<n.length&&Zf(n[s]);)++s};e:for(;s<n.length;){const _=(c=r.at(-1))==null?void 0:c.type;if(_===void 0||_===$.CloseStatement||_===$.CloseExpression||_===$.Comment){let w="";for(;s<n.length&&!(n[s]==="{"&&(n[s+1]==="%"||n[s+1]==="{"||n[s+1]==="#"));)w+=n[s++];if(w.length>0){r.push(new Pt(w,$.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const w=n[s]==="-";w&&++s;let v="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");v+=n[s++]}const y=v.endsWith("-");y&&(v=v.slice(0,-1)),w&&i(),r.push(new Pt(v,$.Comment)),s+=2,y&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new Pt("{%",$.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new Pt("{{",$.OpenExpression)),a=0,s+=3;continue}if(o(Zf),n.slice(s,s+3)==="-%}"){r.push(new Pt("%}",$.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Pt("}}",$.CloseExpression)),s+=3,l();continue}const p=n[s];if(p==="-"||p==="+"){const w=(d=r.at(-1))==null?void 0:d.type;if(w===$.Text||w===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(w){case $.Identifier:case $.NumericLiteral:case $.StringLiteral:case $.CloseParen:case $.CloseSquareBracket:break;default:{++s;let v=o(Kr);if(v.length>0&&n[s]==="."&&Kr(n[s+1])){++s;const y=o(Kr);v=`${v}.${y}`}r.push(new Pt(`${p}${v}`,v.length>0?$.NumericLiteral:$.UnaryOperator));continue}}}for(const[w,v]of bx){if(w==="}}"&&a>0)continue;if(n.slice(s,s+w.length)===w){r.push(new Pt(w,v)),v===$.OpenExpression?a=0:v===$.OpenCurlyBracket?++a:v===$.CloseCurlyBracket&&--a,s+=w.length;continue e}}if(p==="'"||p==='"'){++s;const w=o(v=>v!==p);r.push(new Pt(w,$.StringLiteral)),++s;continue}if(Kr(p)){let w=o(Kr);if(((h=r.at(-1))==null?void 0:h.type)!==$.Dot&&n[s]==="."&&Kr(n[s+1])){++s;const v=o(Kr);w=`${w}.${v}`}r.push(new Pt(w,$.NumericLiteral));continue}if(Kf(p)){const w=o(Kf);r.push(new Pt(w,$.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Ft=class{constructor(){T(this,"type","Statement")}},Tx=class extends Ft{constructor(t){super();T(this,"type","Program");this.body=t}},Ex=class extends Ft{constructor(t,r,n){super();T(this,"type","If");this.test=t,this.body=r,this.alternate=n}},Ax=class extends Ft{constructor(t,r,n,s){super();T(this,"type","For");this.loopvar=t,this.iterable=r,this.body=n,this.defaultBlock=s}},Cx=class extends Ft{constructor(){super(...arguments);T(this,"type","Break")}},Sx=class extends Ft{constructor(){super(...arguments);T(this,"type","Continue")}},Px=class extends Ft{constructor(t,r,n){super();T(this,"type","Set");this.assignee=t,this.value=r,this.body=n}},Fx=class extends Ft{constructor(t,r,n){super();T(this,"type","Macro");this.name=t,this.args=r,this.body=n}},Ix=class extends Ft{constructor(t){super();T(this,"type","Comment");this.value=t}},Mt=class extends Ft{constructor(){super(...arguments);T(this,"type","Expression")}},Lx=class extends Mt{constructor(t,r,n){super();T(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=n}},e_=class extends Mt{constructor(t,r){super();T(this,"type","CallExpression");this.callee=t,this.args=r}},Ir=class extends Mt{constructor(t){super();T(this,"type","Identifier");this.value=t}},wn=class extends Mt{constructor(t){super();T(this,"type","Literal");this.value=t}},Ox=class extends wn{constructor(){super(...arguments);T(this,"type","IntegerLiteral")}},Nx=class extends wn{constructor(){super(...arguments);T(this,"type","FloatLiteral")}},t_=class extends wn{constructor(){super(...arguments);T(this,"type","StringLiteral")}},Dx=class extends wn{constructor(){super(...arguments);T(this,"type","ArrayLiteral")}},r_=class extends wn{constructor(){super(...arguments);T(this,"type","TupleLiteral")}},zx=class extends wn{constructor(){super(...arguments);T(this,"type","ObjectLiteral")}},vn=class extends Mt{constructor(t,r,n){super();T(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=n}},Bx=class extends Mt{constructor(t,r){super();T(this,"type","FilterExpression");this.operand=t,this.filter=r}},Rx=class extends Ft{constructor(t,r){super();T(this,"type","FilterStatement");this.filter=t,this.body=r}},$x=class extends Mt{constructor(t,r){super();T(this,"type","SelectExpression");this.lhs=t,this.test=r}},Gx=class extends Mt{constructor(t,r,n){super();T(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=n}},n_=class extends Mt{constructor(t,r){super();T(this,"type","UnaryExpression");this.operator=t,this.argument=r}},Vx=class extends Mt{constructor(t=void 0,r=void 0,n=void 0){super();T(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=n}},Li=class extends Mt{constructor(t,r){super();T(this,"type","KeywordArgumentExpression");this.key=t,this.value=r}},Ux=class extends Mt{constructor(t){super();T(this,"type","SpreadExpression");this.argument=t}},jx=class extends Mt{constructor(t){super();T(this,"type","KeywordSpreadExpression");this.argument=t}},Wx=class extends Ft{constructor(t,r,n){super();T(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=n}},qx=class extends Mt{constructor(t,r,n){super();T(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=n}};function Hx(e){const t=new Tx([]);let r=0;function n(N,D){const R=e[r++];if(!R||R.type!==N)throw new Error(`Parser Error: ${D}. ${R.type} !== ${N}.`);return R}function s(N){if(!l(N))throw new SyntaxError(`Expected ${N}`);++r}function a(){switch(e[r].type){case $.Comment:return new Ix(e[r++].value);case $.Text:return c();case $.OpenStatement:return d();case $.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...N){return r+N.length<=e.length&&N.every((D,R)=>D===e[r+R].type)}function i(...N){var D,R,re;return((D=e[r])==null?void 0:D.type)===$.OpenStatement&&((R=e[r+1])==null?void 0:R.type)===$.Identifier&&N.includes((re=e[r+1])==null?void 0:re.value)}function l(...N){return r+N.length<=e.length&&N.every((D,R)=>e[r+R].type==="Identifier"&&D===e[r+R].value)}function c(){return new t_(n($.Text,"Expected text token").value)}function d(){if(n($.OpenStatement,"Expected opening statement token"),e[r].type!==$.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const N=e[r].value;let D;switch(N){case"set":++r,D=_();break;case"if":++r,D=p(),n($.OpenStatement,"Expected {% token"),s("endif"),n($.CloseStatement,"Expected %} token");break;case"macro":++r,D=w(),n($.OpenStatement,"Expected {% token"),s("endmacro"),n($.CloseStatement,"Expected %} token");break;case"for":++r,D=y(),n($.OpenStatement,"Expected {% token"),s("endfor"),n($.CloseStatement,"Expected %} token");break;case"call":{++r;let R=null;o($.OpenParen)&&(R=U("parameters"));const re=Y();if(re.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Z=U("call");n($.CloseStatement,"Expected closing statement token");const Me=[];for(;!i("endcall");)Me.push(a());n($.OpenStatement,"Expected '{%'"),s("endcall"),n($.CloseStatement,"Expected closing statement token");const Ne=new e_(re,Z);D=new Wx(Ne,R,Me);break}case"break":++r,n($.CloseStatement,"Expected closing statement token"),D=new Cx;break;case"continue":++r,n($.CloseStatement,"Expected closing statement token"),D=new Sx;break;case"filter":{++r;let R=Y();R instanceof Ir&&o($.OpenParen)&&(R=G(R)),n($.CloseStatement,"Expected closing statement token");const re=[];for(;!i("endfilter");)re.push(a());n($.OpenStatement,"Expected '{%'"),s("endfilter"),n($.CloseStatement,"Expected '%}'"),D=new Rx(R,re);break}default:throw new SyntaxError(`Unknown statement type: ${N}`)}return D}function h(){n($.OpenExpression,"Expected opening expression token");const N=x();return n($.CloseExpression,"Expected closing expression token"),N}function _(){const N=v();let D=null;const R=[];if(o($.Equals))++r,D=v();else{for(n($.CloseStatement,"Expected %} token");!i("endset");)R.push(a());n($.OpenStatement,"Expected {% token"),s("endset")}return n($.CloseStatement,"Expected closing statement token"),new Px(N,D,R)}function p(){const N=x();n($.CloseStatement,"Expected closing statement token");const D=[],R=[];for(;!i("elif","else","endif");)D.push(a());if(i("elif")){++r,++r;const re=p();R.push(re)}else if(i("else"))for(++r,++r,n($.CloseStatement,"Expected closing statement token");!i("endif");)R.push(a());return new Ex(N,D,R)}function w(){const N=Y();if(N.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const D=U("parameters");n($.CloseStatement,"Expected closing statement token");const R=[];for(;!i("endmacro");)R.push(a());return new Fx(N,D,R)}function v(N=!1){const D=N?Y:x,R=[D()],re=o($.Comma);for(;re&&(++r,R.push(D()),!!o($.Comma)););return re?new r_(R):R[0]}function y(){const N=v(!0);if(!(N instanceof Ir||N instanceof r_))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${N.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const D=x();n($.CloseStatement,"Expected closing statement token");const R=[];for(;!i("endfor","else");)R.push(a());const re=[];if(i("else"))for(++r,++r,n($.CloseStatement,"Expected closing statement token");!i("endfor");)re.push(a());return new Ax(N,D,R,re)}function x(){return k()}function k(){const N=A();if(l("if")){++r;const D=A();if(l("else")){++r;const R=k();return new qx(D,N,R)}else return new $x(N,D)}return N}function A(){let N=S();for(;l("or");){const D=e[r];++r;const R=S();N=new vn(D,N,R)}return N}function S(){let N=C();for(;l("and");){const D=e[r];++r;const R=C();N=new vn(D,N,R)}return N}function C(){let N;for(;l("not");){const D=e[r];++r;const R=C();N=new n_(D,R)}return N??O()}function O(){let N=M();for(;;){let D;if(l("not","in"))D=new Pt("not in",$.Identifier),r+=2;else if(l("in"))D=e[r++];else if(o($.ComparisonBinaryOperator))D=e[r++];else break;const R=M();N=new vn(D,N,R)}return N}function M(){let N=L();for(;o($.AdditiveBinaryOperator);){const D=e[r];++r;const R=L();N=new vn(D,N,R)}return N}function V(){const N=B(Y());return o($.OpenParen)?G(N):N}function G(N){let D=new e_(N,U("call"));return D=B(D),o($.OpenParen)&&(D=G(D)),D}function U(N){n($.OpenParen,"Expected opening parenthesis for arguments list");const D=J(N);return n($.CloseParen,"Expected closing parenthesis for arguments list"),D}function J(N){const D=[],R=new Set;let re=!1,Z=!1;for(;!o($.CloseParen);){const Me=o($.ExponentiationBinaryOperator),Ne=o($.MultiplicativeBinaryOperator)&&e[r].value==="*";if(N==="parameters"&&(Me||Ne))throw new SyntaxError("Argument unpacking is not allowed in parameter declarations");if(Me){if(++r,D.push(new jx(x())),o($.Comma)&&++r,!o($.CloseParen))throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let Oe;if(Ne){if(Z)throw new SyntaxError("Only one `*` argument unpacking is allowed");Z=!0,++r;const Ke=x();Oe=new Ux(Ke)}else{if(Oe=x(),o($.Equals)){if(++r,!(Oe instanceof Ir))throw new SyntaxError(N==="parameters"?"Expected identifier for parameter declaration":"Expected identifier for keyword argument");const Ke=x();Oe=new Li(Oe,Ke)}if(N==="parameters"){if(!(Oe instanceof Ir||Oe instanceof Li))throw new SyntaxError("Expected identifier for parameter declaration");const Ke=Oe instanceof Ir?Oe.value:Oe.key.value;if(R.has(Ke))throw new SyntaxError(`Duplicate parameter name: ${Ke}`);R.add(Ke)}if(Oe instanceof Li)re=!0;else{if(re)throw new SyntaxError(N==="call"?"Positional arguments must come before keyword arguments":"Non-default argument follows default argument");if(Z)throw new SyntaxError("Positional arguments must not follow `*` argument unpacking")}}D.push(Oe),o($.Comma)&&++r}return D}function Q(){const N=[];let D=!1;for(;!o($.CloseSquareBracket);)o($.Colon)?(N.push(void 0),++r,D=!0):(N.push(x()),o($.Colon)&&(++r,D=!0));if(N.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(D){if(N.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Vx(...N)}return N[0]}function B(N){for(;o($.Dot)||o($.OpenSquareBracket);){const D=e[r];++r;let R;const re=D.type===$.OpenSquareBracket;if(re)R=Q(),n($.CloseSquareBracket,"Expected closing square bracket");else if(R=Y(),R.type!=="Identifier"&&R.type!=="IntegerLiteral")throw new SyntaxError("Expected identifier or integer following dot operator");N=new Lx(N,R,re)}return N}function L(){let N=ee();for(;o($.MultiplicativeBinaryOperator);){const D=e[r++],R=ee();N=new vn(D,N,R)}return N}function ee(){let N=H();for(;o($.ExponentiationBinaryOperator);){const D=e[r++],R=H();N=new vn(D,N,R)}return N}function H(){let N=ne();for(;l("is");){++r;const D=l("not");D&&++r;const R=Y();if(!(R instanceof Ir))throw new SyntaxError("Expected identifier for the test");N=new Gx(N,D,R)}return N}function ne(){let N=Se();for(;o($.Pipe);){++r;let D=Y();if(!(D instanceof Ir))throw new SyntaxError("Expected identifier for the filter");o($.OpenParen)&&(D=G(D)),N=new Bx(N,D)}return N}function Se(){const N=e[r];if(N&&(N.type===$.UnaryOperator||N.type===$.AdditiveBinaryOperator)&&(N.value==="-"||N.value==="+")){const D=e[r++],R=Se();return new n_(D,R)}return V()}function Y(){const N=e[r++];switch(N.type){case $.NumericLiteral:{const D=N.value;return D.includes(".")?new Nx(Number(D)):new Ox(Number(D))}case $.StringLiteral:{let D=N.value;for(;o($.StringLiteral);)D+=e[r++].value;return new t_(D)}case $.Identifier:return new Ir(N.value);case $.OpenParen:{const D=v();return n($.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),D}case $.OpenSquareBracket:{const D=[];for(;!o($.CloseSquareBracket);)D.push(x()),o($.Comma)&&++r;return++r,new Dx(D)}case $.OpenCurlyBracket:{const D=new Map;for(;!o($.CloseCurlyBracket);){const R=x();n($.Colon,"Expected colon between key and value in object literal");const re=x();D.set(R,re),o($.Comma)&&++r}return++r,new zx(D)}default:throw new SyntaxError(`Unexpected token: ${N.type}`)}}for(;r<e.length;)t.body.push(a());return t}function Qx(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const n=[];if(r>0)for(let s=e;s<t;s+=r)n.push(s);else for(let s=e;s>t;s+=r)n.push(s);return n}function s_(e,t,r,n=1){const s=Math.sign(n);s>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;s*o<s*r;o+=n)a.push(e[o]);return a}function Xx(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function Yx(e){return Jx(new Date,e)}function Jx(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 Kx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zx(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(Kx(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var a_=class extends Error{},o_=class extends Error{},e1=new Map,Ut=class{constructor(e=void 0){T(this,"type","RuntimeValue");T(this,"value");this.value=e}get builtins(){return e1}__bool__(){return new ie(!!this.value)}toString(){return String(this.value)}},ce=class extends Ut{constructor(){super(...arguments);T(this,"type","IntegerValue")}},ke=class extends Ut{constructor(){super(...arguments);T(this,"type","FloatValue")}toString(){return Object.is(this.value,-0)?"-0.0":this.value%1===0?this.value.toFixed(1):this.value.toString()}},K=class extends Ut{constructor(){super(...arguments);T(this,"type","StringValue");T(this,"_builtins")}get builtins(){return this._builtins??(this._builtins=new Map([["upper",new ze(()=>new K(this.value.toUpperCase()))],["lower",new ze(()=>new K(this.value.toLowerCase()))],["strip",new ze(()=>new K(this.value.trim()))],["title",new ze(()=>new K(Xx(this.value)))],["capitalize",new ze(()=>new K(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ce(this.value.length)],["rstrip",new ze(()=>new K(this.value.trimEnd()))],["lstrip",new ze(()=>new K(this.value.trimStart()))],["startswith",new ze(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");const r=t[0];if(r instanceof K)return new ie(this.value.startsWith(r.value));if(r instanceof me){for(const n of r.value){if(!(n instanceof K))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(n.value))return new ie(!0)}return new ie(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new ze(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");const r=t[0];if(r instanceof K)return new ie(this.value.endsWith(r.value));if(r instanceof me){for(const n of r.value){if(!(n instanceof K))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(n.value))return new ie(!0)}return new ie(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new ze(t=>{const r=t[0]??new Ge;if(!(r instanceof K||r instanceof Ge))throw new Error("sep argument must be a string or null");const n=t[1]??new ce(-1);if(!(n instanceof ce))throw new Error("maxsplit argument must be a number");let s=[];if(r instanceof Ge){const a=this.value.trimStart();for(const{0:o,index:i}of a.matchAll(/\S+/g)){if(n.value!==-1&&s.length>=n.value&&i!==void 0){s.push(o+a.slice(i+o.length));break}s.push(o)}}else{if(r.value==="")throw new Error("empty separator");s=this.value.split(r.value),n.value!==-1&&s.length>n.value&&s.push(s.splice(n.value).join(r.value))}return new me(s.map(a=>new K(a)))})],["replace",new ze(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");const r=t[0],n=t[1];if(!(r instanceof K&&n instanceof K))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ge:s=t[2]:s=new Ge,!(s instanceof ce||s instanceof Ge))throw new Error("replace() count argument must be a number or null");return new K(Zx(this.value,r.value,n.value,s.value))})]]))}},ie=class extends Ut{constructor(){super(...arguments);T(this,"type","BooleanValue")}},t1=/[\x7f-\uffff]/g;function i_(e){return e.replace(t1,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Lr(e,t={},r=0,n=!0){const{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,c;switch(o?[l,c]=o:s?(l=",",c=": "):(l=", ",c=": "),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=i_(d)),d}case"ArrayValue":case"NamespaceValue":case"ObjectValue":{const d=s?" ".repeat(s):"",h=`
|
|
15
|
+
`+d.repeat(r),_=h+d;if(e.type==="ArrayValue"){const p=e.value.map(w=>Lr(w,t,r+1,n));return s?`[${_}${p.join(`${l}${_}`)}${h}]`:`[${p.join(l)}]`}else{let p=Array.from(e.value.entries());i&&(p=p.sort(([v],[y])=>v.localeCompare(y)));const w=p.map(([v,y])=>{let x=JSON.stringify(v);a&&(x=i_(x));const k=`${x}${c}${Lr(y,t,r+1,n)}`;return s?`${_}${k}`:k});return s?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var ut=class extends Ut{constructor(){super(...arguments);T(this,"type","ObjectValue");T(this,"_builtins")}__bool__(){return new ie(this.value.size>0)}get builtins(){return this._builtins??(this._builtins=new Map([["get",new ze(([t,r])=>{if(!(t instanceof K))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new Ge})],["items",new ze(()=>this.items())],["keys",new ze(()=>this.keys())],["values",new ze(()=>this.values())],["dictsort",new ze(t=>{let r=new Map;const n=t.filter(l=>l instanceof Zr?(r=l.value,!1):!0),s=n.at(0)??r.get("case_sensitive")??new ie(!1);if(!(s instanceof ie))throw new Error("case_sensitive must be a boolean");const a=n.at(1)??r.get("by")??new K("key");if(!(a instanceof K))throw new Error("by must be a string");if(!["key","value"].includes(a.value))throw new Error("by must be either 'key' or 'value'");const o=n.at(2)??r.get("reverse")??new ie(!1);if(!(o instanceof ie))throw new Error("reverse must be a boolean");const i=Array.from(this.value.entries()).map(([l,c])=>new me([new K(l),c])).sort((l,c)=>{const d=a.value==="key"?0:1,h=l.value[d],_=c.value[d],p=Ni(h,_,s.value);return o.value?-p:p});return new me(i)})]]))}items(){return new me(Array.from(this.value.entries()).map(([t,r])=>new me([new K(t),r])))}keys(){return new me(Array.from(this.value.keys()).map(t=>new K(t)))}values(){return new me(Array.from(this.value.values()))}toString(){return Lr(this,{},0,!1)}},Zr=class extends ut{constructor(){super(...arguments);T(this,"type","KeywordArgumentsValue")}},Oi=class extends Ut{constructor(){super(...arguments);T(this,"type","NamespaceValue")}toString(){return Lr(this,{},0,!1)}},me=class extends Ut{constructor(){super(...arguments);T(this,"type","ArrayValue");T(this,"_builtins")}get builtins(){return this._builtins??(this._builtins=new Map([["length",new ce(this.value.length)]]))}__bool__(){return new ie(this.value.length>0)}toString(){return Lr(this,{},0,!1)}},l_=class extends me{constructor(){super(...arguments);T(this,"type","TupleValue")}},ze=class extends Ut{constructor(){super(...arguments);T(this,"type","FunctionValue")}},Ge=class extends Ut{constructor(){super(...arguments);T(this,"type","NullValue")}},Be=class extends Ut{constructor(){super(...arguments);T(this,"type","UndefinedValue")}};function r1(e){let t;if(e instanceof me?t=e.value:e instanceof K&&(t=Array.from(e.value,s=>new K(s))),!t||t.length!==2)throw new Error("namespace expected an object or an iterable of [key, value] pairs");const[r,n]=t;if(!(r instanceof K))throw new Error("namespace keys must be strings");return[r,n]}var c_=class{constructor(e){T(this,"variables",new Map([["namespace",new ze(e=>{const t=e.slice();let r;if(t.at(-1)instanceof Zr&&(r=t.pop()),t.length>1)throw new Error(`namespace expected at most 1 argument, got ${t.length}`);const n=new Map;if(t.length===1){const s=t[0];if(s instanceof ut)for(const[a,o]of s.value)n.set(a,o);else if(s instanceof me)for(const a of s.value){const[o,i]=r1(a);n.set(o.value,i)}else throw new Error(`'${s.type}' object is not iterable`)}if(r)for(const[s,a]of r.value)n.set(s,a);return new Oi(n)})]]));T(this,"tests",c_.TESTS);this.parent=e}set(e,t){return this.declareVariable(e,va(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 Be}catch{return new Be}}},Or=c_;yx(Or,"TESTS",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof ze],["odd",e=>{if(!(e instanceof ce))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof ce))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 ce||e instanceof ke],["integer",e=>e instanceof ce],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof ut],["sequence",e=>e instanceof me||e instanceof ut||e instanceof K],["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]]));function n1(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",Qx),e.set("strftime_now",Yx),e.set("True",!0),e.set("False",!1),e.set("None",null)}function ma(e){return e instanceof ut||e instanceof Oi}function ga(e){return e instanceof ce||e instanceof ke||e instanceof ie}function wa(e){return e instanceof ie?Number(e.value):e.value}function u_(e,t){const r=t.split(".");let n=e;for(const s of r)if(ma(n))n=n.value.get(s)??new Be;else if(n instanceof me){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&a<n.value.length)n=n.value[a];else return new Be}else return new Be;return n}function Ni(e,t,r=!1){if(e instanceof Ge&&t instanceof Ge)return 0;if(e instanceof Ge||t instanceof Ge)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Be&&t instanceof Be)return 0;if(e instanceof Be||t instanceof Be)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(ga(e)&&ga(t)){const n=wa(e),s=wa(t);return n<s?-1:n>s?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let n=e.value,s=t.value;return r||(n=n.toLowerCase(),s=s.toLowerCase()),n<s?-1:n>s?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}function Di(e){if(e.type==="Identifier")return{name:e.value};const t=e;return{name:t.key.value,defaultValue:t.value}}function d_(e){return e==="kwargs"||e==="varargs"}function h_(e,t){const r=new Set,n=new Set,s=d=>{d_(d)&&r.add(d)},a=d=>{if(d.type==="Identifier")s(d.value);else if(d.type==="TupleLiteral")for(const h of d.value)a(h)},o=d=>{s(Di(d).name)},i=d=>{for(const h of d){const _=Di(h);_.defaultValue&&c(_.defaultValue)}},l=d=>{d.type==="CallExpression"&&c(d.args)},c=d=>{if(Array.isArray(d)){for(const h of d)c(h);return}if(d instanceof Map){for(const[h,_]of d)c(h),c(_);return}if(d instanceof Ft)switch(d.type){case"For":{const h=d;if(a(h.loopvar),h.iterable.type==="SelectExpression"){const _=h.iterable;c(_.lhs),c(h.body),c(h.defaultBlock),c(_.test);return}c(h.iterable),c(h.body),c(h.defaultBlock);return}case"Set":{const h=d;a(h.assignee),c(h.value),c(h.body);return}case"Macro":{const h=d;for(const _ of h.args)o(_);i(h.args),c(h.body);return}case"CallStatement":{const h=d;c(h.call);for(const _ of h.callerArgs??[])o(_);i(h.callerArgs??[]),c(h.body);return}case"FilterStatement":{const h=d;c(h.body),l(h.filter);return}case"Identifier":{const h=d.value;d_(h)&&!r.has(h)&&n.add(h);return}case"MemberExpression":{const h=d;c(h.object),h.computed&&c(h.property);return}case"FilterExpression":{const h=d;c(h.operand),l(h.filter);return}case"TestExpression":c(d.operand);return;case"SelectExpression":{const h=d;c(h.test),c(h.lhs);return}case"KeywordArgumentExpression":c(d.value);return;default:for(const h of Object.values(d))c(h)}};for(const d of e)o(d);return c(t),n}var s1=class{constructor(e){T(this,"global");this.global=e??new Or}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 ie(r.value==n.value);case"!=":return new ie(r.value!=n.value)}if(r instanceof Be||n instanceof Be){if(n instanceof Be&&["in","not in"].includes(e.operator.value))return new ie(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Ge||n instanceof Ge)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new K(r.value.toString()+n.value.toString());if(e.operator.value==="**"&&ga(r)&&ga(n)){const s=wa(r),a=wa(n);if(s===0&&a<0)throw new Error("0.0 cannot be raised to a negative power");const o=s**a;if(!Number.isFinite(o))throw new Error("Exponentiation result is not a finite real number");return r instanceof ke||n instanceof ke||a<0?new ke(o):new ce(o)}else if((r instanceof ce||r instanceof ke)&&(n instanceof ce||n instanceof ke)){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 ke||n instanceof ke?new ke(o):new ce(o)}case"/":return new ke(s/a);case"//":{const o=Math.floor(s/a);return r instanceof ke||n instanceof ke?new ke(o):new ce(o)}case"%":{const o=s%a;return r instanceof ke||n instanceof ke?new ke(o):new ce(o)}case"<":return new ie(s<a);case">":return new ie(s>a);case">=":return new ie(s>=a);case"<=":return new ie(s<=a)}}else if(r instanceof me&&n instanceof me)switch(e.operator.value){case"+":return new me(r.value.concat(n.value))}else if(n instanceof me){const s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ie(s);case"not in":return new ie(!s)}}}if(r instanceof K||n instanceof K)switch(e.operator.value){case"+":return new K(r.value.toString()+n.value.toString())}if(r instanceof K&&n instanceof K)switch(e.operator.value){case"in":return new ie(n.value.includes(r.value));case"not in":return new ie(!n.value.includes(r.value))}if(r instanceof K&&n instanceof ut)switch(e.operator.value){case"in":return new ie(n.value.has(r.value));case"not in":return new ie(!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,s=(a,o)=>{if(n.has(a))throw new Error(`Got multiple values for keyword argument '${a}'`);n.set(a,o)};for(const a of e)if(a.type==="SpreadExpression"){const o=a,i=this.evaluate(o.argument,t);if(!(i instanceof me))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(const l of i.value)r.push(l)}else a.type!=="KeywordArgumentExpression"&&a.type!=="KeywordSpreadExpression"&&r.push(this.evaluate(a,t));for(const a of e)if(a.type==="KeywordArgumentExpression"){const o=a;s(o.key.value,this.evaluate(o.value,t))}else if(a.type==="KeywordSpreadExpression"){const o=a,i=this.evaluate(o.argument,t);if(!(i instanceof ut))throw new Error(`Argument after ** must be a mapping, not ${i.type}`);for(const[l,c]of i.value)s(l,c)}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 K(Lr(e,{}));if(e instanceof me)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 ce(e.value.length);case"reverse":return new me(e.value.slice().reverse());case"sort":return new me(e.value.slice().sort((s,a)=>Ni(s,a,!1)));case"join":return new K(e.value.map(s=>s.value).join(""));case"string":return new K(Lr(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 me(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof K)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const s=e.builtins.get(n.value);if(s instanceof ze)return s.value([],r);if(s instanceof ce)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new K(e.value.trim());case"indent":return new K(e.value.split(`
|
|
16
|
+
`).map((s,a)=>a===0||s.length===0?s:" "+s).join(`
|
|
17
|
+
`));case"join":case"string":return e;case"int":{const s=parseInt(e.value,10);return new ce(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new ke(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof ce||e instanceof ke)switch(n.value){case"abs":return e instanceof ce?new ce(Math.abs(e.value)):new ke(Math.abs(e.value));case"int":return new ce(Math.floor(e.value));case"float":return new ke(e.value);case"string":return new K(e.toString());default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof ut)switch(n.value){case"items":return new me(Array.from(e.value.entries()).map(([s,a])=>new me([new K(s),a])));case"length":return new ce(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof ze?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof ie)switch(n.value){case"bool":return new ie(e.value);case"int":return new ce(e.value?1:0);case"float":return new ke(e.value?1:0);case"string":return new K(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 Ge;if(!(o instanceof ce||o instanceof Ge))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new ie(!1);if(!(i instanceof ie))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new ie(!1);if(!(l instanceof ie))throw new Error("If set, sort_keys must be a boolean");const c=a.get("separators")??new Ge;let d=null;if(c instanceof me||c instanceof l_){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");const[h,_]=c.value;if(!(h instanceof K)||!(_ instanceof K))throw new Error("separators must be a tuple of two strings");d=[h.value,_.value]}else if(!(c instanceof Ge))throw new Error("If set, separators must be a tuple of two strings");return new K(Lr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(s==="join"){let a;if(e instanceof K)a=Array.from(e.value);else if(e instanceof me)a=e.value.map(c=>c.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 K("");if(!(l instanceof K))throw new Error("separator must be a string");return new K(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 ce(0):new ke(0));if(e instanceof K){const l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new ce(l):new ke(l)}else{if(e instanceof ce||e instanceof ke)return e;if(e instanceof ie)return s==="int"?new ce(e.value?1:0):new ke(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 K(""),l=a[1]??o.get("boolean")??new ie(!1);if(!(l instanceof ie))throw new Error("`default` filter flag must be a boolean");return e instanceof Be||l.value&&!e.__bool__().value?i:e}if(e instanceof me){switch(s){case"sort":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new ie(!1);if(!(i instanceof ie))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new ie(!1);if(!(l instanceof ie))throw new Error("case_sensitive must be a boolean");const c=a.at(2)??o.get("attribute")??new Ge;if(!(c instanceof K||c instanceof ce||c instanceof Ge))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(c instanceof Ge)return h;const _=c instanceof ce?String(c.value):c.value;return u_(h,_)};return new me(e.value.slice().sort((h,_)=>{const p=d(h),w=d(_),v=Ni(p,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(h=>!ma(h)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[o,i,l]=n.args.map(h=>this.evaluate(h,r));let c;if(i){const h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);c=h}else c=(...h)=>h[0].__bool__().value;const d=e.value.filter(h=>{const _=h.value.get(o.value),p=_?c(_,l):!1;return a?p:!p});return new me(d)}case"map":{const[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof K))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(c=>{if(!ma(c))throw new Error("items in map must be an object");const d=u_(c,o.value);return d instanceof Be?i??new Be:d});return new me(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 K){switch(s){case"indent":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new ce(4);if(!(i instanceof ce))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new ie(!1),c=a.at(2)??o.get("blank")??new ie(!1),d=e.value.split(`
|
|
18
|
+
`),h=" ".repeat(i.value),_=d.map((p,w)=>!l.value&&w===0||!c.value&&p.length===0?p:h+p);return new K(_.join(`
|
|
19
|
+
`))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof ze))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new Zr(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof ut){const a=e.builtins.get(s);if(a&&a instanceof ze){const[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new Zr(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 ie(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Be}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ie(!r.value);case"+":case"-":{const n=e.operator.value==="-"?-1:1;if(r instanceof ce||r instanceof ke||r instanceof ie){const s=r instanceof ie?r.value?1:0:r.value,a=n*s;return r instanceof ke?new ke(a):new ce(a)}throw new SyntaxError(`Unknown operator "${e.operator.value}" for ${r.type}`)}default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const n of e){const s=this.evaluate(n,t);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(r+=s.toString())}return new K(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 Zr(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 me||e instanceof K))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 ce||n instanceof Be))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ce||s instanceof Be))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof ce||a instanceof Be))throw new Error("Slice step must be numeric or undefined");return e instanceof me?new me(s_(e.value,n.value,s.value,a.value)):new K(s_(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 e.property.type==="IntegerLiteral"?n=new ce(e.property.value):n=new K(e.property.value);let s;if(ma(r)){if(!(n instanceof K))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??(r instanceof ut?r.builtins.get(n.value):void 0)}else if(r instanceof me||r instanceof K)if(n instanceof ce)s=r.value.at(n.value),r instanceof K&&(s=new K(r.value.at(n.value)));else if(n instanceof K)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 K))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Ut?s:new Be}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 me))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;a<n.value.length;++a){const o=n.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,s[a])}}else if(e.assignee.type==="MemberExpression"){const n=e.assignee,s=this.evaluate(n.object,t);if(!(s instanceof Oi))throw new Error("cannot assign attribute on non-namespace object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Ge}evaluateIf(e,t){const r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const r=new Or(t);let n,s;if(e.iterable.type==="SelectExpression"){const c=e.iterable;s=this.evaluate(c.lhs,r),n=c.test}else s=this.evaluate(e.iterable,r);if(!(s instanceof me||s instanceof ut))throw new Error(`Expected iterable or object type in for loop: got ${s.type}`);s instanceof ut&&(s=s.keys());const a=[],o=[];for(let c=0;c<s.value.length;++c){const d=new Or(r),h=s.value[c];let _;if(e.loopvar.type==="Identifier")_=p=>p.setVariable(e.loopvar.value,h);else if(e.loopvar.type==="TupleLiteral"){const p=e.loopvar;if(h.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${h.type}`);const w=h;if(p.value.length!==w.value.length)throw new Error(`Too ${p.value.length>w.value.length?"few":"many"} items to unpack`);_=v=>{for(let y=0;y<p.value.length;++y){if(p.value[y].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${p.value[y].type}`);v.setVariable(p.value[y].value,w.value[y])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);n&&(_(d),!this.evaluate(n,d).__bool__().value)||(a.push(h),o.push(_))}let i="",l=!0;for(let c=0;c<a.length;++c){const d=new Map([["index",new ce(c+1)],["index0",new ce(c)],["revindex",new ce(a.length-c)],["revindex0",new ce(a.length-c-1)],["first",new ie(c===0)],["last",new ie(c===a.length-1)],["length",new ce(a.length)],["previtem",c>0?a[c-1]:new Be],["nextitem",c<a.length-1?a[c+1]:new Be]]);r.setVariable("loop",new ut(d)),o[c](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof o_)continue;if(h instanceof a_)break;throw h}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new K(i)}bindMacroArguments(e,t,r,n,s){const a=n.slice();let o=new Map;a.at(-1)instanceof Zr&&(o=new Map(a.pop().value));const i=[];for(let l=0;l<t.length;++l){const{name:c,defaultValue:d}=Di(t[l]);let h=a[l];h===void 0&&o.has(c)&&(h=o.get(c),o.delete(c)),h===void 0&&d!==void 0&&i.push([c,d]),s.setVariable(c,h??new Be)}if(r.has("kwargs"))s.setVariable("kwargs",new ut(o));else if(o.size>0)throw new Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(r.has("varargs"))s.setVariable("varargs",new me(a.slice(t.length)));else if(a.length>t.length)throw new Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(const[l,c]of i)s.setVariable(l,this.evaluate(c,s))}evaluateMacro(e,t){const r=h_(e.args,e.body);return t.setVariable(e.name.value,new ze((n,s)=>{const a=new Or(s);return this.bindMacroArguments(`'${e.name.value}'`,e.args,r,n,a),this.evaluateBlock(e.body,a)})),new Ge}evaluateCallStatement(e,t){const r=e.callerArgs??[],n=h_(r,e.body),s=new ze(c=>{const d=new Or(t);return this.bindMacroArguments("None",r,n,c,d),this.evaluateBlock(e.body,d)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new Zr(o));const i=this.evaluate(e.call.callee,t);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);const l=new Or(t);return l.setVariable("caller",s),i.value(a,l)}evaluateFilterStatement(e,t){const r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new Be;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new a_;case"Continue":throw new o_;case"IntegerLiteral":return new ce(e.value);case"FloatLiteral":return new ke(e.value);case"StringLiteral":return new K(e.value);case"ArrayLiteral":return new me(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new l_(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 K))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new ut(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 Ge;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function va(e){switch(typeof e){case"number":return Number.isInteger(e)?new ce(e):new ke(e);case"string":return new K(e);case"boolean":return new ie(e);case"undefined":return new Be;case"object":return e===null?new Ge:Array.isArray(e)?new me(e.map(va)):new ut(new Map(Object.entries(e).map(([t,r])=>[t,va(r)])));case"function":return new ze((t,r)=>{const n=e(...t.map(s=>s.value))??null;return va(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var et=`
|
|
20
|
+
`,a1="{%- ",o1=" -%}",Ue=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function f_(e){switch(e.operator.type){case"ExponentiationBinaryOperator":return Ue.EXPONENTIATION;case"MultiplicativeBinaryOperator":return Ue.MULTIPLICATIVE;case"AdditiveBinaryOperator":return Ue.ADDITIVE;case"ComparisonBinaryOperator":return Ue.COMPARISON;case"Identifier":return e.operator.value==="and"?Ue.LOGICAL_AND:e.operator.value==="in"||e.operator.value==="not in"?Ue.COMPARISON:Ue.LOGICAL_OR}return Ue.LOGICAL_OR}function __(e){switch(e.type){case"SelectExpression":case"Ternary":return Ue.CONDITIONAL;case"BinaryExpression":return f_(e);case"UnaryExpression":return e.operator.value==="not"?Ue.LOGICAL_NOT:Ue.UNARY_SIGN;case"TestExpression":return Ue.TEST;case"FilterExpression":return Ue.FILTER;default:return Ue.ATOM}}function jt(e,t){const r=Ve(e);return __(e)<t?`(${r})`:r}function i1(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Wt(e.body,0,r).replace(/\n$/,"")}function st(...e){return a1+e.join(" ")+o1}function Wt(e,t,r){return e.map(n=>l1(n,t,r)).join(et)}function ya(e){return e.map(t=>Ve(t)).join(", ")}function l1(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return Wt(e.body,t,r);case"If":return c1(e,t,r);case"For":return u1(e,t,r);case"Set":return d1(e,t,r);case"Macro":return h1(e,t,r);case"Break":return n+st("break");case"Continue":return n+st("continue");case"CallStatement":return f1(e,t,r);case"FilterStatement":return _1(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+Ve(e)+" -}}"}}function c1(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+st("if",Ve(s[0].test))+et+Wt(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=et+n+st("elif",Ve(s[i].test))+et+Wt(s[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=et+n+st("else")+et+Wt(a.alternate,t+1,r)),o+=et+n+st("endif"),o}function u1(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;s=`${Ve(o.lhs)} if ${Ve(o.test)}`}else s=Ve(e.iterable);let a=n+st("for",Ve(e.loopvar),"in",s)+et+Wt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=et+n+st("else")+et+Wt(e.defaultBlock,t+1,r)),a+=et+n+st("endfor"),a}function d1(e,t,r){const n=r.repeat(t),s=Ve(e.assignee),a=e.value?Ve(e.value):"",o=n+st("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+et+Wt(e.body,t+1,r)+et+n+st("endset")}function h1(e,t,r){const n=r.repeat(t),s=ya(e.args);return n+st("macro",`${e.name.value}(${s})`)+et+Wt(e.body,t+1,r)+et+n+st("endmacro")}function f1(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${ya(e.callerArgs)})`:"",a=Ve(e.call);let o=n+st(`call${s}`,a)+et;return o+=Wt(e.body,t+1,r)+et,o+=n+st("endcall"),o}function _1(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:Ve(e.filter);let a=n+st("filter",s)+et;return a+=Wt(e.body,t+1,r)+et,a+=n+st("endfilter"),a}function Ve(e){switch(e.type){case"SpreadExpression":return`*${Ve(e.argument)}`;case"KeywordSpreadExpression":return`**${Ve(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":{const t=e.value;return Object.is(t,-0)?"-0.0":t%1===0?t.toFixed(1):t.toString()}case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const t=e,r=f_(t),n=jt(t.left,r),s=jt(t.right,r+1);return`${n} ${t.operator.value} ${s}`}case"UnaryExpression":{const t=e,r=t.argument.type==="UnaryExpression"?__(t):Ue.ATOM;return t.operator.value+(t.operator.value==="not"?" ":"")+jt(t.argument,r)}case"CallExpression":{const t=e,r=ya(t.args);return`${Ve(t.callee)}(${r})`}case"MemberExpression":{const t=e,r=jt(t.object,Ue.ATOM);let n=Ve(t.property);return!t.computed&&t.property.type!=="Identifier"&&t.property.type!=="IntegerLiteral"&&(n=`(${n})`),t.computed?`${r}[${n}]`:`${r}.${n}`}case"FilterExpression":{const t=e,r=jt(t.operand,Ue.FILTER);return t.filter.type==="CallExpression"?`${r} | ${Ve(t.filter)}`:`${r} | ${t.filter.value}`}case"SelectExpression":{const t=e;return`${jt(t.lhs,Ue.LOGICAL_OR)} if ${jt(t.test,Ue.LOGICAL_OR)}`}case"TestExpression":{const t=e;return`${jt(t.operand,Ue.TEST)} is${t.negate?" not":""} ${t.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const t=ya(e.value),r=e.type==="ArrayLiteral"?"[]":"()";return`${r[0]}${t}${r[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([r,n])=>`${Ve(r)}: ${Ve(n)}`).join(", ")}}`;case"SliceExpression":{const t=e,r=t.start?Ve(t.start):"",n=t.stop?Ve(t.stop):"",s=t.step?`:${Ve(t.step)}`:"";return`${r}:${n}${s}`}case"KeywordArgumentExpression":{const t=e;return`${t.key.value}=${Ve(t.value)}`}case"Ternary":{const t=e;return`${jt(t.trueExpr,Ue.LOGICAL_OR)} if ${jt(t.condition,Ue.LOGICAL_OR)} else ${jt(t.falseExpr,Ue.CONDITIONAL)}`}default:throw new Error(`Unknown expression type: ${e.type}`)}}var p1=class{constructor(e){T(this,"parsed");const t=kx(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Hx(t)}render(e){const t=new Or;if(n1(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new s1(t).run(this.parsed).value}format(e){return i1(this.parsed,(e==null?void 0:e.indent)||" ")}},m1={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"},ba=class Gy{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=At.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=At.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=At.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",m1[t]??"application/octet-stream")}clone(){let t=new Gy(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 At.promises.readFile(this.filePath)).buffer}async blob(){const t=await At.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await At.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Ma=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(pe.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[p_(this._random_fn,t)]}};function p_(e,t){let r=0;for(let s=0;s<t.length;++s)r+=t[s];let n=e()*r;for(let s=0;s<t.length;++s)if(n-=t[s],n<0)return s;return t.length-1}var rr=new Ma,zi=Object.freeze({Random:Ma,seed:rr.seed.bind(rr),random:rr.random.bind(rr),gauss:rr.gauss.bind(rr),shuffle:rr.shuffle.bind(rr),choices:rr.choices.bind(rr)}),g1=e=>p_(zi.random,e),w1=new Ma,m_=class{constructor(e){this.path=e}async match(e){let t=Zt.join(this.path,e),r=new ba(t);if(r.exists)return r}async put(e,t,r=void 0){const n=Zt.join(this.path,e),s=pe.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=w1._int32().toString(36),o=n+`.tmp.${s}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let c=0;await At.promises.mkdir(Zt.dirname(n),{recursive:!0});const d=At.createWriteStream(o),h=t.body.getReader();for(;;){const{done:_,value:p}=await h.read();if(_)break;await new Promise((v,y)=>{d.write(p,x=>{if(x){y(x);return}v()})}),c+=p.length;const w=l?c/l*100:0;r==null||r({progress:w,loaded:c,total:l})}await new Promise((_,p)=>{d.close(w=>w?p(w):_())}),await At.promises.rename(o,n)}catch(i){try{await At.promises.unlink(o)}catch{}throw i}}async delete(e){let t=Zt.join(this.path,e);try{return await At.promises.unlink(t),!0}catch{return!1}}},v1={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"},g_=100,y1=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function xa(...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 en(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 b1(e){return!(!y1.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function Bi(e,t={},...r){return JSON.stringify([e,t.revision??"main",t.cache_dir??null,t.local_files_only??!1,...r])}var Ri=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name="ModelFileNotFoundError",this.status=t}},M1=new Set([401,403,404]);function w_(e,t,r){if(!r)return null;const s=`${v1[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;throw M1.has(e)?new Ri(s,{status:e}):Error(s)}async function x1(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&he.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:c,value:d}=await i.read();if(c)return;const h=o+d.length;if(h>s){s=h;const p=new Uint8Array(s);p.set(a),a=p}a.set(d,o),o=h;const _=o/s*100;return t({progress:_,loaded:o,total:s}),l()}return await l(),a}function v_(e){return en(e,["blob:"])}function $i(e,{allowUnresolved:t=!1}={}){let r;if(typeof location<"u"&&location.href)r=location.href;else if(typeof{url:self.location.href}<"u"&&self.location.href)r=self.location.href;else return e;try{return new URL(e,r).href}catch(n){if(!t)throw n;return e}}var y_="SHA-256",k1="experimental_transformers-hash-cache",b_=e=>({algorithm:y_,value:e}),M_=(Ru=class{constructor(){No(this,As,null);T(this,"_getHashCache",()=>(pt(this,As)??Do(this,As,caches.open(k1)),pt(this,As)));T(this,"match",async e=>{const t=await this._getFileHash(e);if(t)try{const n=await(await navigator.crossOriginStorage.requestFileHandle(b_(t))).getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}});T(this,"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)});T(this,"_storeBlobInCOS",async(e,t)=>{const n=await(await navigator.crossOriginStorage.requestFileHandle(b_(t),{create:!0,origins:"*"})).createWritable();await n.write(e),await n.close()});T(this,"_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{}});T(this,"delete",async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}});T(this,"_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}});T(this,"_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}});T(this,"_getBlobHash",async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(y_,t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")})}},As=new WeakMap,T(Ru,"isAvailable",()=>typeof navigator<"u"&&"crossOriginStorage"in navigator),Ru);async function Gi(e=null){let t=null;if(ve.useCustomCache){if(!ve.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ve.customCache.match||!ve.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=ve.customCache}if(!t&&ve.experimental_useCrossOriginStorage&&M_.isAvailable()&&(t=new M_),!t&&ve.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ve.cacheKey)}catch(r){he.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ve.useFSCache){if(!pe.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new m_(e??ve.cacheDir)}return t}async function T1(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}var E1=(ww=class{constructor(e){No(this,Cs);No(this,_t);Do(this,Cs,e),Do(this,_t,new Map)}get(e){if(!pt(this,_t).has(e))return;const t=pt(this,_t).get(e);return pt(this,_t).delete(e),pt(this,_t).set(e,t),t}put(e,t){pt(this,_t).has(e)&&pt(this,_t).delete(e),pt(this,_t).set(e,t),pt(this,_t).size>pt(this,Cs)&&pt(this,_t).delete(pt(this,_t).keys().next().value)}delete(e){return pt(this,_t).delete(e)}clear(){pt(this,_t).clear()}},Cs=new WeakMap,_t=new WeakMap,ww),A1=100,Vi=new E1(A1);function x_(e,t){const r=Vi.get(e);if(r!==void 0)return r;const n=t().then(s=>s,s=>(Vi.delete(e),Promise.reject(s)));return Vi.put(e,n),n}async function C1(e){if(!en(e,["http:","https:"]))return null;const t=k_(e);return t.set("Range","bytes=0-0"),ve.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function cs(e,t,r={}){const n=Bi(e,r,t);return x_(n,()=>S1(e,t,r))}async function S1(e,t,r){var c;const n=await Gi(r==null?void 0:r.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=T_(e,t,r,n),l=await E_(n,s,o);if(l!==void 0&&typeof l!="string"){const d=l.headers.get("content-length"),h=l.headers.get("content-type");return{exists:!0,size:d?parseInt(d,10):void 0,contentType:h||void 0,fromCache:!0}}if(ve.allowLocalModels&&!en(s,["http:","https:"]))try{const h=await us(s);if(typeof h!="string"&&h.status!==404){const _=h.headers.get("content-length"),p=h.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:p||void 0,fromCache:!1}}}catch{}if(ve.allowRemoteModels&&!r.local_files_only&&i){const d=await C1(a);if(d&&d.status>=200&&d.status<300){let h;const _=d.headers.get("content-type");if(d.status===206){const p=d.headers.get("content-range");if(p){const w=p.match(/bytes \d+-\d+\/(\d+)/);w&&(h=parseInt(w[1],10))}}else if(d.status===200)try{await((c=d.body)==null?void 0:c.cancel())}catch{}if(h===void 0){const p=d.headers.get("content-length");h=p?parseInt(p,10):void 0}return{exists:!0,size:h,contentType:_||void 0,fromCache:!1}}d&&d.status!==404&&d.status!==416&&w_(d.status,a,!0)}return{exists:!1,fromCache:!1}}async function us(e){return ve.useFS&&!en(e,["http:","https:","blob:"])?new ba(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ve.fetch(e,{headers:k_(e)})}function k_(e){var n;const t=typeof process<"u"&&((n=process==null?void 0:process.release)==null?void 0:n.name)==="node",r=new Headers;if(t){const s=!!(fr!=null&&fr.TESTING_REMOTELY),a=ve.version;if(r.set("User-Agent",`transformers.js/${a}; is_ci/${s};`),en(e,["http:","https:"],["huggingface.co","hf.co"])){const i=(fr==null?void 0:fr.HF_TOKEN)??(fr==null?void 0:fr.HF_ACCESS_TOKEN);i&&r.set("Authorization",`Bearer ${i}`)}}return r}function T_(e,t,r={},n=null){const s=r.revision??"main",a=xa(e,t),o=b1(e),i=o?xa(ve.localModelPath,a):a,l=xa(ve.remoteHost,ve.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),c=n instanceof m_?s==="main"?a:xa(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function E_(e,t,r){if(e)return await T1(e,t,r)}async function P1(e,t,r,n,s,a,o={}){if(await r.match(n)===void 0&&!(typeof Cache<"u"&&r instanceof Cache&&!en($i(n,{allowUnresolved:!0}),["http:","https:"])))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=>{he.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>Pr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function F1(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=T_(e,t,n,a);let h,_=!1,p;p=await E_(a,i,c);const w=p!==void 0;if(w)h=c;else{if(ve.allowLocalModels)if(en(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(!ve.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{p=await us(i),h=i}catch(k){he.warn(`Unable to load from local path "${i}": "${k}"`)}if(p===void 0||typeof p!="string"&&p.status===404){if(n.local_files_only||!ve.allowRemoteModels){if(r)throw new Ri(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw new Ri(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await us(l),p.status!==200)return w_(p.status,l,r);h=c}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200}Pr(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(pe.IS_NODE_ENV&&s)){let x;if(typeof p!="string")if(!n.progress_callback)x=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))x=new Uint8Array(await p.arrayBuffer()),Pr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:x.length,total:x.length});else{let k;const A=p.headers.get("content-length");if(A)k=parseInt(A,10);else try{const S=await cs(e,t,n);S.size&&(k=S.size)}catch{}x=await x1(p,S=>{Pr(n.progress_callback,{status:"progress",name:e,file:t,...S})},k)}v=x}if(_&&h&&typeof p!="string"&&await P1(e,t,a,h,p,v,n),pe.IS_NODE_ENV&&s&&n.progress_callback&&typeof p!="string"){const x=parseInt(p.headers.get("content-length"),10)||0;Pr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:x,total:x})}if(Pr(n.progress_callback,{status:"done",name:e,file:t}),v){if(!pe.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(p instanceof ba)return p.filePath;const y=await(a==null?void 0:a.match(h));if(y instanceof ba)return y.filePath;if(y instanceof Response)return new Uint8Array(await y.arrayBuffer());if(typeof y=="string")return y;throw new Error("Unable to get model file path or buffer.")}var Ui=new Map;async function ka(e,t,r=!0,n={},s=!1){if(!ve.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(!ve.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}const a=Bi(e,n,t,r,s),{progress_callback:o}=n,i=o instanceof la?o.loads:Ui;let l=i.get(a);return l||(Pr(o,{status:"initiate",name:e,file:t}),l=Gi(n.cache_dir).then(c=>F1(e,t,r,n,s,c)),i===Ui&&(l=l.finally(()=>Ui.delete(a))),i.set(a,l)),await l}async function ji(e,t,r=!0,n={}){const s=await ka(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function nr(e,t,r=!0,n={}){const s=await ji(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,c=s/r,d=new e.constructor(s*a*t),h=r*n,_=s*a;for(let p=0;p<s;++p)for(let w=0;w<a;++w){const v=p*a+w,y=(w+.5)/l-.5,x=(p+.5)/c-.5;let k=Math.floor(y),A=Math.floor(x);const S=Math.min(k+1,n-1),C=Math.min(A+1,r-1);k=Math.max(k,0),A=Math.max(A,0);const O=y-k,M=x-A,V=(1-O)*(1-M),G=O*(1-M),U=(1-O)*M,J=O*M,Q=A*n,B=C*n,L=Q+k,ee=Q+S,H=B+k,ne=B+S;for(let Se=0;Se<t;++Se){const Y=Se*h;d[Se*_+v]=V*e[Y+L]+G*e[Y+ee]+U*e[Y+H]+J*e[Y+ne]}}return d}function L1(e,t,r){const n=new Array(r.length),s=new Array(r.length);for(let i=r.length-1,l=1;i>=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<e.length;++i){let l=0;for(let c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);o[l]=e[i]}return[o,n]}function at(e){const t=Qe(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 O1(e){const t=Qe(e)[0];let r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);const n=Math.log(r);return e.map(a=>a-t-n)}function Wi(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}function Qe(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]>t&&(t=e[n],r=n);return[t,r]}function A_(e){return e>0&&(e&e-1)===0}var C_=class{constructor(e){if(this.size=e|0,this.size<=1||!A_(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;r<this.table.length;r+=2){const n=Math.PI*r/this.size;this.table[r]=Math.cos(n),this.table[r+1]=-Math.sin(n)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let n=0;n<this._width;n+=2){const s=this._width-n-2;this._bitrev[r]|=(r>>>n&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const r=t||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)r[n>>>1]=e[n];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let n=0;n<r.length;n+=2)r[n]=e[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<e.length;++r)e[r]/=this.size}_transform4(e,t,r){const n=this._csize;let a=1<<this._width,o=n/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const h=c[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<n;i+=o,++l){const h=c[l];this._singleTransform4(t,e,i,h,a,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const h=o>>>2;for(i=0;i<n;i+=o){const _=i+h-1;for(let p=i,w=0;p<_;p+=2,w+=a){const v=p,y=v+h,x=y+h,k=x+h,A=e[v],S=e[v+1],C=e[y],O=e[y+1],M=e[x],V=e[x+1],G=e[k],U=e[k+1],J=d[w],Q=r*d[w+1],B=C*J-O*Q,L=C*Q+O*J,ee=d[2*w],H=r*d[2*w+1],ne=M*ee-V*H,Se=M*H+V*ee,Y=d[3*w],N=r*d[3*w+1],D=G*Y-U*N,R=G*N+U*Y,re=A+ne,Z=S+Se,Me=A-ne,Ne=S-Se,Oe=B+D,Ke=L+R,Ot=r*(B-D),Ze=r*(L-R);e[v]=re+Oe,e[v+1]=Z+Ke,e[y]=Me+Ze,e[y+1]=Ne-Ot,e[x]=re-Oe,e[x+1]=Z-Ke,e[k]=Me-Ze,e[k+1]=Ne+Ot}}}}_singleTransform2(e,t,r,n,s){const a=e[n],o=e[n+1],i=e[n+s],l=e[n+s+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,n,s,a){const o=s*2,i=s*3,l=e[n],c=e[n+1],d=e[n+s],h=e[n+s+1],_=e[n+o],p=e[n+o+1],w=e[n+i],v=e[n+i+1],y=l+_,x=c+p,k=l-_,A=c-p,S=d+w,C=h+v,O=a*(d-w),M=a*(h-v);t[r]=y+S,t[r+1]=x+C,t[r+2]=k+M,t[r+3]=A-O,t[r+4]=y-S,t[r+5]=x-C,t[r+6]=k-M,t[r+7]=A+O}_realTransform4(e,t,r){const n=this._csize;let a=1<<this._width,o=n/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<n;i+=o,++l){const _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<n;i+=o)for(let v=0,y=0;v<=w;v+=2,y+=a){const x=i+v,k=x+p,A=k+p,S=A+p,C=e[x],O=e[x+1],M=e[k],V=e[k+1],G=e[A],U=e[A+1],J=e[S],Q=e[S+1],B=C,L=O,ee=d[y],H=r*d[y+1],ne=M*ee-V*H,Se=M*H+V*ee,Y=d[2*y],N=r*d[2*y+1],D=G*Y-U*N,R=G*N+U*Y,re=d[3*y],Z=r*d[3*y+1],Me=J*re-Q*Z,Ne=J*Z+Q*re,Oe=B+D,Ke=L+R,Ot=B-D,Ze=L-R,wt=ne+Me,be=Se+Ne,ue=r*(ne-Me),Fe=r*(Se-Ne);if(e[x]=Oe+wt,e[x+1]=Ke+be,e[k]=Ot+Fe,e[k+1]=Ze-ue,v===0){e[A]=Oe-wt,e[A+1]=Ke-be;continue}if(v===w)continue;const vt=i+p-v,lr=i+_-v;e[vt]=Ot-r*Fe,e[vt+1]=-Ze-r*ue,e[lr]=Oe-r*wt,e[lr+1]=-Ke+r*be}}const h=n>>>1;for(let _=2;_<h;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,t,r,n,s){const a=e[n],o=e[n+s];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,n,s,a){const o=s*2,i=s*3,l=e[n],c=e[n+s],d=e[n+o],h=e[n+i],_=l+d,p=l-d,w=c+h,v=a*(c-h);t[r]=_+w,t[r+1]=0,t[r+2]=p,t[r+3]=-v,t[r+4]=_-w,t[r+5]=0,t[r+6]=p,t[r+7]=v}},N1=class{constructor(e){const t=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=t;const s=new Float64Array(r),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){const d=(c+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),p=2*c;s[p]=h*Math.cos(_),s[p+1]=h*Math.sin(_),a[p]=s[p],a[p+1]=-s[p+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,c=this._a;if(r)for(let d=0;d<l.length;d+=2){const h=d+1,_=d>>1,p=t[_];n[d]=p*l[d],n[h]=p*l[h]}else for(let d=0;d<l.length;d+=2){const h=d+1;n[d]=t[d]*l[d]-t[h]*l[h],n[h]=t[d]*l[h]+t[h]*l[d]}this._f.transform(a,n);for(let d=0;d<i.length;d+=2){const h=d+1;s[d]=a[d]*i[d]-a[h]*i[h],s[h]=a[d]*i[h]+a[h]*i[d]}this._f.inverseTransform(o,s);for(let d=0;d<o.length;d+=2){const h=o[d+c],_=o[d+c+1],p=l[d],w=l[d+1];e[d]=h*p-_*w,e[d+1]=h*w+_*p}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},D1=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=A_(e),this.isPowerOfTwo?(this.fft=new C_(e),this.outputBufferSize=2*e):(this.fft=new N1(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function z1(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const r=new e.constructor(e.length),n=new e.constructor(t),s=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-s;i<=s;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function ds(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function B1(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function R1(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;d<n[1];++d)for(let h=1;h<n[0];++h){const _=s[h-1][d-1],p=s[h-1][d],w=s[h][d-1];let v,y;_<p&&_<w?(v=_,y=0):p<_&&p<w?(v=p,y=1):(v=w,y=2),s[h][d]=e[h-1][d-1]+v,a[h][d]=y}for(let d=0;d<n[1];++d)a[0][d]=2;for(let d=0;d<n[0];++d)a[d][0]=1;let o=t,i=r,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.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(),c.reverse(),[l,c]}var $1=(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<e.length;++l){let c=0;const d=(l&32768)<<16,h=(l&31744)>>10;let _=l&1023;if(h===31)c=d|2139095040|_<<13;else if(h===0)if(_===0)c=d;else{let p=113;for(;(_&1024)===0;)_<<=1,--p;_&=-1025,c=d|p<<23|_<<13}else c=d|h+112<<23|_<<13;o[0]=c,e[l]=i[0]}}const r=t.length,n=e,s=new Float32Array(r);for(let a=0;a<r;++a)s[a]=n[t[a]];return s}})(),G1={};async function S_(e){const t=e.split("/").pop();let r;try{if(r=await Gi(),r){const s=await r.match(e);if(s)return s}}catch(s){he.warn(`Failed to load ${t} from cache:`,s)}const n=await ve.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){he.warn(`Failed to cache ${t}:`,s)}return n}async function V1(e){const t=await S_(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return he.warn("Failed to read WASM binary:",r),null}}async function U1(e){if(pe.IS_SERVICE_WORKER_ENV||pe.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 he.warn("Failed to read WASM factory:",r),null}}var j1=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<=Rt.DEBUG?0:e<=Rt.INFO?2:e<=Rt.WARNING||e<=Rt.ERROR?3:4}var W1={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},It=[],qi,Nr,F_=Symbol.for("onnxruntime");if(F_ in globalThis)Nr=globalThis[F_];else if(pe.IS_NODE_ENV){switch(Nr=G1,process.platform){case"win32":It.push("dml");break;case"linux":process.arch==="x64"&&It.push("cuda");break;case"darwin":It.push("coreml");break}It.push("webgpu"),It.push("cpu"),qi=["cpu"]}else Nr=pb,pe.IS_WEBNN_AVAILABLE&&It.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),pe.IS_WEBGPU_AVAILABLE&&It.push("webgpu"),It.push("wasm"),qi=["wasm"];var q1=Nr.InferenceSession;function H1(e=null){if(!e)return qi;switch(e){case"auto":return It;case"gpu":return It.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(It.includes(e))return[j1[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${It.join(", ")}.`)}var I_=Promise.resolve(),yn=null;async function Q1(){var t,r,n,s,a;if(yn)return yn;if(!(ve.useWasmCache&&typeof((t=Le==null?void 0:Le.wasm)==null?void 0:t.wasmPaths)=="object"&&((n=(r=Le==null?void 0:Le.wasm)==null?void 0:r.wasmPaths)==null?void 0:n.wasm)&&((a=(s=Le==null?void 0:Le.wasm)==null?void 0:s.wasmPaths)==null?void 0:a.mjs))){if(pe.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return yn=Promise.resolve(),yn}return yn=(async()=>{const o=Le.wasm.wasmPaths;let i=!1;await Promise.all([o.wasm&&!v_(o.wasm)?(async()=>{try{const l=await V1($i(o.wasm));l&&(Le.wasm.wasmBinary=l,i=!0)}catch(l){he.warn("Failed to pre-load WASM binary:",l)}})():Promise.resolve(),o.mjs&&!v_(o.mjs)?(async()=>{try{const l=await U1($i(o.mjs));l&&(Le.wasm.wasmPaths.mjs=l)}catch(l){he.warn("Failed to pre-load WASM factory:",l)}})():Promise.resolve()]),i||(Le.wasm.wasmPaths.mjs=o.mjs)})(),yn}async function L_(e,t,r){await Q1();const n=P_(ve.logLevel??Rt.WARNING),s=()=>q1.create(e,{logSeverityLevel:n,...t}),a=await(pe.IS_WEB_ENV?I_=I_.then(s):s());return a.config=r,a}var O_=Promise.resolve();async function N_(e,t){const r=()=>e.run(t);return pe.IS_WEB_ENV?O_=O_.then(r):r()}function D_(e){return e instanceof Nr.Tensor}var Le=Nr==null?void 0:Nr.env;function Hi(){var e;return(e=Le==null?void 0:Le.wasm)==null?void 0:e.proxy}if(Le){let e=function(t){const r=P_(t);Le.logLevel=W1[r]};if(Le.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&((vw=Le.versions)!=null&&vw.web)&&!Le.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Le.versions.web}/dist/`;let r=".asyncify";pe.IS_SAFARI_BELOW_26&&!pe.IS_WEBGPU_AVAILABLE&&(r=""),Le.wasm.wasmPaths={mjs:`${t}ort-wasm-simd-threaded${r}.mjs`,wasm:`${t}ort-wasm-simd-threaded${r}.wasm`}}Le.wasm.proxy=!1}Le.webgpu&&(Le.webgpu.powerPreference="high-performance"),e(ve.logLevel??Rt.WARNING),ve.backends.onnx={...Le,setLogLevel:e}}var Dr=async(e,t,r)=>{const n=await L_(new Uint8Array(e),t);return(async s=>{const a=Hi(),o=Object.fromEntries(Object.entries(s).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await N_(n,o);return Array.isArray(r)?r.map(l=>new j(i[l])):new j(i[r])})},bn=($u=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Dr([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=Dr([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=Dr([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=Dr([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=Dr([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=Dr([8,9,58,93,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,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Dr([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=Dr([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}},T($u,"session_options",{}),$u),X1=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"}),Qi=pe.IS_NODE_ENV?"cpu":"wasm";function z_(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 (${Qi}).`),Qi):Qi}var Y1=(function(){let e;return async function(){if(e===void 0)if(!pe.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),Ye=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"}),B_=Ye.fp32,R_=Object.freeze({[X1.wasm]:Ye.q8}),Xi=Object.freeze({[Ye.fp32]:"",[Ye.fp16]:"_fp16",[Ye.int8]:"_int8",[Ye.uint8]:"_uint8",[Ye.q8]:"_quantized",[Ye.q4]:"_q4",[Ye.q2]:"_q2",[Ye.q1]:"_q1",[Ye.q4f16]:"_q4f16",[Ye.q2f16]:"_q2f16",[Ye.q1f16]:"_q1f16",[Ye.bnb4]:"_bnb4"});function $_(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===Ye.auto){if(n){const l=typeof n=="string"?n:n==null?void 0:n[t];if(l&&l!==Ye.auto&&Ye.hasOwnProperty(l))return l}i=R_[r]??B_}else a&&Ye.hasOwnProperty(a)?i=a:i=R_[r]??B_;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var hs=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}),j=class He{constructor(...t){T(this,"ort_tensor");return D_(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new Eb(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})}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}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;s<t;++s)yield this._subarray(s,n,r)}else yield*this.data}_getitem(t){const[r,...n]=this.dims;if(t=sr(t,r),n.length>0){const s=n.reduce((a,o)=>a*o);return this._subarray(t,s,n)}else return new He(this.type,[this.data[t]],n)}_subarray(t,r,n){const s=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(s,a):this.data.slice(s,a);return new He(this.type,o,n)}item(){const t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return J1(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]=t(r[n],n,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]-=t;return this}remainder(t){return this.clone().remainder_(t)}remainder_(t){const r=this.data,s=r instanceof BigInt64Array||r instanceof BigUint64Array?BigInt(t):Number(t);if((s===0||s===0n)&&(this.type.includes("int")||this.type==="bool"))throw new RangeError("Division by zero");if(s<0&&(this.type.startsWith("uint")||this.type==="bool"))throw new RangeError("Negative divisors are not supported for unsigned or boolean tensors");for(let a=0;a<r.length;++a){const o=r[a]%s,i=o<0&&s>0||o>0&&s<0;r[a]=i?o+s:o}return this}clone(){return new He(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],n=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)n.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=sr(h,this.dims[d],d),n.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[_,p]=h;if(_=_===null?0:sr(_,this.dims[d],d,!1),p=p===null?this.dims[d]:sr(p,this.dims[d],d,!1),_>p)throw new Error(`Invalid slice: ${h}`);const w=[Math.max(_,0),Math.min(p,this.dims[d])];n.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${h}`)}const s=n.map(([d,h])=>h-d),a=s.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride();let c=!0;for(let d=1;d<s.length;++d)if(n[d][0]!==0||n[d][1]!==this.dims[d]){c=!1;break}if(c){const d=n[0][0]*l[0],h=n[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,h));else if(Array.isArray(o)){const _=o.slice(d,h);for(let p=0;p<_.length;++p)i[p]=_[p]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let h=0;for(let _=s.length-1,p=d;_>=0;--_){const w=s[_];h+=(p%w+n[_][0])*l[_],p=Math.floor(p/w)}i[d]=o[h]}return new He(this.type,i,r)}permute(...t){return K1(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=(h,_)=>h+_,i=0n):(o=(h,_)=>h+_**t,i=0),r===null){let h=s.reduce(o,i);return t!==1&&(h=h**(1/t)),new He(this.type,[h],[])}const[l,c,d]=fs(o,this,r,n);if(t!==1)for(let h=0;h<c.length;++h)c[h]=c[h]**(1/t);return new He(l,c,d)}normalize_(t=2,r=1){r=sr(r,this.dims.length);const n=this.norm(t,r,!0),s=this.data,a=n.data;for(let o=0;o<s.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){const h=this.dims[l];if(l!==r){const _=c%h;i+=_*d,d*=this.dims[l]}c=Math.floor(c/h)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Ji(this.dims)}squeeze(t=null){return new He(this.type,this.data,U_(this.dims,t))}squeeze_(t=null){return this.dims=U_(this.dims,t),this}unsqueeze(t){return new He(this.type,this.data,j_(this.dims,t))}unsqueeze_(t){return this.dims=j_(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;s<t.length;++s)if(t[s]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=s}const n=this.data;if(r!==-1){const s=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=n.length/s}return new He(this.type,n,t)}neg_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]>t?1:0;return new He("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]<t?1:0;return new He("bool",r,this.dims)}clamp_(t,r){const n=this.data;for(let s=0;s<n.length;++s)n[s]=Math.min(Math.max(n[s],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return Yi(this,t,r)}min(t=null,r=!1){if(t===null){const o=Wi(this.data)[0];return new He(this.type,[o],[])}const[n,s,a]=fs((o,i)=>Math.min(o,i),this,t,r,1/0);return new He(n,s,a)}max(t=null,r=!1){if(t===null){const o=Qe(this.data)[0];return new He(this.type,[o],[])}const[n,s,a]=fs((o,i)=>Math.max(o,i),this,t,r,-1/0);return new He(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Wi(this.data)[1];return new He("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Qe(this.data)[1];return new He("int64",[BigInt(n)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(d=>d===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,h=Array(d).fill(1).concat(this.dims);return new He(this.type,this.data.slice(),h)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((d,h)=>d*t[h]),a=s.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=Ji(n),c=Ji(s);for(let d=0;d<a;++d){let h=d,_=0;for(let p=0;p<s.length;++p){const w=Math.floor(h/c[p]);h=h%c[p];const v=w%n[p];_+=v*l[p]}i[d]=o[_]}return new He(this.type,i,s)}tile(...t){if(t.length<this.dims.length){const r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!hs.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r;const n=["int64","uint64"].includes(this.type),s=["int64","uint64"].includes(t);if(n&&!s)r=Number;else if(!n&&s)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new He(t,$1(this.data),this.dims);return new He(t,hs[t].from(this.data,r),this.dims)}};function J1(e,t){const r=e.length,n=t.length===0?1: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.length<t[a]?l.push(i):o.push([i]),o},[[]]);return s[0]}function K1(e,t){const[r,n]=L1(e.data,e.dims,t);return new j(e.type,r,n)}function G_(e,[t,r],n="bilinear",s=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=I1(e.data,[a,o,i],[t,r],n,s);return new j(e.type,l,[a,t,r])}async function qt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let n;if(t.length===2)n=[...e.dims.slice(0,2),...t];else if(t.length===3)n=[e.dims[0],...t];else if(t.length===4)n=t;else throw new Error("`size` must be of length 2, 3, or 4.");let s;if(r==="nearest")s=await bn.nearest_interpolate_4d;else if(r==="bilinear")s=await bn.bilinear_interpolate_4d;else if(r==="bicubic")s=await bn.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new j("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await s({x:e,s:a})}async function Z1(e,t){return await(await bn.matmul)({a:e,b:t})}async function Mn(e,t){const r=await bn.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new j("int64",[BigInt(t)],[1])})}var Ta=e=>new j("int64",e,[e.length]);async function V_(e,t,r,n,s){return await(await bn.slice)({x:e,s:Ta(t),e:Ta(r),a:Ta(n),t:Ta(new Array(n.length).fill(1))})}function ek(e,t){const r=e.data,n=t.data,s=[e.dims[0],e.dims[2]],a=new r.constructor(s[0]*s[1]),[o,i,l]=e.dims;let c=0;for(let d=0;d<o;++d){const h=d*l*i;for(let _=0;_<l;++_){let p=0,w=0;const v=d*i,y=h+_;for(let k=0;k<i;++k){const A=Number(n[v+k]);w+=A,p+=r[y+k*l]*A}const x=p/w;a[c++]=x}}return new j(e.type,a,s)}function U_(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 j_(e,t){return t=sr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function sr(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 Re(e,t=0){t=sr(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<e.length;++i){const{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let h=0;for(let _=c.length-1,p=d,w=1;_>=0;--_){const v=c[_];let y=p%v;_===t&&(y+=o),h+=y*w,w*=r[_],p=Math.floor(p/v)}s[h]=l[d]}o+=c[t]}}return new j(a,s,r)}function pr(e,t=0){return Re(e.map(r=>r.unsqueeze(t)),t)}function fs(e,t,r,n=!1,s=null){const a=t.data,o=t.dims;r=sr(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 c=0;c<a.length;++c){let d=0;for(let h=o.length-1,_=c,p=1;h>=0;--h){const w=o[h];if(h!==r){const v=_%w;d+=v*p,p*=i[h]}_=Math.floor(_/w)}l[d]=e(l[d],a[c],c,d)}return n||i.splice(r,1),[t.type,l,i]}function tk(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const p=s.reduce((x,k)=>x+k,0)/s.length,w=Math.sqrt(s.reduce((x,k)=>x+(k-p)**2,0)/(s.length-r)),v=new j(e.type,[p],[]);return[new j(e.type,[w],[]),v]}t=sr(t,a.length);const o=Yi(e,t,n),i=o.data,[l,c,d]=fs((_,p,w,v)=>_+(p-i[v])**2,e,t,n);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return[new j(l,c,d),o]}function Yi(e,t=null,r=!1){const n=e.dims,s=e.data;if(t===null){const l=s.reduce((c,d)=>c+d,0);return new j(e.type,[l/s.length],[])}t=sr(t,n.length);const[a,o,i]=fs((l,c)=>l+c,e,t,r);if(n[t]!==1)for(let l=0;l<o.length;++l)o[l]/=n[t];return new j(a,o,i)}function Ji(e){const t=new Array(e.length);for(let r=e.length-1,n=1;r>=0;--r)t[r]=n,n*=e[r];return t}function Ki(e,t,r,n){const s=e.reduce((a,o)=>a*o,1);return new j(r,new n(s).fill(t),e)}function dt(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 Ki(e,t,r,n)}function Zi(e,t){return dt(e.dims,t)}function xt(e){return Ki(e,1n,"int64",BigInt64Array)}function el(e){return xt(e.dims)}function W_(e){return Ki(e,0n,"int64",BigInt64Array)}function tl(e){return W_(e.dims)}function rk(e){const t=e.reduce((r,n)=>r*n,1);return new j("float32",Float32Array.from({length:t},()=>zi.gauss()),e)}function nk(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const r=t==="binary",n=r?"int8":"uint8",s=r?Int8Array:Uint8Array,a=e.data,o=new s(a.length/8);for(let i=0;i<a.length;++i){const l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,r&&d===0&&(o[c]-=128)}return new j(n,o,[e.dims[0],e.dims[1]/8])}async function q_(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await cs(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function H_(e,t){const r=await q_(e);return await Promise.all(r.map(n=>nr(e,n,!0,t)))}function rl(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 sk=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ak(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"?er(e[s],i):er(i,e[s])}}function ok(e,t){for(const r of Object.keys(e))e[r].length=t}function tn(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 ik(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var de=class extends gt{constructor(t,r){super();T(this,"return_token_type_ids",!1);T(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new gx(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=tn(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=tn(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=tn(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=tn(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=tn(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=tn(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const s=Object.create(null);for(const{name:a,template:o}of this.chat_template){if(typeof a!="string"||typeof o!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[a]=o}this.chat_template=s}this._compiled_template_cache=new Map;const n=ik(this._tokenizer);this.all_special_ids=n.map(s=>s.id),this.all_special_tokens=n.map(s=>s.content)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){const i=await H_(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,r={}){const{text_pair:n=null,add_special_tokens:s=!0,padding:a=!1,return_token_type_ids:o=null}=r;let{truncation:i=null,max_length:l=null}=r;const c=r.return_tensor??!0,d=Array.isArray(t);let h;if(d){if(t.length===0)throw Error("text array must be non-empty");if(n!==null){if(Array.isArray(n)){if(t.length!==n.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=t.map((p,w)=>this._encode_plus(p,{text_pair:n[w],add_special_tokens:s,return_token_type_ids:o}))}else h=t.map(p=>this._encode_plus(p,{add_special_tokens:s,return_token_type_ids:o}))}else{if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(t,{text_pair:n,add_special_tokens:s,return_token_type_ids:o})]}if(l===null?l=this.model_max_length:i===null&&(a===!0?(he.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):a===!1&&(he.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),a===!0&&(l=Math.min(Qe(h.map(p=>p.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),a||i)for(let p=0;p<h.length;++p)h[p].input_ids.length!==l&&(h[p].input_ids.length>l?i&&ok(h[p],l):a&&ak(h[p],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));const _={};if(c){if(!(a&&i)&&h.some(w=>{var v;for(const y of Object.keys(w))if(w[y].length!==((v=h[0][y])==null?void 0:v.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 p=[h.length,h[0].input_ids.length];for(const w of Object.keys(h[0]))_[w]=new j("int64",BigInt64Array.from(h.flatMap(v=>v[w]).map(BigInt)),p)}else{for(const p of Object.keys(h[0]))_[p]=h.map(w=>w[p]);if(!d)for(const p of Object.keys(_))_[p]=_[p][0]}return _}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){const{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s??this.return_token_type_ids});return{input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:n})}encode(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s}).ids}batch_decode(t,r={}){return t instanceof j&&(t=t.tolist()),t.map(n=>this.decode(n,r))}decode(t,r={}){if(t instanceof j&&(t=rl(t)),!Array.isArray(t)||t.length===0||!Vb(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const n=this.chat_template;if(t!==null&&Object.hasOwn(n,t))t=n[t];else if(t===null)if(r!==null&&"tool_use"in n)t=n.tool_use;else if("default"in n)t=n.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(n).sort()}.`)}else if(t===null)if(this.chat_template)t=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 t}apply_chat_template(t,r={}){let{tools:n=null,documents:s=null,chat_template:a=null,add_generation_prompt:o=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:d=null,return_tensor:h=!0,return_dict:_=!0,tokenizer_kwargs:p={},...w}=r;if(a=this.get_chat_template({chat_template:a,tools:n}),typeof a!="string")throw Error(`chat_template must be a string, but got ${typeof a}`);let v=this._compiled_template_cache.get(a);v===void 0&&(v=new p1(a),this._compiled_template_cache.set(a,v));const y=Object.create(null);for(const k of sk){const A=tn(this.config,k);A&&(y[k]=A)}const x=v.render({messages:t,add_generation_prompt:o,tools:n,documents:s,...y,...w});if(i){const k=this._call(x,{add_special_tokens:!1,padding:l,truncation:c,max_length:d,return_tensor:h,...p});return _?k:k.input_ids}return x}};function nl(e,t,r,n){var o;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(", ")}}`);const i=(o=e._tokenizer.post_processor)==null?void 0:o.config;if(i&&"single"in i){for(const l of i.single)if("SpecialToken"in l&&e.languageRegex.test(l.SpecialToken.id)){l.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 Q_={};as(Q_,{AlbertTokenizer:()=>lk,AutoTokenizer:()=>Te,BartTokenizer:()=>ck,BertTokenizer:()=>uk,BlenderbotSmallTokenizer:()=>dk,BlenderbotTokenizer:()=>hk,BloomTokenizer:()=>fk,CLIPTokenizer:()=>pk,CamembertTokenizer:()=>_k,CodeGenTokenizer:()=>gk,CodeLlamaTokenizer:()=>mk,CohereAsrTokenizer:()=>vk,CohereTokenizer:()=>wk,ConvBertTokenizer:()=>yk,DebertaTokenizer:()=>Mk,DebertaV2Tokenizer:()=>bk,DistilBertTokenizer:()=>xk,ElectraTokenizer:()=>kk,EsmTokenizer:()=>Tk,FalconTokenizer:()=>Ek,GPT2Tokenizer:()=>Sk,GPTNeoXTokenizer:()=>Ck,GemmaTokenizer:()=>Ak,HerbertTokenizer:()=>Pk,LlamaTokenizer:()=>Fk,M2M100Tokenizer:()=>Ik,MBart50Tokenizer:()=>Ok,MBartTokenizer:()=>X_,MPNetTokenizer:()=>zk,MarianTokenizer:()=>Lk,MgpstrTokenizer:()=>Nk,MobileBertTokenizer:()=>Dk,NllbTokenizer:()=>Bk,NougatTokenizer:()=>Rk,PreTrainedTokenizer:()=>de,Qwen2Tokenizer:()=>$k,RoFormerTokenizer:()=>Vk,RobertaTokenizer:()=>Gk,SiglipTokenizer:()=>Uk,SpeechT5Tokenizer:()=>jk,SqueezeBertTokenizer:()=>Wk,T5Tokenizer:()=>qk,TokenizersBackend:()=>de,VitsTokenizer:()=>Qk,Wav2Vec2CTCTokenizer:()=>Xk,WhisperTokenizer:()=>eT,XLMRobertaTokenizer:()=>tT,XLMTokenizer:()=>rT});var lk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},ck=class extends de{},uk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},dk=class extends de{},hk=class extends de{},fk=class extends de{},_k=class extends de{},pk=class extends de{},mk=class extends de{},gk=class extends de{},wk=class extends de{},vk=class extends de{},yk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},bk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},Mk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},xk=class extends de{},kk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},Tk=class extends de{},Ek=class extends de{},Ak=class extends de{},Ck=class extends de{},Sk=class extends de{},Pk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},Fk=class extends de{constructor(){super(...arguments);T(this,"padding_side","left")}},Ik=class extends de{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 nl(this,e,t,r)}},Lk=class extends de{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)),he.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)||he.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),er([n],super._encode_text(s))}}},X_=class extends de{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 nl(this,e,t,r)}},Ok=class extends X_{},Nk=class extends de{},Dk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},zk=class extends de{},Bk=class extends de{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 nl(this,e,t,r)}},Rk=class extends de{},$k=class extends de{},Gk=class extends de{},Vk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},Uk=class extends de{},jk=class extends de{},Wk=class extends de{constructor(){super(...arguments);T(this,"return_token_type_ids",!0)}},qk=class extends de{},Hk=class extends Vt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},Qk=class extends de{constructor(e,t){super(e,t),this._tokenizer.decoder=new Hk({type:"VitsDecoder"})}},Xk=class extends de{},Y_=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Ea=new Map(Y_),Yk=new Map([...Y_.map(([e,t])=>[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 Jk(e){e=e.toLowerCase();let t=Yk.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),Ea.has(e))t=e;else{const s=e.length===2?Ea.keys():Ea.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var Kk="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",J_=new RegExp(`^[${Kk}]+$`,"gu"),Zk=.1,eT=class extends de{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 c=i(),d=0;const h=this.timestamp_begin,p=h+1500;let w=[],v=[],y=!1,x=null;const k=new Set(this.all_special_ids);for(const C of e){const O=C.tokens,M=o?C.token_timestamps:null;let V=null,G=h;if("stride"in C){const[Q,B,L]=C.stride;if(d-=B,x=Q-L,B&&(G=B/n+h),L)for(let ee=O.length-1;ee>=0;--ee){const H=Number(O[ee]);if(H>=h){if(V!==null&&(H-h)*n<x)break;V=H}}}let U=[],J=[];for(let Q=0;Q<O.length;++Q){const B=Number(O[Q]);if(k.has(B)){const L=this.decode([B]),ee=Ea.get(L.slice(2,-2));if(ee!==void 0){if(a!==null&&ee!==a&&!t){w.push(U);const H=this.findLongestCommonSequence(w)[0],ne=this.decode(H);c.text=ne,l.push(c),w=[],U=[],c=i()}a=c.language=ee}}else if(B>=h&&B<=p){const L=(B-h)*n+d,ee=ds(L,2);if(V!==null&&B>=V)y=!0;else if(y||w.length>0&&B<G)y=!1;else if(c.timestamp[0]===null)c.timestamp[0]=ee;else if(ee!==c.timestamp[0]){c.timestamp[1]=ee,w.push(U),o&&v.push(J);const[H,ne]=this.findLongestCommonSequence(w,v),Se=this.decode(H);if(c.text=Se,o&&(c.words=this.collateWordTimestamps(H,ne,a),c.words.length>0&&c.timestamp[1]!==null))for(const Y of c.words)Y.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=Y.timestamp[0]&&(Y.timestamp[1]=c.timestamp[1]);l.push(c),w=[],U=[],v=[],J=[],c=i()}}else if(U.push(B),o){let L=ds(M[Q]+d,2),ee;if(Q+1<M.length){ee=ds(M[Q+1]+d,2);const H=this.decode([B]);J_.test(H)&&(ee=ds(Math.min(L+n,ee),2))}else ee=null;J.push([L,ee])}}if("stride"in C){const[Q,B,L]=C.stride;d+=Q-L}U.length>0?(w.push(U),o&&v.push(J)):w.every(Q=>Q.length===0)&&(c=i(),w=[],U=[],v=[],J=[])}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[C,O]=this.findLongestCommonSequence(w,v),M=this.decode(C);c.text=M,o&&(c.words=this.collateWordTimestamps(C,O,a)),l.push(c)}let A=Object.create(null);const S=l.map(C=>C.text).join("");if(t||r){for(let C=0;C<l.length;++C){const O=l[C];t||delete O.timestamp,r||delete O.language}if(o){const C=[];for(const O of l)for(const M of O.words)C.push(M);A={chunks:C}}else A={chunks:l}}return[S,A]}findLongestCommonSequence(e,t=null){let r=e[0],n=r.length,s=[];const a=Array.isArray(t)&&t.length>0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,h=[n,n,0,0];const _=c.length;for(let A=1;A<n+_;++A){const S=Math.max(0,n-A),C=Math.min(n,n+_-A),O=r.slice(S,C),M=Math.max(0,A-n),V=Math.min(_,A),G=c.slice(M,V);if(O.length!==G.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let U;a?U=O.filter((B,L)=>B===G[L]&&i[S+L][0]-Zk<=t[l][M+L][0]).length:U=O.filter((B,L)=>B===G[L]).length;const J=A/1e4,Q=U/A+J;U>1&&Q>d&&(d=Q,h=[S,C,M,V])}const[p,w,v,y]=h,x=Math.floor((w+p)/2);let k=Math.floor((y+v)/2);if(a&&d===0&&n>0){const A=i[n-1][0],S=t[l].findIndex(C=>C[0]>=A);k=S===-1?c.length:S}s.push(...r.slice(0,x)),r=c.slice(k),n=r.length,a&&(o.push(...i.slice(0,x)),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.length;++i){const l=a[i];o.push({text:n[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,n=`"'.。,,!!??::”)]}、`){t=t??"english";let s,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[s,a,o]=this.splitTokensOnUnicode(e):[s,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(s,a,o,r,n)}decode(e,t){let r;return t!=null&&t.decode_with_timestamps?(e instanceof j&&(e=rl(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){const r=(t==null?void 0:t.time_precision)??.02,n=this.all_special_ids.at(-1)+1;let s=[[]];for(let a of e)if(a=Number(a),a>=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 c=0;c<e.length;++c){const d=e[c];o.push(d),i.push(c);const h=this.decode(o,{decode_with_timestamps:!0});(!h.includes(r)||t[l+h.indexOf(r)]===r)&&(n.push(h),s.push(o),a.push(i),o=[],i=[],l+=h.length)}return[n,s,a]}splitTokensOnSpaces(e){const[t,r,n]=this.splitTokensOnUnicode(e),s=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],c=r[i],d=n[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=J_.test(p);if(h||_||w||s.length===0)s.push(l),a.push(c),o.push(d);else{const v=s.length-1;s[v]+=l,a[v].push(...c),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,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=er(o[l],o[c]),i[c]=er(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&s.includes(a[c])?(a[l]+=a[c],o[l]=er(o[l],o[c]),i[l]=er(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},tT=class extends de{},rT=class extends de{constructor(t,r){super(t,r);T(this,"return_token_type_ids",!0);he.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Te=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"}={}){var d;const[o,i]=await H_(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=((d=i.tokenizer_class)==null?void 0:d.replace(/Fast$/,""))??"PreTrainedTokenizer";let c=Q_[l];return c||(he.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=de),new c(o,i)}},Aa="https://github.com/huggingface/transformers.js/issues/new/choose",K_="preprocessor_config.json",_s="preprocessor_config.json",Z_="processor_config.json",ep="chat_template.jinja",Ee=(Ss=class extends gt{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?nr(e,Z_,!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?ji(e,ep,!0,t):null]);return new this(r,n,s)}},T(Ss,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),T(Ss,"uses_processor_config",!1),T(Ss,"uses_chat_template_file",!1),Ss),sl={};as(sl,{ChatterboxProcessor:()=>FT,CohereAsrProcessor:()=>LT,EmbeddingGemma2Processor:()=>RT,EmbeddingGemma2VideoProcessor:()=>_p,Florence2Processor:()=>DE,Gemma3Processor:()=>zE,Gemma3nProcessor:()=>BE,Gemma4Processor:()=>fp,Glm46VProcessor:()=>RE,GraniteSpeechProcessor:()=>$E,GroundingDinoProcessor:()=>VE,Idefics3Processor:()=>Bp,JinaCLIPProcessor:()=>HE,Lfm2VlProcessor:()=>QE,LlavaProcessor:()=>XE,MgpstrProcessor:()=>YE,MoonshineProcessor:()=>JE,OwlViTProcessor:()=>KE,PaliGemmaProcessor:()=>e2,Phi3VProcessor:()=>r2,PixtralProcessor:()=>n2,Processor:()=>Ee,PyAnnoteProcessor:()=>s2,Qwen2VLProcessor:()=>gl,Qwen2_5_VLProcessor:()=>Gp,Qwen3VLProcessor:()=>a2,Sam2Processor:()=>Up,Sam2VideoProcessor:()=>o2,SamProcessor:()=>Vp,SmolVLMProcessor:()=>Bp,SpeechT5Processor:()=>i2,UltravoxProcessor:()=>l2,VLChatProcessor:()=>qE,VoxtralProcessor:()=>h2,VoxtralRealtimeProcessor:()=>p2,Wav2Vec2Processor:()=>m2,Wav2Vec2ProcessorWithLM:()=>g2,WhisperProcessor:()=>w2});var ht=class extends gt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await nr(e,K_,!0,t);return new this(r)}};function ot(e,t){var r;if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${((r=e==null?void 0:e.constructor)==null?void 0:r.name)??typeof e} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var al={};as(al,{ASTFeatureExtractor:()=>gT,ChatterboxFeatureExtractor:()=>wT,ClapFeatureExtractor:()=>vT,CohereAsrFeatureExtractor:()=>bT,DacFeatureExtractor:()=>lp,EncodecFeatureExtractor:()=>op,FeatureExtractor:()=>ht,Gemma3nAudioFeatureExtractor:()=>cp,Gemma4AudioFeatureExtractor:()=>up,GraniteSpeechFeatureExtractor:()=>MT,MoonshineFeatureExtractor:()=>xT,ParakeetFeatureExtractor:()=>ip,PyAnnoteFeatureExtractor:()=>dp,SeamlessM4TFeatureExtractor:()=>kT,SnacFeatureExtractor:()=>TT,SpeechT5FeatureExtractor:()=>ET,VoxtralRealtimeFeatureExtractor:()=>ST,Wav2Vec2FeatureExtractor:()=>AT,WeSpeakerFeatureExtractor:()=>CT,WhisperFeatureExtractor:()=>PT});var nT=()=>{},sT=nT;async function tp(e,t){if(pe.IS_BROWSER_ENV){if(pe.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(pe.IS_FS_AVAILABLE)t.stream(),At.createWriteStream(e),await sT();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function aT(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const r=await(await us(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});typeof t>"u"&&he.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const s=await n.decodeAudioData(r);let a;if(s.numberOfChannels===2){const o=Math.sqrt(2),i=s.getChannelData(0),l=s.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<s.length;++c)a[c]=o*(i[c]+l[c])/2}else a=s.getChannelData(0);return a}async function oT(e,t){return await aT(e,t)}function rp(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;a<e;++a)s[a]=t-r*Math.cos(a*n);return s}function np(e){return rp(e,.5)}function iT(e){return rp(e,.54)}var lT={htk:e=>2595*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 ol(e,t="htk"){const r=lT[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 cT={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 uT(e,t="htk"){const r=cT[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 dT(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;o<e.length;++o){const i=n[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const s=t.length-2,a=Array.from({length:s},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=n[o];for(let l=0;l<s;++l){const c=-i[l]/r[l],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,d))}}return a}function sp(e,t,r){const n=(t-e)/(r-1);return Float64Array.from({length:r},(s,a)=>e+n*a)}function ar(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=ol(r,o),c=ol(n,o),d=sp(l,c,t+2);let h=uT(d,o),_;if(i){const w=s/((e-1)*2);_=ol(Float64Array.from({length:e},(v,y)=>y*w),o),h=d}else _=sp(0,Math.floor(s/2),e);const p=dT(_,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){const v=p[w],y=2/(h[w+2]-h[w]);for(let x=0;x<e;++x)v[x]*=y}return p}function hT(e,t,r){const n=new e.constructor(e.length+t+r),s=e.length-1;for(let a=0;a<e.length;++a)n[t+a]=e[a];for(let a=1;a<=t;++a)n[t-a]=e[ca(a,s)];for(let a=1;a<=r;++a)n[s+t+a]=e[ca(s-a,s)];return n}function ap(e,t,r,n,s){if(r<=0)throw new Error("reference must be greater than zero");if(n<=0)throw new Error("min_value must be greater than zero");r=Math.max(n,r);const a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(n,e[o])-a);if(s!==null){if(s<=0)throw new Error("db_range must be greater than zero");const o=Qe(e)[0]-s;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function fT(e,t=1,r=1e-5,n=null){return ap(e,20,t,r,n)}function _T(e,t=1,r=1e-10,n=null){return ap(e,10,t,r,n)}async function or(e,t,r,n,{fft_length:s=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:h=null,mel_floor:_=1e-10,log_mel:p=null,max_log_mel:w=null,reference:v=1,min_value:y=1e-10,db_range:x=null,remove_dc_offset:k=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:C=!0,transpose:O=!1,mel_offset:M=0,mel_floor_mode:V="clamp"}={}){const G=t.length;if(s===null&&(s=r),r>s)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(G!==r)throw new Error(`Length of the window (${G}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&h!==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 D=Math.floor(r/2);switch(i){case"reflect":{e=hT(e,D,D);break}case"constant":{const R=new e.constructor(e.length+2*D);R.set(e,D),e=R;break}case"semicausal":{const R=new e.constructor(e.length+D);R.set(e,D),e=R;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((e.length-r)/n));A!==null&&U<A&&(U=A);const J=l?Math.floor(s/2)+1:s;let Q=U,B=U;S!==null&&(S>U?C&&(B=S):B=Q=S);const L=new D1(s),ee=new Float64Array(s),H=new Float64Array(L.outputBufferSize),ne=new Float32Array(J*B);for(let D=0;D<Q;++D){const R=D*n,re=Math.min(e.length-R,r);re!==r&&ee.fill(0,0,r);for(let Z=0;Z<re;++Z)ee[Z]=e[R+Z];if(k){let Z=0;for(let Ne=0;Ne<re;++Ne)Z+=ee[Ne];const Me=Z/re;for(let Ne=0;Ne<re;++Ne)ee[Ne]-=Me}if(c!==null){for(let Z=re-1;Z>=1;--Z)ee[Z]-=c*ee[Z-1];ee[0]*=1-c}for(let Z=0;Z<t.length;++Z)ee[Z]*=t[Z];L.realTransform(H,ee);for(let Z=0;Z<J;++Z){const Me=Z<<1;ne[Z*B+D]=H[Me]**2+H[Me+1]**2}}if(a!==null&&a!==2){const D=a/2;for(let R=0;R<ne.length;++R)ne[R]**=D}const Se=h.length;let Y=await Z1(new j("float32",h.flat(),[Se,J]),new j("float32",ne,[J,B]));O&&(Y=Y.transpose(1,0));const N=Y.data;if(V==="add")for(let D=0;D<N.length;++D)N[D]=M+N[D]+_;else for(let D=0;D<N.length;++D)N[D]=M+Math.max(_,N[D]);if(a!==null&&p!==null){const D=Math.min(N.length,Q*Se);switch(p){case"log":for(let R=0;R<D;++R)N[R]=Math.log(N[R]);break;case"log10":for(let R=0;R<D;++R)N[R]=Math.log10(N[R]);break;case"log10_max_norm":{for(let Z=0;Z<D;++Z)N[Z]=Math.log10(N[Z]);const re=(w??Qe(N)[0])-8;for(let Z=0;Z<D;++Z)N[Z]=(Math.max(N[Z],re)+4)/4;break}case"dB":if(a===1)fT(N,v,y,x);else if(a===2)_T(N,v,y,x);else throw new Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return Y}function mr(e,t,{periodic:r=!0,frame_length:n=null,center:s=!0}={}){const a=r?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=np(a);break;case"hamming":o=iT(a);break;case"povey":o=np(a).map(c=>Math.pow(c,.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}function pT(e,t){const r=e.reduce((a,o)=>a+o.length,0),n=new ArrayBuffer(44),s=new DataView(n);return Ca(s,0,"RIFF"),s.setUint32(4,36+r*4,!0),Ca(s,8,"WAVE"),Ca(s,12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,1,!0),s.setUint32(24,t,!0),s.setUint32(28,t*4,!0),s.setUint16(32,4,!0),s.setUint16(34,32,!0),Ca(s,36,"data"),s.setUint32(40,r*4,!0),new Blob([n,...e.map(a=>a.buffer instanceof ArrayBuffer?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a.slice())],{type:"audio/wav"})}function Ca(e,t,r){for(let n=0;n<r.length;++n)e.setUint8(t+n,r.charCodeAt(n))}var mT=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];const e=this.audio.reduce((n,s)=>n+s.length,0),t=new Float32Array(e);let r=0;for(const n of this.audio)t.set(n,r),r+=n.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),pT(e,this.sampling_rate)}async save(e){return tp(e,this.toBlob())}},gT=class extends ht{constructor(e){super(e);const t=this.config.sampling_rate,r=ar(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=mr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return or(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){ot(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;s<n.length;++s)n[s]=(n[s]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},op=class extends ht{async _call(e){ot(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const r=[1,t,e.length/t];return{input_values:new j("float32",e,r)}}},wT=class extends ht{async _call(e){ot(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},vT=class extends ht{constructor(e){super(e),this.mel_filters=ar(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=ar(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=mr(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,n){let s;const a=e.length-t;if(a>0)if(r==="rand_trunc"){const o=Math.floor(zi.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<t;i+=e.length)o.set(e.subarray(0,Math.min(e.length,t-i)),i);else if(n==="repeatpad")for(let i=e.length;i<-a;i+=e.length)o.set(e,i);e=o}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return s.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return or(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return ot(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},yT=1e-5,ip=class extends ht{constructor(e){var n;super(e),(n=this.config).mel_filters??(n.mel_filters=ar(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));const t=mr(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await or(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){ot(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;d<r;++d){const h=d*a;for(let _=0;_<a;++_){const p=n[h+_];o[_]+=p,i[_]+=p*p}}const l=r>1?r-1:1;for(let d=0;d<a;++d){const h=o[d]/r,_=(i[d]-r*h*h)/l,w=1/(Math.sqrt(_)+yT);for(let v=0;v<r;++v){const y=v*a+d;n[y]=(n[y]-h)*w}}const c=new BigInt64Array(s);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new j("int64",c,[1,s])}}},bT=class extends ip{_apply_dither(e){const t=this.config.dither??0;if(t<=0)return e;const r=new Ma(e.length);for(let n=0;n<e.length;++n)e[n]+=t*r.gauss();return e}split_audio(e){const t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,n=this.config.min_energy_window_samples??1600,s=this.config.sampling_rate,a=Math.max(1,Math.round(t*s)),o=Math.max(1,Math.round(r*s));if(e.length<=a)return[e];const i=[];let l=0;const c=e.length;for(;l<c;){if(l+a>=c){i.push(e.slice(l,c));break}const d=Math.max(l,l+a-o),h=Math.min(l+a,c);let _;h<=d?_=l+a:_=this._find_split_point_energy(e,d,h,n),_=Math.max(l+1,Math.min(_,c)),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 c=0;for(let d=0;d<n;++d){const h=e[t+l+d];c+=h*h}c=Math.sqrt(c/n),c<a&&(a=c,o=t+l)}return o}async _call(e){ot(e,"CohereAsrFeatureExtractor");const t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},lp=class extends op{},cp=class extends ht{constructor(e){super(e);const{fft_length:t,feature_size:r,min_frequency:n,max_frequency:s,sampling_rate:a,frame_length:o}=this.config,i=ar(Math.floor(1+t/2),r,n,s,a,null,"htk",!1);this.mel_filters=i,this.window=mr(o,"hann")}async _extract_fbank_features(e,t){return or(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,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,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:r=!0,padding:n=!0,pad_to_multiple_of:s=128}={}){if(ot(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(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=dt([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},up=class extends cp{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 or(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={}){ot(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,c=Math.floor(i/2),d=i+1,h=new Uint8Array(r+c+(t.pad_to_multiple_of??128));h.fill(1,c,c+r);const _=new Uint8Array(a);for(let w=0;w<a;++w)_[w]=h[w*l+d-1]?1:0;const p=s.data;for(let w=0;w<a;++w)_[w]||p.fill(0,w*o,(w+1)*o);return n.input_features_mask=new j("bool",_,[1,a]),n}},MT=class extends ht{constructor(e){super(e);const{n_fft:t,win_length:r,n_mels:n,sample_rate:s}=e.melspec_kwargs;this.mel_filters=ar(Math.floor(1+t/2),n,0,s/2,s,null,"htk");const a=mr(r,"hann");this.window=new Float64Array(t);const o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){ot(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:r,n_mels:n}=this.config.melspec_kwargs,s=Math.floor(e.length/r)+1,a=s-s%2;return{input_features:(await or(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}},xT=class extends ht{async _call(e){ot(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},dp=class extends ht{async _call(e){ot(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new j("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const r=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(const s of e.tolist()){const a=[];let o=-1;for(let i=0;i<s.length;++i){const l=at(s[i]),[c,d]=Qe(l),[h,_]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,end:_,score:c})):(a.at(-1).end=_,a.at(-1).score+=c)}n.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return n}},kT=class extends ht{constructor(e){super(e);const t=this.config.sampling_rate,r=ar(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=mr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),or(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}={}){ot(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[p,w]=a.dims,v=a.data;for(let y=0;y<w;++y){let x=0;for(let C=0;C<p;++C)x+=v[C*w+y];const k=x/p;let A=0;for(let C=0;C<p;++C)A+=(v[C*w+y]-k)**2;A/=p-1;const S=Math.sqrt(A+1e-7);for(let C=0;C<p;++C){const O=C*w+y;v[O]=(v[O]-k)/S}}}let o;if(t){const[p,w]=a.dims,v=a.data,y=p%r;if(y>0){const x=new Float32Array(w*(p+y));x.set(v),x.fill(this.config.padding_value,v.length);const k=p+y;a=new j(a.type,x,[k,w]),s&&(o=new j("int64",new BigInt64Array(k),[1,k]),o.data.fill(1n,0,p))}}const[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const h=a.view(1,Math.floor(i/c),l*c),_={input_features:h};if(s){const p=h.dims[1],w=new BigInt64Array(p);if(o){const v=o.data;for(let y=1,x=0;y<i;y+=c,++x)w[x]=v[y]}else w.fill(1n);_.attention_mask=new j("int64",w,[1,p])}return _}},TT=class extends lp{},ET=class extends ht{},AT=class extends ht{_zero_mean_unit_var_norm(e){const r=e.reduce((s,a)=>s+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){ot(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 j("float32",t,r),attention_mask:new j("int64",new BigInt64Array(t.length).fill(1n),r)}}},CT=class extends ht{constructor(e){super(e);const t=this.config.sampling_rate,r=ar(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=mr(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),or(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){ot(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;i<s;++i){const l=i*a*o,c=i*o;for(let d=0;d<a;++d){const h=l+d*o;for(let _=0;_<o;++_)n[h+_]-=r[c+_]}}}return{input_features:t}}},ST=class extends ht{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=ar(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=mr(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){const{n_fft:r,hop_length:n,mel_filters:s,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/n:(e.length-r)/n);return await or(e,this.window,r,n,{power:2,mel_filters:s,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return ot(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},PT=class extends ht{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=ar(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=mr(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await or(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){ot(e,"WhisperFeatureExtractor");let r;const n=t??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&he.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)}}},Lt=class{static async from_pretrained(e,t={}){const r=await nr(e,K_,!0,t),n=r.feature_extractor_type,s=al[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Aa}.`);return new s(r)}},FT=(ao=class extends Ee{async _call(e,t=null){const r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},T(ao,"tokenizer_class",Te),T(ao,"feature_extractor_class",Lt),ao),IT=new Set(["ja","zh"]),LT=(Ps=class extends Ee{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=IT.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}},T(Ps,"tokenizer_class",Te),T(Ps,"feature_extractor_class",Lt),T(Ps,"uses_processor_config",!0),Ps),il={},rn,hp,zr;if(pe.IS_WEB_ENV)rn=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},zr=self.createImageBitmap,hp=self.ImageData;else if(il)zr=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new Ht(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 OT={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},NT=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ht=class hr{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 hr)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(!pe.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 hr(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(pe.IS_WEB_ENV){const r=await zr(t),n=rn(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=il(await t.arrayBuffer());return await zr(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.permute(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 hr(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<this.data.length;r+=this.channels){const s=this.data[r],a=this.data[r+1],o=this.data[r+2];t[n++]=Math.round(.2989*s+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r];break;case 4:for(let r=0,n=0;r<this.data.length;r+=4)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=255;break;case 3:for(let r=0,n=0;r<this.data.length;r+=3)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2],t[n++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);const r=this.data,n=t.data,s=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(s*4);for(let o=0,i=0,l=0;o<s;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=n[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<s;++a)r[4*a+3]=n[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:n=2}={}){if(this.width===t&&this.height===r)return this;let s=OT[n]??n;const a=xf(t),o=xf(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),pe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=rn(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new hr(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(s){case"box":case"hamming":(s==="box"||s==="hamming")&&(he.warn(`Resampling method ${s} is not yet supported. Using bilinear instead.`),s="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:s});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${s} is not supported.`)}return await zr(i)}}async pad([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.max(n,0),s=Math.max(s,0),t===0&&r===0&&n===0&&s===0)return this;if(pe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+n+s,c=rn(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new hr(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:r,top:n,bottom:s});return await zr(a)}}async crop([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.min(n,this.width-1),s=Math.min(s,this.height-1),t===0&&r===0&&n===this.width-1&&s===this.height-1)return this;const a=n-t+1,o=s-r+1;if(pe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=rn(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new hr(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{const i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await zr(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;const n=(this.width-t)/2,s=(this.height-r)/2;if(pe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=rn(t,r).getContext("2d");let l=0,c=0,d=0,h=0;return n>=0?l=n:d=-n,s>=0?c=s:h=-s,i.drawImage(o,l,c,t,r,d,h,t,r),new hr(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],c=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):c=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await zr(a)}}async toBlob(t="image/png",r=1){if(!pe.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 j("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(!pe.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=rn(t.width,t.height),n=new hp(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;l<o;++l){const c=s*l;for(let d=0;d<s;++d)i[d][l]=t[c+d]}return i.map(l=>new hr(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 hr(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(pe.IS_WEB_ENV){if(pe.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=NT.get(r)??"image/png",s=await this.toBlob(n);return tp(t,s)}else if(pe.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(pe.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return il(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Ht.read.bind(Ht);function DT(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,c=Math.floor(o*t/i)*i;if(l===0&&c===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,c=Math.min(Math.floor(t/e)*i,d)):c===0&&(c=i,l=Math.min(Math.floor(e/t)*i,d)),[l,c]}function zT(e,t,r,n,s,a,o){const i=Math.floor(t/s),l=Math.floor(r/s),c=i*l,d=s*s*n,h=new Float32Array(a*d);let _=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)for(let x=0;x<s;++x){const k=(v*s+x)*r*n+y*s*n;for(let A=0;A<s;++A){const S=k+A*n;for(let C=0;C<n;++C)h[_++]=e[S+C]}}const p=new BigInt64Array(a*2).fill(-1n);let w=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)p[w++]=BigInt(y),p[w++]=BigInt(v);return{patches:new j("float32",h,[a,d]),positions:new j("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var ll=class extends gt{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);const{patch_size:t,pooling_kernel_size:r}=this,n=this.max_soft_tokens*r**2,s=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){const[_,p]=DT(i.height,i.width,t,n,r);(_!==i.height||p!==i.width)&&(i=await i.resize(p,_,{resample:this.resample}))}const l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;const{patches:c,positions:d,num_soft_tokens:h}=zT(l,i.height,i.width,i.channels,t,n,r);s.push(c),a.push(d),o.push(h)}return{pixel_values:pr(s,0),image_position_ids:pr(a,0),num_soft_tokens_per_image:o}}},fp=(oo=class extends Ee{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([nr(e,Z_,!0,t),Te.from_pretrained(e,t),ji(e,ep,!1,t)]),a={tokenizer:n};return r.image_processor&&(a.image_processor=new ll(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new up(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,()=>`
|
|
21
|
+
|
|
22
|
+
${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
|
|
23
|
+
|
|
24
|
+
`))}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(c=>c.replaceAll(this.audio_token,()=>`
|
|
25
|
+
|
|
26
|
+
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
|
|
27
|
+
|
|
28
|
+
`))}return{...this.tokenizer(e,n),...s,...a}}},T(oo,"uses_processor_config",!0),T(oo,"uses_chat_template_file",!0),oo),_p=class extends gt{constructor(e){super(),this.config=e,this.frame_processor=new ll(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??"uniform"}sample_frames(e){const t=e.length,{max_frames:r}=this;if(t<=r)return e;if(this.overflow_strategy==="truncate")return e.slice(0,r);const n=r>1?(t-1)/(r-1):0;return Array.from({length:r},(s,a)=>e[a>0&&a===r-1?t-1:Math.floor(a*n)])}async _call(e){Array.isArray(e)||(e=[e]);const t=e.map(o=>this.sample_frames(o.frames.map(i=>i.image))),{pixel_values:r,image_position_ids:n,num_soft_tokens_per_image:s}=await this.frame_processor(t.flat());let a=0;return{pixel_values_videos:r,video_position_ids:n,num_frames_per_video:t.map(o=>o.length),num_soft_tokens_per_video:t.map(o=>s[(a+=o.length)-1])}}};function cl(e,t){return Array.isArray(e)?e.every(r=>Array.isArray(r))?e:t?[e]:e.map(r=>[r]):[[e]]}function BT(e,t,r){let n=0;if(e=e.map(s=>s.replaceAll(t,()=>r[n++]??"")),n!==r.length)throw new Error(`Found ${n} ${t} tokens in the text, but ${r.length} inputs were passed.`);return e}var RT=class extends fp{constructor(e,t,r){super(e,t,r),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new _p(e.video_processor)}async _call(e,t=null,r=null,n=null,s={}){var S;const a=[[this.image_token,t&&cl(t,!0)],[this.video_token,n&&cl(n,!1)],[this.audio_token,r&&cl(r,!1)]];if(e==null){const C=a.filter(([,M])=>M),O=(S=C[0])==null?void 0:S[1].length;if(C.some(([,M])=>M.length!==O))throw new Error("Received a different number of samples per modality.");e=Array.from({length:O},(M,V)=>C.flatMap(([G,U])=>Array(U[V].length).fill(G)).join(" "))}else typeof e=="string"&&(e=[e]);const[o,i,l]=a.map(([,C])=>C==null?void 0:C.flat()),c=o&&await this.image_processor(o),d=i&&await this.video_processor(i),h=l&&await this._process_audio(l),{image_token:_,video_token:p,audio_token:w,boi_token:v,eoi_token:y,boa_token:x,eoa_token:k}=this,A={[_]:c==null?void 0:c.num_soft_tokens_per_image.map(C=>v+_.repeat(C)+y),[p]:d==null?void 0:d.num_soft_tokens_per_video.map((C,O)=>(v+p.repeat(C)+y).repeat(d.num_frames_per_video[O])),[w]:h==null?void 0:h.num_soft_tokens_per_audio.map(C=>x+w.repeat(C)+k)};for(const[C,O]of Object.entries(A))e=BT(e,C,O??[]);return{...this.tokenizer(e,{padding:!0,...s}),...c,...d,...h}}async _process_audio(e){const t=[];for(const o of e)t.push(await this.feature_extractor(o));const r=Math.max(...t.map(o=>o.input_features.dims[1])),n=t[0].input_features.dims[2],s=new Float32Array(e.length*r*n),a=new Uint8Array(e.length*r);return t.forEach((o,i)=>{s.set(o.input_features.data,i*r*n),a.set(o.input_features_mask.data,i*r)}),{input_features:new j("float32",s,[e.length,r,n]),input_features_mask:new j("bool",a,[e.length,r]),num_soft_tokens_per_audio:t.map(({input_features_mask:{data:o}})=>{let i=0;for(let l=0;l<o.length;l+=4)i+=Number(o[l]);return i})}}};function pp(e,t,r=0,n=null){const s=e/t;let a=B1(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),a<r&&(a=Math.ceil(s)*t),a}function mp([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function gp([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function Sa(e,t=.5,r=null,n=!1){const s=e.logits,a=e.pred_boxes,[o,i,l]=s.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let d=0;d<o;++d){let h=r!==null?r[d]:null,_={boxes:[],classes:[],scores:[]},p=s[d],w=a[d];for(let v=0;v<i;++v){let y=p[v],x=[],k;if(n){k=y.sigmoid().data;for(let A=0;A<k.length;++A)k[A]>t&&x.push(A)}else{let A=Qe(y.data)[1];if(A===l-1||(k=at(y.data),k[A]<t))continue;x.push(A)}for(const A of x){let S=w[v].data;S=gp(S),h!==null&&(S=S.map((C,O)=>C*h[(O+1)%2])),_.boxes.push(S),_.classes.push(A),_.scores.push(k[A])}}c.push(_)}return c}function wp(e,t=null){const r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let a=0;a<n;++a){const o=t!==null?t[a]:null;let i=r[a];o!==null&&(i=G_(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new j("int32",new Int32Array(l*c),[l,c]),h=i[0].data,_=d.data;for(let v=1;v<i.dims[0];++v){const y=i[v].data;for(let x=0;x<y.length;++x)y[x]>h[x]&&(h[x]=y[x],_[x]=v)}const p=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const y=_[v];p[y]=y}const w=p.filter(v=>v!==void 0);s.push({segmentation:d,labels:w})}return s}function $T(e,t,r,n){const s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=Qe(l.data)[1];if(d===n)continue;const _=at(l.data)[d];_>r&&(s.push(c),a.push(_),o.push(d))}return[s,a,o]}function GT(e,t,r,n=.5,s=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let d=0;d<e.length;++d)e[d]===r&&(a.push(d),++o),l[d]>=n&&++i;let c=o>0&&i>0;return c&&(c=o/i>s),[c,a]}function VT(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,c=new j("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=G_(e[v],o,"bilinear",!1);const h=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let y=t[v];const x=e[v].data;for(let k=0;k<x.length;++k)x[k]*=y,x[k]>_[k]&&(h[k]=v,_[k]=x[k])}let p=0;const w=c.data;for(let v=0;v<r.length;++v){const y=r[v],[x,k]=GT(h,e,v,n,s);if(x){++p;for(const A of k)w[A]=p;d.push({id:p,label_id:y,score:t[v]})}}return[c,d]}function ul(e,t,r=28,n=3136,s=784*1280,a=1){if(e<r||t<r){const l=Math.max(r/e,r/t);e=Math.round(e*l),t=Math.round(t*l)}if(Math.max(e,t)/Math.min(e,t)>200)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*i<n){const l=Math.sqrt(n/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function vp(e,t=.5,r=.5,n=.8,s=null,a=null){s===null&&(he.warn("`label_ids_to_fuse` unset. No instance will be fused."),s=new Set);const o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,h]=o.dims;if(h-=1,a!==null&&a.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let p=0;p<c;++p){let w=a!==null?a[p]:null,v=o[p],y=l[p],[x,k,A]=$T(v,y,t,h);if(A.length===0){let[O,M]=w??y.dims.slice(-2),V=new j("int32",new Int32Array(O*M).fill(-1),[O,M]);_.push({segmentation:V,segments_info:[]});continue}let[S,C]=VT(x,k,A,r,n,s,w);_.push({segmentation:S,segments_info:C})}return _}function yp(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var fe=class extends gt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){const n=e.height,s=e.width,a=t.height,o=t.width;let i=Math.min(n,a),l=Math.min(s,o);return i===n&&l===s?e:(n>s?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=Wi(r.data)[0],a=Qe(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,c=0,d=0;const h=r.data;for(let _=0;_<r.height;++_){const p=_*r.width;for(let w=0;w<r.width;++w)(h[p+w]-n)/a<o&&(i=Math.min(i,w),l=Math.min(l,_),c=Math.max(c,w),d=Math.max(d,_))}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){const[o,i,l]=t;let c,d;if(typeof r=="number"?(c=r,d=r):r==="square"?c=d=Math.max(o,i):(c=r.width,d=r.height),c!==i||d!==o){const h=new Float32Array(c*d*l);if(Array.isArray(a))for(let w=0;w<h.length;++w)h[w]=a[w%l];else a!==0&&h.fill(a);const[_,p]=s?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+p)*c,y=w*i;for(let x=0;x<i;++x){const k=(v+x+_)*l,A=(y+x)*l;for(let S=0;S<l;++S)h[k+S]=e[A+S]}}if(n==="symmetric"){if(s)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const w=o-1,v=i-1;for(let y=0;y<d;++y){const x=y*c,k=ca(y,w)*i;for(let A=0;A<c;++A){if(y<o&&A<i)continue;const S=(x+A)*l,C=(k+ca(A,v))*l;for(let O=0;O<l;++O)h[S+O]=e[C+O]}}}e=h,t=[d,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[r,n]=e.size;let s,a;if(this.do_thumbnail){const{height:o,width:i}=t;s=Math.min(o,i)}else Number.isInteger(t)?(s=t,a=this.config.max_size??s):t!==void 0&&(s=t.shortest_edge,a=t.longest_edge);if(s!==void 0||a!==void 0){const o=s===void 0?1:Math.max(s/r,s/n),i=r*o,l=n*o,c=a===void 0?1:Math.min(a/i,a/l);let d=Math.floor(Number((i*c).toFixed(2))),h=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=mp([d,h],this.size_divisibility)),[d,h]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/n,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=pp(l*n,this.config.ensure_multiple_of),o=pp(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return mp([r,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:n=null,do_convert_grayscale:s=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(n??this.do_convert_rgb?e=e.rgb():s&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,p;Number.isInteger(this.crop_size)?(_=this.crop_size,p=this.crop_size):(_=this.crop_size.width,p=this.crop_size.height),e=await e.center_crop(_,p)}const l=[e.height,e.width];let c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let p=this.image_std;if(Array.isArray(this.image_std)||(p=new Array(e.channels).fill(p)),_.length!==e.channels||p.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${p.length}) must match the number of channels in the image (${e.channels}).`);for(let w=0;w<c.length;w+=e.channels)for(let v=0;v<e.channels;++v)c[w+v]=(c[w+v]-_[v])/p[v]}if(r??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,p=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:_,height:p})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){const p=c[_];c[_]=c[_+2],c[_+2]=p}}const h=new j("float32",c,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:h}}async _call(e,...t){Array.isArray(e)||(e=[e]);const r=await Promise.all(e.map(s=>this.preprocess(s)));return{pixel_values:pr(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 nr(e,_s,!0,t);return new this(r)}},Pa={};as(Pa,{BeitFeatureExtractor:()=>UT,BitImageProcessor:()=>jT,CHMv2ImageProcessor:()=>qT,CLIPFeatureExtractor:()=>HT,CLIPImageProcessor:()=>bp,ChineseCLIPFeatureExtractor:()=>WT,ConvNextFeatureExtractor:()=>QT,ConvNextImageProcessor:()=>Mp,DINOv3ViTImageProcessor:()=>JT,DPTFeatureExtractor:()=>ZT,DPTImageProcessor:()=>Tp,DeiTFeatureExtractor:()=>XT,DeiTImageProcessor:()=>xp,DetrFeatureExtractor:()=>YT,DetrImageProcessor:()=>kp,DonutFeatureExtractor:()=>KT,DonutImageProcessor:()=>dl,EfficientNetImageProcessor:()=>eE,GLPNFeatureExtractor:()=>nE,Gemma3ImageProcessor:()=>tE,Gemma4ImageProcessor:()=>ll,Glm46VImageProcessor:()=>rE,GroundingDinoImageProcessor:()=>sE,Idefics3ImageProcessor:()=>Ap,ImageFeatureExtractor:()=>fe,ImageProcessor:()=>fe,JinaCLIPImageProcessor:()=>oE,Lfm2VlImageProcessor:()=>dE,LlavaOnevisionImageProcessor:()=>hE,Mask2FormerImageProcessor:()=>_E,MaskFormerFeatureExtractor:()=>fE,MaskFormerImageProcessor:()=>hl,MobileNetV1FeatureExtractor:()=>pE,MobileNetV1ImageProcessor:()=>Sp,MobileNetV2FeatureExtractor:()=>mE,MobileNetV2ImageProcessor:()=>Pp,MobileNetV3FeatureExtractor:()=>gE,MobileNetV3ImageProcessor:()=>Fp,MobileNetV4FeatureExtractor:()=>wE,MobileNetV4ImageProcessor:()=>Ip,MobileViTFeatureExtractor:()=>vE,MobileViTImageProcessor:()=>Lp,NougatImageProcessor:()=>yE,OwlViTFeatureExtractor:()=>bE,OwlViTImageProcessor:()=>fl,Owlv2ImageProcessor:()=>ME,Phi3VImageProcessor:()=>kE,PixtralImageProcessor:()=>TE,PvtImageProcessor:()=>EE,Qwen2VLImageProcessor:()=>Ep,RTDetrImageProcessor:()=>AE,Sam2ImageProcessor:()=>ml,Sam3ImageProcessor:()=>ml,SamImageProcessor:()=>ml,SapiensFeatureExtractor:()=>CE,SapiensImageProcessor:()=>Op,SegformerFeatureExtractor:()=>SE,SegformerImageProcessor:()=>Np,SiglipImageProcessor:()=>PE,SmolVLMImageProcessor:()=>Ap,Swin2SRImageProcessor:()=>FE,VLMImageProcessor:()=>aE,ViTFeatureExtractor:()=>IE,ViTImageProcessor:()=>Dp,VitMatteImageProcessor:()=>LE,VitPoseImageProcessor:()=>OE,YolosFeatureExtractor:()=>NE,YolosImageProcessor:()=>zp});var UT=class extends fe{},jT=class extends fe{},WT=class extends fe{},qT=class extends fe{},bp=class extends fe{},HT=class extends bp{},Mp=class extends fe{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var r;const t=(r=this.size)==null?void 0:r.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const n=Math.floor(t/this.crop_pct),[s,a]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(s,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},QT=class extends Mp{},xp=class extends fe{},XT=class extends xp{},kp=class extends fe{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=dt(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Sa(...e)}post_process_panoptic_segmentation(...e){return vp(...e)}post_process_instance_segmentation(...e){return yp(...e)}},YT=class extends kp{},JT=class extends fe{},dl=class extends fe{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 c=i.map((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...n})}},KT=class extends dl{},Tp=class extends fe{},ZT=class extends Tp{},eE=class extends fe{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))}},tE=class extends fe{},Ep=class extends fe{constructor(e){var t,r;super(e),this.min_pixels=e.min_pixels??((t=e.size)==null?void 0:t.shortest_edge),this.max_pixels=e.max_pixels??((r=e.size)==null?void 0:r.longest_edge),this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size;return ul(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:n,reshaped_input_sizes:s}=await super._call(e,...t);let a=r;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=Re(Array.from({length:o},()=>a),0));const c=a.dims[0]/o,d=a.dims[1],h=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),p=a.view(c,o,d,Math.floor(h/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*h*_,d*o*l*l),w=new j("int64",[c,h,_],[1,3]);return{pixel_values:p,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},rE=class extends Ep{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return ul(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}},nE=class extends fe{},sE=class extends fe{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=xt([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},Ap=class extends fe{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 y of n){let x=await Promise.all(y.map(S=>this.preprocess(S)));i.push(...x.map(S=>S.original_size)),l.push(...x.map(S=>S.reshaped_input_size)),x.forEach(S=>S.pixel_values.unsqueeze_(0));const{longest_edge:k}=this.max_image_size;let A;if(t??this.do_image_splitting){let S=new Array(x.length),C=new Array(x.length);A=await Promise.all(x.map(async(O,M)=>{const V=this.get_resize_for_vision_encoder(O.pixel_values,k),G=await qt(O.pixel_values,{size:[V.height,V.width]}),{frames:U,num_splits_h:J,num_splits_w:Q}=await this.split_image(G,this.max_image_size);return S[M]=J,C[M]=Q,Re(U,0)})),a.push(S),o.push(C)}else{const S=[k,k];A=await Promise.all(x.map(C=>qt(C.pixel_values,{size:S}))),a.push(new Array(x.length).fill(0)),o.push(new Array(x.length).fill(0))}s.push(Re(A,0))}const c=s.length,[d,h,_,p]=s[0].dims;let w,v;if(c===1)w=s[0].unsqueeze_(0),v=dt([c,d,_,p],!0);else{const y=Math.max(...s.map(A=>A.dims.at(0)));v=dt([c,y,_,p],!0);const x=v.data,k=y*_*p;for(let A=0;A<c;++A){const S=s[A].dims[0];if(S<y){s[A]=Re([s[A],dt([y-S,h,_,p],0)],0);const C=A*k+S*_*p,O=(A+1)*k;x.fill(!1,C,O)}}w=pr(s,0)}return{pixel_values:w,pixel_attention_mask:v,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){const r=t,n=t,s=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>r||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);const c=Math.ceil(a/i),d=Math.ceil(o/l);for(let p=0;p<i;++p)for(let w=0;w<l;++w){let v,y,x,k;p===i-1?(y=a-c,k=a):(y=p*c,k=(p+1)*c),w===l-1?(v=o-d,x=o):(v=w*d,x=(w+1)*d);const C=await V_(e,[y,v],[k,x],[2,3]);s.push(C)}const h=r,_=n;(a!==h||o!==_)&&(e=await qt(e,{size:[h,_]}))}return s.push(e),{frames:s,num_splits_h:i,num_splits_w:l}}},aE=class extends fe{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},oE=class extends fe{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 Cp(e,t){return Math.round(e/t)*t}function iE(e,t,r,n,s){let a=1/0,o=[1,1];const i=r*n;for(const l of t){const c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*s*s*l[0]*l[1]&&(o=l)}return o}function lE(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 cE(e,t){const[r,n,s,a]=e.dims,o=Math.floor(s/t),i=Math.floor(a/t),l=t*t*n,c=e.data,d=new Float32Array(r*o*i*l),h=s*a;for(let _=0;_<r;++_){const p=_*n*h,w=_*o*i*l;for(let v=0;v<o;++v)for(let y=0;y<i;++y){let x=w+(v*i+y)*l;for(let k=0;k<t;++k){const A=(v*t+k)*a+y*t;for(let S=0;S<t;++S){const C=A+S;for(let O=0;O<n;++O)d[x++]=c[p+O*h+C]}}}}return new j("float32",d,[r,o*i,l])}function uE(e,t){const[,r,n]=e.dims,s=new BigInt64Array(t);s.fill(1n,0,r);let a=e;if(r<t){const o=new Float32Array(t*n);o.set(e.data),a=new j("float32",o,[1,t,n])}return{padded:a,mask:new j("int64",s,[t])}}var dE=class extends fe{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;const t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r)}_is_image_too_large(e,t){const r=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,Cp(e,r)),s=Math.max(this.encoder_patch_size,Cp(t,r));return n*s>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=lE(this.min_tiles,this.max_tiles),[n,s]=iE(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 h=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(const{pixel_values:_}of h){const[,p,w]=_.dims,v=_.unsqueeze_(0),y=this.encoder_patch_size*this.downsample_factor,x=y**2,[k,A]=ul(Math.max(y,p),Math.max(y,w),y,this.min_image_tokens*x,this.max_image_tokens*x).map(G=>Math.max(y,G));let S,C=1,O=1;const M=this._is_image_too_large(p,w),V=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(M&&V){const{grid_width:G,grid_height:U,target_width:J,target_height:Q}=this._get_grid_layout(p,w);C=U,O=G;const B=await qt(v,{size:[Q,J]});S=[];for(let L=0;L<U;++L)for(let ee=0;ee<G;++ee){const H=L*this.tile_size,ne=ee*this.tile_size;S.push(B.slice(null,null,[H,H+this.tile_size],[ne,ne+this.tile_size]))}this.use_thumbnail&&G*U!==1&&S.push(await qt(v,{size:[A,k]}))}else S=[await qt(v,{size:[A,k]})];for(const G of S){const[,,U,J]=G.dims,Q=cE(G,this.encoder_patch_size),{padded:B,mask:L}=uE(Q,this.max_num_patches);n.push(B),s.push(L),a.push([Math.floor(U/this.encoder_patch_size),Math.floor(J/this.encoder_patch_size)])}o.push(C),i.push(O),l.push([A,k])}}const c={pixel_values:Re(n,0),pixel_attention_mask:pr(s,0),spatial_shapes:new j("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(c.image_rows=o,c.image_cols=i,c.image_sizes=l),c}},hE=class extends fe{},hl=class extends fe{post_process_panoptic_segmentation(...e){return vp(...e)}post_process_instance_segmentation(...e){return yp(...e)}},fE=class extends hl{},_E=class extends hl{},Sp=class extends fe{},pE=class extends Sp{},Pp=class extends fe{},mE=class extends Pp{},Fp=class extends fe{},gE=class extends Fp{},Ip=class extends fe{},wE=class extends Ip{},Lp=class extends fe{},vE=class extends Lp{},yE=class extends dl{},fl=class extends fe{post_process_object_detection(...e){return Sa(...e)}},bE=class extends fl{},ME=class extends fl{},Ct=336,xE=[2,3],{ceil:_l,floor:xn,sqrt:pl}=Math,kE=class extends fe{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){const{num_img_tokens:r}=this.config;return xn((xn(t/Ct)*xn(e/Ct)+1)*r+1+(xn(t/Ct)+1)*pl(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[n,s]=e.size;let a=n/s,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;const i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,n={}){const[s,a]=t,o=Ct*_l(s/Ct),i=Ct*_l(a/Ct),l=[1,1,1].map((c,d)=>(c-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??(t=this.config.num_crops),t<4||pl(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(h=>this.preprocess(h))),s=n.map(h=>h.original_size),a=n.map(h=>h.reshaped_input_size),o=[];for(const{pixel_values:h}of n){h.unsqueeze_(0);const[_,p]=h.dims.slice(-2),w=await qt(h,{size:[Ct,Ct],mode:"bicubic"});if(t>0){const v=[],y=pl(t),x=xn(p/y),k=xn(_/y);for(let S=0;S<y;++S)for(let C=0;C<y;++C){let O,M,V,G;S===y-1?(M=_-k,G=_):(M=S*k,G=(S+1)*k),C===y-1?(O=p-x,V=p):(O=C*x,V=(C+1)*x);const Q=await V_(h,[M,O],[G,V],xE);v.push(Q)}const A=await qt(Re(v,0),{size:[Ct,Ct],mode:"bicubic"});o.push(Re([w,A],0))}else o.push(w)}const i=pr(o,0),l=a.map(h=>h.map(_=>Ct*_l(_/Ct))),c=new j("int64",l.flat(),[r,2]),d=l.map(([h,_])=>this.calc_num_image_tokens_from_image_size(_,h));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},TE=class extends fe{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:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");const d=l*c,h=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[h*d,_*d]}},EE=class extends fe{},AE=class extends fe{post_process_object_detection(...e){return Sa(...e)}},ml=class extends fe{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=kf(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;a<e.length;++a){const[o,i]=t[a],[l,c]=r[a],d=[c/i,l/o];for(let h=0;h<e[a].length;++h)for(let _=0;_<e[a][h].length;++_)for(let p=0;p<e[a][h][_].length;++p)e[a][h][_][p]*=d[p%2]}return new j("float32",Float32Array.from(e.flat(1/0)),s)}add_input_labels(e,t){let r=kf(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((n,s)=>n!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j("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;l<t.length;++l){const c=t[l],d=r[l];let h=await qt(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await qt(h,{mode:"bilinear",size:c}),s){const _=h.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)_[w]>n&&(p[w]=1);h=new j("bool",p,h.dims)}o.push(h)}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}={}){}},Op=class extends fe{post_process_semantic_segmentation(...e){return wp(...e)}},CE=class extends Op{},Np=class extends fe{post_process_semantic_segmentation(...e){return wp(...e)}},SE=class extends Np{},PE=class extends fe{},FE=class extends fe{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})}},Dp=class extends fe{},IE=class extends Dp{},LE=class extends fe{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:pr(r.map((a,o)=>Re([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)}}},OE=class extends fe{post_process_pose_estimation(e,t,{threshold:r=null}={}){const n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let c=0;c<s;++c){const d=n[c],h=t[c],_=[];for(let p=0;p<h.length;++p){const w=h[p],v=[],y=[],x=[],k=w.at(-2)/i,A=w.at(-1)/o;for(let S=0;S<d.length;++S){let[C,O]=[0,0],M=0,V=-1/0;const G=d[S];for(let J=0;J<G.length;++J){const Q=G[J];for(let B=0;B<Q.length;++B){const L=Q[B];M+=L,V=Math.max(V,L),C+=(B+.5)*L,O+=J*L}}if(r!=null&&V<r)continue;const U=[k*C/M,A*O/M];v.push(U),x.push(S),y.push(V)}_.push({bbox:w,scores:y,labels:x,keypoints:v})}l.push(_)}return l}},zp=class extends fe{post_process_object_detection(...e){return Sa(...e)}},NE=class extends zp{},ft=class{static async from_pretrained(e,t={}){const r=await nr(e,_s,!0,t),n=r.image_processor_type??r.feature_extractor_type;let s=Pa[n==null?void 0:n.replace(/Fast$/,"")];return s||(n!==void 0&&he.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Aa}.`),s=fe),new s(r)}},DE=(io=class extends Ee{constructor(e,t,r){super(e,t,r);const{tasks_answer_post_processing_type:n,task_prompts_without_inputs:s,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(s??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/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("<s>","").replaceAll("</s>","");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[c,d,...h]of o)i.push(d?d.trim():i.at(-1)??""),l.push(h.map((_,p)=>(Number(_)+.5)/this.size_per_bin*r[p%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}}},T(io,"tokenizer_class",Te),T(io,"image_processor_class",ft),io),zE=(Wn=class extends Ee{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=`
|
|
29
|
+
|
|
30
|
+
${n}${o}${a}
|
|
31
|
+
|
|
32
|
+
`}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}}},T(Wn,"tokenizer_class",Te),T(Wn,"image_processor_class",ft),T(Wn,"uses_processor_config",!0),T(Wn,"uses_chat_template_file",!0),Wn),BE=(sn=class extends Ee{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:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
33
|
+
|
|
34
|
+
${s}${h}${o}
|
|
35
|
+
|
|
36
|
+
`,this.image_token_id=i,this.boi_token=l,this.image_token=c;const _=c.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
37
|
+
|
|
38
|
+
${l}${_}${d}
|
|
39
|
+
|
|
40
|
+
`}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}}},T(sn,"image_processor_class",ft),T(sn,"feature_extractor_class",Lt),T(sn,"tokenizer_class",Te),T(sn,"uses_processor_config",!0),T(sn,"uses_chat_template_file",!0),sn),gl=(Fs=class extends Ee{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,c=s.tolist();e=e.map(d=>{for(;d.includes(l);){const h=Number(c[i++].reduce((_,p)=>_*p,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(h/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...n}}},T(Fs,"image_processor_class",ft),T(Fs,"tokenizer_class",Te),T(Fs,"image_token","<|image_pad|>"),Fs),RE=(Gu=class extends gl{},T(Gu,"image_token","<|image|>"),Gu),$E=(Is=class extends Ee{_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 j("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}}},T(Is,"tokenizer_class",Te),T(Is,"feature_extractor_class",Lt),T(Is,"uses_processor_config",!0),Is);function GE(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 VE=(lo=class extends Ee{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),c=a.sigmoid(),d=c.max(-1).tolist(),h=o.tolist().map(p=>p.map(w=>gp(w))),_=[];for(let p=0;p<i;++p){const w=s!==null?s[p]:null;w!==null&&(h[p]=h[p].map(A=>A.map((S,C)=>S*w[(C+1)%2])));const v=d[p],y=[],x=[],k=[];for(let A=0;A<l;++A){const S=v[A];if(S<=r)continue;const C=h[p][A],O=c[p][A];y.push(S),k.push(C);const M=GE(O.gt(n),t[p]);x.push(M)}_.push({scores:y,boxes:k,labels:this.batch_decode(x)})}return _}},T(lo,"tokenizer_class",Te),T(lo,"image_processor_class",ft),lo);function UE(e,t,r,n,s,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=n+`<row_${i+1}_col_${l+1}>`+s.repeat(e);o+=`
|
|
41
|
+
`}return o+=`
|
|
42
|
+
${n}${a}`+s.repeat(e)+`${n}`,o}function jE(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function WE(e,t,r,n,s,a){return e===0&&t===0?jE(r,n,s,a):UE(r,e,t,n,s,a)}var Bp=(Ls=class extends Ee{constructor(){super(...arguments);T(this,"fake_image_token","<fake_token_around_image>");T(this,"image_token","<image>");T(this,"global_img_token","<global-img>")}async _call(t,r=null,n={}){n.return_row_col_info??(n.return_row_col_info=!0);let s;r&&(s=await this.image_processor(r,n)),Array.isArray(t)||(t=[t]);const a=s.rows??[new Array(t.length).fill(0)],o=s.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let h=0;h<t.length;++h){const _=t[h],p=a[h],w=o[h];l.push(jb(_,this.image_token));const v=p.map((k,A)=>WE(k,w[A],i,this.fake_image_token,this.image_token,this.global_img_token)),y=_.split(this.image_token);if(y.length===0)throw new Error("The image token should be present in the text.");let x=y[0];for(let k=0;k<v.length;++k)x+=v[k]+y[k+1];c.push(x)}return{...this.tokenizer(c),...s}}},T(Ls,"image_processor_class",ft),T(Ls,"tokenizer_class",Te),T(Ls,"uses_processor_config",!0),Ls),qE=(Os=class extends Ee{constructor(e,t,r){super(e,t,r),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(v=>v.images).flatMap(v=>v.images).map(v=>Ht.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,c,d]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let h=a(o[0]),_=new Array(h.length).fill(!1);for(let v=1;v<o.length;++v){const y=new Array(this.num_image_tokens).fill(l),x=a(o[v]);h=er(h,[c],y,[d],x);const k=new Array(this.num_image_tokens).fill(!0);_=er(_,[!1],k,[!1],new Array(x.length).fill(!1))}const p=[1,h.length],w={input_ids:new j("int64",h,p),attention_mask:new j("int64",new Array(h.length).fill(1),p),images_seq_mask:new j("bool",_,p),images_emb_mask:new j("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},T(Os,"image_processor_class",ft),T(Os,"tokenizer_class",Te),T(Os,"uses_processor_config",!0),Os),HE=(co=class extends Ee{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}}},T(co,"tokenizer_class",Te),T(co,"image_processor_class",ft),co),QE=(uo=class extends Ee{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??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:h=!0}=this.image_processor.config,_=k=>Math.ceil(Math.floor(k/d)/c),p=_(l)**2,w=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",y=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let x=0;t=t.map(k=>{const A=k.split(i);return A[0]+A.slice(1).map(S=>{const C=x++,[O,M]=a[C],V=n[C],G=s[C],U=_(O)*_(M);let J=w;if(V>1||G>1){const Q=i.repeat(p);for(let B=0;B<V;++B)for(let L=0;L<G;++L)J+=`<|img_row_${B+1}_col_${L+1}|>`+Q;h&&(J+=y+i.repeat(U))}else J+=i.repeat(U);return J+v+S}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},T(uo,"tokenizer_class",Te),T(uo,"image_processor_class",ft),uo),XE=(Ns=class extends Ee{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:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let h=0;h<t.length;++h)t[h]=t[h].replace(i,i.repeat(d))}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},T(Ns,"tokenizer_class",Te),T(Ns,"image_processor_class",ft),T(Ns,"uses_processor_config",!0),Ns),Rp={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},YE=(ho=class extends Ee{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!Rp.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,n]=Rp[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let h=0;h<a;++h){const _=c[h],p=[],w=[];for(let y=1;y<o;++y){const[x,k]=Qe(at(_[y]));if(w.push(x),k==n)break;p.push(k)}const v=w.length>0?w.reduce((y,x)=>y*x,1):0;l.push(p),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"),c=[],d=[];for(let h=0;h<n.length;++h){const[_,p]=Qe([s[h],o[h],l[h]]);c.push([n[h],a[h],i[h]][p]),d.push(_)}return{generated_text:c,scores:d,char_preds:n,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),r=await Te.from_pretrained("Xenova/gpt2"),n=await Te.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:n},t}async _call(e,t=null){const r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},T(ho,"tokenizer_class",Te),T(ho,"image_processor_class",ft),ho),JE=(fo=class extends Ee{async _call(e){return await this.feature_extractor(e)}},T(fo,"tokenizer_class",Te),T(fo,"feature_extractor_class",Lt),fo),KE=(_o=class extends Ee{},T(_o,"tokenizer_class",Te),T(_o,"image_processor_class",ft),_o),kn="<image>";function ZE(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
|
|
43
|
+
`}var e2=(Ds=class extends Ee{async _call(e,t=null,r={}){t||(he.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(kn))?a=t.map(l=>{const c=l.replaceAll(kn,kn.repeat(s)),d=c.lastIndexOf(kn),h=d===-1?0:d+kn.length;return c.slice(0,h)+n+c.slice(h)+`
|
|
44
|
+
`}):(he.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 `<image>` 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=>ZE(l,n,s,kn,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},T(Ds,"tokenizer_class",Te),T(Ds,"image_processor_class",ft),T(Ds,"uses_processor_config",!1),Ds),$p="<|image|>",t2=/<\|image_\d+\|>/g,r2=(po=class extends Ee{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,h)=>d.split(t2).join($p.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:n});const c=this.tokenizer._tokenizer.token_to_id($p);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},T(po,"image_processor_class",ft),T(po,"tokenizer_class",Te),po),n2=(zs=class extends Ee{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:c,patch_size:d,spatial_merge_size:h}=this.config,_=d*h,p=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v<t.length;++v){const y=i.repeat(w),x=y+l,k=y+c,A=x.repeat(p-1)+k;t[v]=t[v].replace(i,A)}}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},T(zs,"tokenizer_class",Te),T(zs,"image_processor_class",ft),T(zs,"uses_processor_config",!0),zs),s2=(Vu=class extends Ee{async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},T(Vu,"feature_extractor_class",dp),Vu),Gp=class extends gl{},a2=class extends Gp{},Vp=(Uu=class extends Ee{async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},T(Uu,"image_processor_class",ft),Uu),Up=class extends Vp{},o2=class extends Up{},i2=(mo=class extends Ee{async _call(e){return await this.feature_extractor(e)}},T(mo,"tokenizer_class",Te),T(mo,"feature_extractor_class",Lt),mo),l2=(Bs=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){const a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);n.audio_token_len=[l],n.audio_values=o;const c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},T(Bs,"tokenizer_class",Te),T(Bs,"feature_extractor_class",Lt),T(Bs,"uses_processor_config",!0),Bs),Fa="[AUDIO]",c2="[BEGIN_AUDIO]",u2=375;function d2(e,t){const r=[];for(let n=0;n<e.length;n+=t)r.push(e.subarray(n,Math.min(n+t,e.length)));return r}var h2=(Rs=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const n={};if(t){if(!e.includes(Fa))throw new Error(`The input text does not contain the audio token ${Fa}.`);Array.isArray(t)||(t=[t]);const a=e.split(Fa),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(p=>d2(p,i)),c=l.map(p=>p.length),d=l.flat(),h=(await Promise.all(d.map(p=>this.feature_extractor(p,r)))).map(p=>p.input_features);n.audio_values=h.length>1?Re(h,0):h[0];let _=a[0];for(let p=0;p<c.length;++p){_+=c2;for(let w=0;w<c[p];++w)_+=Fa.repeat(u2);_+=a[p+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},T(Rs,"tokenizer_class",Te),T(Rs,"feature_extractor_class",Lt),T(Rs,"uses_processor_config",!1),Rs),jp=32,wl=6,Ia=8,f2=10,_2=32,p2=($s=class extends Ee{get num_mel_frames_first_audio_chunk(){return(wl+1)*Ia}get num_samples_first_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return Ia*e+t}get num_right_pad_tokens(){return wl+1+f2}get audio_length_per_tok(){return Ia}get raw_audio_length_per_tok(){return Ia*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(ot(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){const n=jp*this.raw_audio_length_per_tok,s=new Float32Array(n+e.length);s.set(e,n);const a=await this.feature_extractor(s,{center:!0}),i=1+(jp+wl),l=new BigInt64Array(i).fill(BigInt(_2));return l[0]=1n,{input_ids:new j("int64",l,[1,i]),...a}}else{const n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,s=new Float32Array(e.length+n);return s.set(e),await this.feature_extractor(s,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},T($s,"tokenizer_class",Te),T($s,"feature_extractor_class",Lt),T($s,"uses_processor_config",!1),$s),m2=(go=class extends Ee{async _call(e){return await this.feature_extractor(e)}},T(go,"tokenizer_class",Te),T(go,"feature_extractor_class",Lt),go),g2=(wo=class extends Ee{async _call(e){return await this.feature_extractor(e)}},T(wo,"tokenizer_class",Te),T(wo,"feature_extractor_class",Lt),wo),w2=(vo=class extends Ee{async _call(e){return await this.feature_extractor(e)}},T(vo,"tokenizer_class",Te),T(vo,"feature_extractor_class",Lt),vo),v2=class{static async from_pretrained(e,t={}){const r=await nr(e,_s,!0,t),{image_processor_type:n,feature_extractor_type:s,processor_class:a}=r;if(a&&sl[a])return sl[a].from_pretrained(e,t);if(!n&&!s)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(n){const l=Pa[n.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){const l=Pa[s];if(l)o.image_processor=new l(r);else{const c=al[s];if(!c)throw new Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new c(r)}}const i={};return new Ee(i,o,null)}};async function y2(e,t){return await nr(e,"config.json",!0,t)}function Tn(e){const t={};let r={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=Tn(e.text_config);break;case"moondream1":r=Tn(e.phi_config);break;case"musicgen":r=Tn(e.decoder);break;case"multi_modality":r=Tn(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"deepseek_v4":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv=e.model_type==="deepseek_v4"?"head_dim":"qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"zaya":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"hrm_text":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";const{num_hidden_layers:s,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:s,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":const i=Tn(e.decoder),l="num_decoder_layers"in i,c=rt(e,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=i.num_decoder_layers,c.num_decoder_heads=i.num_decoder_heads,c.decoder_hidden_size=i.decoder_hidden_size,c.num_encoder_layers=i.num_encoder_layers,c.num_encoder_heads=i.num_encoder_heads,c.encoder_hidden_size=i.encoder_hidden_size):(c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size),c}const n={...r,...rt(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function La(e,t){e instanceof vl||(e=new vl(e));const r=(t==null?void 0:t.prefix)??"past_key_values",n=r==="present"?"present":"past",s=new Set;if(["lfm2","lfm2_moe"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")s.add(`${r}.${o}.key`),s.add(`${r}.${o}.value`);else if(a[o]==="conv")s.add(`${n}_conv.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return s}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){const a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??(o==null?void 0:o.length);for(let l=0;l<i;++l)(!o||o[l]==="mamba")&&(s.add(`${n}_conv.${l}`),s.add(`${n}_ssm.${l}`)),(!o||o[l]==="attention")&&(s.add(`${r}.${l}.key`),s.add(`${r}.${l}.value`));return s}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")s.add(`${r}.${o}.key`),s.add(`${r}.${o}.value`);else if(a[o]==="linear_attention")e.model_type==="olmo_hybrid"?(s.add(`${n}_conv.${o}.key`),s.add(`${n}_conv.${o}.value`),s.add(`${n}_conv.${o}.query`)):s.add(`${n}_conv.${o}`),s.add(`${n}_recurrent.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return s}else if(["gemma4","gemma4_text"].includes(e.model_type)){const a=e.model_type==="gemma4"?e.text_config:e,o=a.num_hidden_layers,i=a.num_kv_shared_layers??0,l=o-i;for(let c=0;c<l;++c)s.add(`${r}.${c}.key`),s.add(`${r}.${c}.value`);return s}else if(e.model_type==="deepseek_v4"){const{layer_types:a,num_hidden_layers:o}=e;for(let i=0;i<o;++i){s.add(`${r}.${i}.key`),s.add(`${r}.${i}.value`);const l=a[i];if(l==="compressed_sparse_attention")s.add(`${n}_compressor.${i}.kv`),s.add(`${n}_compressor.${i}.gate`),s.add(`${n}_indexer.${i}.kv`),s.add(`${n}_indexer.${i}.gate`);else if(l==="heavily_compressed_attention")s.add(`${n}_compressor.${i}.kv`),s.add(`${n}_compressor.${i}.gate`);else if(l&&l!=="sliding_attention")throw new Error(`Unsupported layer type: ${l}`)}return s}else if(e.model_type==="zaya"){const{num_hidden_layers:a,cca_time1:o}=e,i=o??1;for(let l=0;l<a;l+=i)s.add(`${r}.${l}.key`),s.add(`${r}.${l}.value`),s.add(`${r}.${l}.conv_state`),s.add(`${r}.${l}.shift_state`);return s}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let a;return e.model_type==="voxtral_realtime"&&(t==null?void 0:t.session_name)==="audio_encoder"?a=e.audio_config:a=e.text_config,La(a,t)}return b2(e,{prefix:r})}function b2(e,{prefix:t="past_key_values"}={}){const r=new Set,n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n)for(let s=0;s<n.num_decoder_layers;++s)r.add(`${t}.${s}.encoder.key`),r.add(`${t}.${s}.encoder.value`),r.add(`${t}.${s}.decoder.key`),r.add(`${t}.${s}.decoder.value`);else if(n.multi_query)for(let s=0;s<n.num_layers;++s)r.add(`${t}.${s}.key_value`);else for(let s=0;s<n.num_layers;++s)r.add(`${t}.${s}.key`),r.add(`${t}.${s}.value`);return r}var vl=class Qd{constructor(t){T(this,"model_type",null);T(this,"is_encoder_decoder",!1);T(this,"max_position_embeddings");T(this,"transformers.js_config");Object.assign(this,t),this.normalized_config=Tn(this)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){n&&!(n instanceof Qd)&&(n=new Qd(n));const i=n??await y2(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},ps=class{static async from_pretrained(...e){return vl.from_pretrained(...e)}};function Wp(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function qp(e,t){const r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function M2(e,t,r,n){const s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await ka(e,a,!0,r,pe.IS_NODE_ENV)}async function x2(e,t,r,n,s,a={}){const o=`${t}${r}.onnx`,i=pe.IS_NODE_ENV;let l=[];const c=Wp(s,o,t);if(c>0){if(c>g_)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${g_}).`);const d=qp(o,c);for(const h of d){const _=`${n.subfolder??""}/${h}`;l.push(new Promise(async(p,w)=>{const v=await ka(e,_,!0,n,i);p(v instanceof Uint8Array?{path:h,data:v}:h)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const h=await ka(e,d.data,!0,n);return{...d,data:h}}return d}));return Promise.all(l)}async function k2(e,t,r,n=!1,s=void 0){var k;let a=((k=r.config)==null?void 0:k["transformers.js_config"])??{};const o=z_(r.device??a.device,t,{warn:A=>he.info(A)}),i=H1(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const c=$_(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:A=>he.info(A)});if(Xi.hasOwnProperty(c)){if(o==="webgpu"&&!pe.IS_NODE_ENV&&c===Ye.fp16&&!await Y1())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(Ye).join(", ")}`);const d=Xi[c],h={...r.session_options};h.executionProviders??(h.executionProviders=i);const _=a.free_dimension_overrides;_?h.freeDimensionOverrides??(h.freeDimensionOverrides=_):o.startsWith("webnn")&&!h.freeDimensionOverrides&&he.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 p=M2(e,t,r,d),w=r.use_external_data_format??a.use_external_data_format,v=await x2(e,t,d,r,w,h);if(v.length>0&&(!pe.IS_NODE_ENV||v.some(A=>typeof A!="string"))&&(h.externalData=v),n&&o==="webgpu"){const A=La(r.config,{prefix:"present",session_name:s});if(A.size>0&&!Hi()){const S={};for(const C of A)S[C]="gpu-buffer";h.preferredOutputLocation=S}}return{buffer_or_path:await p,session_options:h,session_config:{dtype:c,device:o}}}async function T2(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const a=(n==null?void 0:n[s])??!1,{buffer_or_path:o,session_options:i,session_config:l}=await k2(e,t[s],r,a,s),c=await L_(o,i,l);return[s,c]})))}function Hp(e){for(let t in e)D_(e[t])?e[t]=new j(e[t]):typeof e[t]=="object"&&Hp(e[t]);return e}async function ye(e,t){const r=E2(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return pe.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await N_(e,n);return Hp(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 he.error(`An error occurred during model execution: "${n}".`),he.error("Inputs given to model:",s),n}}function E2(e,t){const r=Object.create(null),n=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof j)){n.push(o);continue}r[o]=Hi()?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));he.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var je=class{},A2=class extends je{constructor({last_hidden_state:e,hidden_states:t=null,attentions:r=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=r}},le=class extends je{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},Xe=class extends je{constructor({logits:e}){super(),this.logits=e}},Je=class extends je{constructor({logits:e}){super(),this.logits=e}},it=class extends je{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Br=class extends je{constructor({logits:e}){super(),this.logits=e}},C2=class extends je{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}},S2=class extends je{constructor({logits:e,past_key_values:t,encoder_outputs:r,decoder_attentions:n=null,cross_attentions:s=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=r,this.decoder_attentions=n,this.cross_attentions=s}},Qp=class extends je{constructor({alphas:e}){super(),this.alphas=e}},Qt=class extends gt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},P2=class extends gt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},yl=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()}},F2=class extends Qt{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){const n=t[r].data;n.fill(-1/0),n[this.bos_token_id]=0}return t}},I2=class extends Qt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){const n=t[r].data;n.fill(-1/0);for(const s of this.eos_token_id)n[s]=0}return t}},L2=class extends Qt{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data;for(const s of this.suppress_tokens)n[s]=-1/0}return t}},Xp=class extends Qt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){const n=t[r].data;for(const s of this.begin_suppress_tokens)n[s]=-1/0}return t}},O2=class extends Qt{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data;if(n[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){n.subarray(0,this.timestamp_begin).fill(-1/0);continue}const s=e[r].slice(this.begin_index),a=s.length>=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=O1(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=Qe(i.subarray(0,this.timestamp_begin))[0];l>c&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},N2=class extends Qt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let s=0;s<t+1-this.no_repeat_ngram_size;++s){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[s+o]);r.push(a.map(Number))}const n=new Map;for(const s of r){const a=s.slice(0,s.length-1),o=JSON.stringify(a),i=n.get(o)??[];i.push(s[s.length-1]),n.set(o,i)}return n}getGeneratedNgrams(e,t){const r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data,s=this.calcBannedNgramTokens(e[r]);for(const a of s)n[a]=-1/0}return t}},D2=class extends Qt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data;for(const s of new Set(e[r])){const a=Number(s);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return t}},z2=class extends Qt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){const n=t[r].data;for(const s of this.eos_token_id)n[s]=-1/0}return t}},B2=class extends Qt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){const s=t[r].data;for(const a of this.eos_token_id)s[a]=-1/0}return t}},R2=class extends Qt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data,s=e[r];for(const a of this.bad_words_ids){if(s.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=s.at(-i)){o=!1;break}o&&(n[a.at(-1)]=-1/0)}}return t}},$2=class extends Qt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 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;a<s.data.length;++a)s.data[a]+=(n.data[a]-s.data[a])*this.guidance_scale;return s}},G2=class extends P2{constructor(e){super(),this.temperature=e}_call(e,t){const r=t.data;for(let n=0;n<r.length;++n)r[n]/=this.temperature;return t}},Yp=class{constructor(e){T(this,"max_length",20);T(this,"max_new_tokens",null);T(this,"min_length",0);T(this,"min_new_tokens",null);T(this,"early_stopping",!1);T(this,"max_time",null);T(this,"do_sample",!1);T(this,"num_beams",1);T(this,"num_beam_groups",1);T(this,"penalty_alpha",null);T(this,"use_cache",!0);T(this,"temperature",1);T(this,"top_k",50);T(this,"top_p",1);T(this,"typical_p",1);T(this,"epsilon_cutoff",0);T(this,"eta_cutoff",0);T(this,"diversity_penalty",0);T(this,"repetition_penalty",1);T(this,"encoder_repetition_penalty",1);T(this,"length_penalty",1);T(this,"no_repeat_ngram_size",0);T(this,"bad_words_ids",null);T(this,"force_words_ids",null);T(this,"renormalize_logits",!1);T(this,"constraints",null);T(this,"forced_bos_token_id",null);T(this,"forced_eos_token_id",null);T(this,"remove_invalid_values",!1);T(this,"exponential_decay_length_penalty",null);T(this,"suppress_tokens",null);T(this,"streamer",null);T(this,"begin_suppress_tokens",null);T(this,"forced_decoder_ids",null);T(this,"guidance_scale",null);T(this,"num_return_sequences",1);T(this,"output_attentions",!1);T(this,"output_hidden_states",!1);T(this,"output_scores",!1);T(this,"return_dict_in_generate",!1);T(this,"pad_token_id",null);T(this,"bos_token_id",null);T(this,"eos_token_id",null);T(this,"encoder_no_repeat_ngram_size",0);T(this,"decoder_start_token_id",null);T(this,"generation_kwargs",{});Object.assign(this,rt(e,Object.getOwnPropertyNames(this)))}},Oa=class extends gt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},Jp=class Vy extends gt{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof Vy?t=t.criteria:t instanceof Oa&&(t=[t]),this.criteria.push(...t)}_call(t,r){const n=new Array(t.length).fill(!1);for(const s of this.criteria){const a=s(t,r);for(let o=0;o<n.length;++o)n[o]||(n[o]=a[o])}return n}[Symbol.iterator](){return this.criteria.values()}},V2=class extends Oa{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(t=>t.length>=this.max_length)}},U2=class extends Oa{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)})}},Na=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 g1(e)}static getSampler(e){if(e.do_sample)return new W2(e);if(e.num_beams>1)return new q2(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 j2(e)}},j2=class extends Na{async sample(e){const t=Qe(e.data)[1];return[[BigInt(t),0]]}},W2=class extends Na{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 Mn(e,t),s=at(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},q2=class extends Na{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 Mn(e,t),s=at(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},H2=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 j))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)}},bl=H2,q={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,MultimodalEncoder:17},gr={[q.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[q.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[q.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[q.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[q.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...gr[q.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"}},[q.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...gr[q.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"}},[q.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...gr[q.ImageAudioTextToText].text_only_sessions};return r||(n.audio_encoder="audio_encoder",n.vision_encoder="vision_encoder"),n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.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"}},[q.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[q.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[q.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"}},[q.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const n={...gr[q.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"}},[q.MultimodalEncoder]:{sessions:(e,t)=>({model:t.model_file_name??"model",...e.vision_config&&{vision_encoder:"vision_encoder"},...e.audio_config&&{audio_encoder:"audio_encoder"}})},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};function Q2(e){const t=gr[e];return(t==null?void 0:t.text_only_sessions)??null}function X2(e,t,r={}){const n=gr[e]??gr.default;return{sessions:n.sessions(t,r,r.textOnly??!1),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}function Kp(e,{warn:t=!0}={}){const r=e.architectures||[];for(const n of r){const s=wr.get(n);if(s!==void 0)return s}if(e.model_type){const n=wr.get(e.model_type);if(n!==void 0)return n;for(const s of Object.values(En))if(s.has(e.model_type)){const a=wr.get(s.get(e.model_type));if(a!==void 0)return a}}if(t){const n=r.length>0?r.join(", "):"(none)";he.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: ${Aa}`)}return q.EncoderOnly}function Zp(e,{config:t=null,cache_dir:r=null,local_files_only:n=!1,revision:s="main"}={}){if(t!==null)return ps.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s});const a=Bi(e,{cache_dir:r,local_files_only:n,revision:s});return x_(a,()=>ps.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s}))}async function em(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await Zp(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=n??o.device;let d=r??o.dtype;const h=Kp(t),_=(v,y=null)=>{y=y??v;const x=z_(c,v),k=$_(d,v,x),A=Xi[k]??"",S=`${y}${A}.onnx`,C=`${l}/${S}`;a.push(C);const O=Wp(i,S,v);for(const M of qp(S,O)){const V=`${l}/${M}`;a.push(V)}},{sessions:p,optional_configs:w}=X2(h,t,{model_file_name:s});for(const[v,y]of Object.entries(p))_(v,y);if(w)for(const v of Object.values(w))a.push(v);return a}var En=null;function Y2(e){En=e}function Ml(e){if(e instanceof j)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 j("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new j("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function tm(e){return new j("bool",[e],[1])}var rm={[q.DecoderOnly]:{can_generate:!0,forward:vr,prepare_inputs:Cn},[q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:vr,prepare_inputs:Cn},[q.Seq2Seq]:{can_generate:!0,forward:Da,prepare_inputs:za},[q.Vision2Seq]:{can_generate:!0,forward:Da,prepare_inputs:za},[q.Musicgen]:{can_generate:!0,forward:Da},[q.EncoderDecoder]:{can_generate:!1,forward:Da},[q.ImageTextToText]:{can_generate:!0,forward:eA,prepare_inputs:Ba},[q.AudioTextToText]:{can_generate:!0,forward:Z2,prepare_inputs:Ba},[q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ba},[q.Phi3V]:{can_generate:!0,prepare_inputs:Ba},[q.MultiModality]:{can_generate:!0},[q.AutoEncoder]:{can_generate:!1,forward:J2},[q.Chatterbox]:{can_generate:!0,forward:Rr},[q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Cn},default:{can_generate:!1,forward:Rr}};function nm(e,t){var i;let r=wr.get(e),n=!1;const s=(i=t==null?void 0:t.architectures)==null?void 0:i[0];if(s&&s!==e&&(e!=null&&e.endsWith("ForCausalLM"))&&s.endsWith("ForConditionalGeneration")){const l=wr.get(s);l!==void 0&&(r=l,n=!0)}const a=rm[r]??rm.default,o=gr[r]??gr.default;return{typeConfig:{...a,...o},textOnly:n,modelType:r}}var wr=new Map,xl=new Map,An=new Map,I=class extends gt{constructor(t,r,n){super();T(this,"main_input_name","input_ids");T(this,"forward_params",["input_ids","attention_mask"]);T(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=n;const s=An.get(this.constructor),{typeConfig:a}=nm(s,t);this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const t=[];for(const n of Object.values(this.sessions))t.push((r=n.release)==null?void 0:r.call(n));return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:h=null,session_options:_={}}={}){const p={progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:c,dtype:d,use_external_data_format:h,session_options:_},w=An.get(this);n=p.config=await ps.from_pretrained(t,p);const{typeConfig:v,textOnly:y,modelType:x}=nm(w,n);if(x===void 0){const C=w??(n==null?void 0:n.model_type);C!=="custom"&&he.warn(`Model type for '${C}' not found, assuming encoder-only architecture. Please report this at ${Aa}.`)}if(r&&!(r instanceof la)){const C={};try{const O=await em(t,{config:n,dtype:d,device:c,model_file_name:i});(await Promise.all(O.map(V=>cs(t,V,p)))).forEach((V,G)=>{if(V.exists){const U=O[G]==="config.json";C[O[G]]={loaded:U?V.size??0:0,total:V.size??0}}})}catch(O){he.warn(`Unable to fetch model file metadata for total progress tracking: ${O}`)}Object.keys(C).length>0&&(p.progress_callback=new la(r,C))}const k=v.sessions(n,p,y),A=[T2(t,k,p,v.cache_sessions)];v.optional_configs&&A.push(rA(t,v.optional_configs,p));const S=await Promise.all(A);return new this(n,...S)}async _call(t){return await this.forward(t)}async forward(t){return await this._forward(this,t)}get generation_config(){var t;return((t=this.configs)==null?void 0:t.generation_config)??null}_get_logits_processor(t,r,n=null){const s=new yl;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&s.push(new D2(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&s.push(new N2(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&s.push(new R2(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&s.push(new z2(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&s.push(new B2(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&s.push(new F2(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&s.push(new I2(t.max_length,t.forced_eos_token_id)),t.suppress_tokens!==null&&s.push(new L2(t.suppress_tokens)),t.begin_suppress_tokens!==null){const a=r>1||t.forced_bos_token_id===null?r:r+1;s.push(new Xp(t.begin_suppress_tokens,a))}return t.guidance_scale!==null&&t.guidance_scale>1&&s.push(new $2(t.guidance_scale)),t.temperature===0&&t.do_sample&&(he.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`."),t.do_sample=!1),t.do_sample&&t.temperature!==null&&t.temperature!==1&&s.push(new G2(t.temperature)),n!==null&&s.extend(n),s}_prepare_generation_config(t,r,n=Yp){const s={...this.config};for(const o of["decoder","generator","text_config"])o in s&&Object.assign(s,s[o]);const a=new n(s);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,rt(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){const n=new Jp;return t.max_length!==null&&n.push(new V2(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&n.push(new U2(t.eos_token_id)),r&&n.extend(r),n}_validate_model_class(){if(!this.can_generate){const t=[En.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,En.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,En.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,En.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=An.get(this.constructor),n=new Set,s=this.config.model_type;for(const o of t){const i=o==null?void 0:o.get(s);i&&n.add(i)}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(a+=` Please use the following class instead: ${[...n].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){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,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:n,is_encoder_decoder:s}){return n.past_key_values=kl(r,n.past_key_values),n.input_ids=new j("int64",t.flat(),[t.length,1]),s?"decoder_attention_mask"in n&&(n.decoder_attention_mask=Re([n.decoder_attention_mask,xt([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=Re([n.attention_mask,xt([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:n}){const s=rt(n,this.forward_params),a=this.main_input_name;if(a in s){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[a]=t;return{inputs_tensor:s[a],model_inputs:s,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:n,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:i,attention_mask:l,...c}=r,d=await this._prepare_inputs_embeds(r);r={...c,...rt(d,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await Rr(this,r);if(s.guidance_scale!==null&&s.guidance_scale>1)a=Re([a,Zi(a,0)],0),"attention_mask"in r&&(r.attention_mask=Re([r.attention_mask,tl(r.attention_mask)],0));else if(r.decoder_input_ids){const o=Ml(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=Re(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:n,decoder_start_token_id:s,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=n;if(!(i instanceof j)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(s??(s=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==t)throw new Error(`\`decoder_start_token_id\` expected to have length ${t} but got ${s.length}`);i=s}else i=Array.from({length:t},()=>[s]);i=Ml(i)}return l.decoder_attention_mask=el(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:s=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:t,model_kwargs:o});const d=this.config.is_encoder_decoder;d&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let h;d?{input_ids:h,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):h=l[c];let _=h.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);const p=this._get_logits_processor(r,_,n),w=this._get_stopping_criteria(r,s),v=l[c].dims.at(0),y=Na.getSampler(r),x=new Array(v).fill(0),k=h.tolist();a&&a.put(k);let A,S={},C={};for(;;){if(l=this.prepare_inputs_for_generation(k,l,r),A=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){const L=K2(A);for(const ee in L)ee in S||(S[ee]=[]),S[ee].push(L[ee])}else this._return_dict_in_generate_keys&&Object.assign(C,rt(A,this._return_dict_in_generate_keys));const U=A.logits.slice(null,-1,null).to("float32"),J=p(k,U),Q=[];for(let L=0;L<J.dims.at(0);++L){const ee=J[L],H=await y(ee);for(const[ne,Se]of H){const Y=BigInt(ne);x[L]+=Se,k[L].push(Y),Q.push([Y]);break}}if(a&&a.put(Q),w(k).every(L=>L))break;l=this._update_model_kwargs_for_generation({generated_input_ids:Q,outputs:A,model_inputs:l,is_encoder_decoder:d})}a&&a.end();const O=new j("int64",k.flat(),[k.length,k[0].length]),M=kl(A,l.past_key_values),V=new Set(Object.values(M));for(const U of Object.values(A))U.location==="gpu-buffer"&&!V.has(U)&&U.dispose();return"past_key_values"in o||r.return_dict_in_generate||await M.dispose(),r.return_dict_in_generate?{sequences:O,past_key_values:M,...S,...C}:O}async _encode_input(t,r,n){if(!Object.hasOwn(this.sessions,t))throw new Error(`Model does not have a ${t} session.`);const s=this.sessions[t];return(await ye(s,rt(r,s.inputNames)))[n]}async encode_image(t){return this._encode_input("vision_encoder",t,"image_features")}async encode_text(t){return this._encode_input("embed_tokens",t,"inputs_embeds")}async encode_audio(t){return this._encode_input("audio_encoder",t,"audio_features")}};async function Da(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,decoder_attention_mask:a,...o}=t;if(!r){const i=rt(t,e.sessions.model.inputNames);r=(await Rr(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 vr(e,o,!0)}async function Rr(e,t){const r=e.sessions.model,n=rt(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=tl(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=xt([s[0],s[2],s[3]])}return await ye(r,n)}async function J2(e,t){const r=await e.encode(t);return await e.decode(r)}function kl(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_compressor","past_compressor").replace("present_indexer","past_indexer").replace("present","past_key_values");n.includes("encoder")&&t?r[s]=t[s]:r[s]=e[n]}return t?(t.update(r),t):new bl(r)}function K2(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 sm(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function Tl(e,t,r){var c,d,h,_;if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;const n=e.sessions.decoder_model_merged??e.sessions.model,s=((d=(c=t[e.main_input_name]??t.attention_mask)==null?void 0:c.dims)==null?void 0:d[0])??1,a=La(e.config),o=(_=(h=e.config)==null?void 0:h.normalized_config)==null?void 0:_.num_heads,i={batch_size:s};typeof o=="number"&&(i["batch_size x num_heads"]=s*o);const l=Object.create(null);for(const p of n.inputMetadata){if(!a.has(p.name))continue;const w=sm(p.shape,i),v=w.reduce((k,A)=>k*A,1),y=hs[p.type],x=new j(p.type,new y(v),w);t[p.name]=x,l[p.name]=x}return r?(r.update(l),r):new bl(l)}function ms(e,t,r){if(t.num_logits_to_keep)return;const n=e.sessions.decoder_model_merged??e.sessions.model;n!=null&&n.inputNames.includes("num_logits_to_keep")&&(t.num_logits_to_keep=new j("int64",[r],[]))}async function vr(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=tm(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=tA(a,s,i)}ms(e,a,0n),Tl(e,a,s);const o=rt(a,n.inputNames);return await ye(n,o)}async function am(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:c=null,generation_config:d=null,logits_processor:h=null,num_logits_to_keep:_=null,...p}){if(!l){l=await e.encode_text({input_ids:a,...p});const v=rt(p,n);if(Object.keys(v).length>0){if(a.dims[1]!==1){const y=await t({...v,...p});({inputs_embeds:l,attention_mask:o}=r({[s]:y,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){const y=a.dims[1],x=c.get_seq_length();o=Re([xt([a.dims[0],x]),o.slice(null,[o.dims[1]-y,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:v,video_grid_thw:y}=p;[i]=e.get_rope_index(a,v,y,o)}return await vr(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h,num_logits_to_keep:_},!0)}async function Z2(e,t){return await am(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 eA(e,t){return await am(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 om(e,t=0){const[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;o<r;++o){const i=o*n;let l=BigInt(t);for(let c=0;c<n;++c){const d=i+c;s[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=s[d])}}return{data:a,dims:e.dims}}function tA(e,t=null,r=0){const{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=om(a,r);let l=new j("int64",o,i);if(t){const c=-(n??s).dims.at(1);l=l.slice(null,[c,null])}return l}function Cn(e,t,r,n){const s=r.past_key_values?r.past_key_values.get_seq_length():0;if(ms(e,r,1n),!r.attention_mask){let a;for(const o of["input_ids","inputs_embeds","position_ids"])if(r[o]){a=r[o].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=xt([a[0],s+a[1]])}if(r.past_key_values){const{input_ids:a,attention_mask:o}=r;o&&o.dims[1]>a.dims[1]||s<a.dims[1]&&(r.input_ids=a.slice(null,[s,null]))}return r}function za(e,t,r,n){return r.past_key_values&&(t=t.map(s=>[s.at(-1)])),ms(e,r,1n),{...r,decoder_input_ids:Ml(t)}}function Ba(e,...t){return e.config.is_encoder_decoder?za(e,...t):Cn(e,...t)}function im({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(c=>c.reduce((d,h,_)=>(h==e&&d.push(_),d),[])),o=a.reduce((c,d)=>c+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 c=0;c<a.length;++c){const d=a[c],h=t[c];for(let _=0;_<d.length;++_)h[d[_]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function El({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return im({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function lm({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:n,attention_mask:s}){return im({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}async function rA(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const s=await nr(e,t[n],!1,r);return[n,s]})))}var Al={};as(Al,{ASTForAudioClassification:()=>_A,ASTModel:()=>fA,ASTPreTrainedModel:()=>Fl,AfmoeForCausalLM:()=>uA,AfmoeModel:()=>cA,AfmoePreTrainedModel:()=>Sl,AlbertForMaskedLM:()=>oA,AlbertForQuestionAnswering:()=>aA,AlbertForSequenceClassification:()=>sA,AlbertModel:()=>nA,AlbertPreTrainedModel:()=>gs,ApertusForCausalLM:()=>lA,ApertusModel:()=>iA,ApertusPreTrainedModel:()=>Cl,ArceeForCausalLM:()=>hA,ArceeModel:()=>dA,ArceePreTrainedModel:()=>Pl,BartForConditionalGeneration:()=>mA,BartForSequenceClassification:()=>gA,BartModel:()=>pA,BartPretrainedModel:()=>Ra,BaseModelOutput:()=>A2,BeitForImageClassification:()=>vA,BeitModel:()=>wA,BeitPreTrainedModel:()=>Il,BertForMaskedLM:()=>bA,BertForQuestionAnswering:()=>kA,BertForSequenceClassification:()=>MA,BertForTokenClassification:()=>xA,BertModel:()=>yA,BertPreTrainedModel:()=>Sn,BlenderbotForConditionalGeneration:()=>EA,BlenderbotModel:()=>TA,BlenderbotPreTrainedModel:()=>Ll,BlenderbotSmallForConditionalGeneration:()=>CA,BlenderbotSmallModel:()=>AA,BlenderbotSmallPreTrainedModel:()=>Ol,BloomForCausalLM:()=>PA,BloomModel:()=>SA,BloomPreTrainedModel:()=>Nl,CHMv2ForDepthEstimation:()=>BA,CHMv2PreTrainedModel:()=>fm,CLIPModel:()=>$A,CLIPPreTrainedModel:()=>nn,CLIPSegForImageSegmentation:()=>WA,CLIPSegModel:()=>jA,CLIPSegPreTrainedModel:()=>Dl,CLIPTextModel:()=>GA,CLIPTextModelWithProjection:()=>mm,CLIPVisionModel:()=>VA,CLIPVisionModelWithProjection:()=>UA,CamembertForMaskedLM:()=>IA,CamembertForQuestionAnswering:()=>NA,CamembertForSequenceClassification:()=>LA,CamembertForTokenClassification:()=>OA,CamembertModel:()=>FA,CamembertPreTrainedModel:()=>Pn,CausalLMOutput:()=>Br,CausalLMOutputWithPast:()=>C2,ChatterboxModel:()=>dm,ChatterboxPreTrainedModel:()=>um,ChineseCLIPModel:()=>zA,ChineseCLIPPreTrainedModel:()=>hm,ClapAudioModelWithProjection:()=>pm,ClapModel:()=>RA,ClapPreTrainedModel:()=>$a,ClapTextModelWithProjection:()=>_m,CodeGenForCausalLM:()=>HA,CodeGenModel:()=>qA,CodeGenPreTrainedModel:()=>zl,Cohere2ForCausalLM:()=>JA,Cohere2Model:()=>YA,Cohere2PreTrainedModel:()=>Rl,CohereAsrForConditionalGeneration:()=>ZA,CohereAsrModel:()=>KA,CohereAsrPreTrainedModel:()=>$l,CohereForCausalLM:()=>XA,CohereModel:()=>QA,CoherePreTrainedModel:()=>Bl,ConvBertForMaskedLM:()=>tC,ConvBertForQuestionAnswering:()=>sC,ConvBertForSequenceClassification:()=>rC,ConvBertForTokenClassification:()=>nC,ConvBertModel:()=>eC,ConvBertPreTrainedModel:()=>Fn,ConvNextForImageClassification:()=>oC,ConvNextModel:()=>aC,ConvNextPreTrainedModel:()=>Gl,ConvNextV2ForImageClassification:()=>lC,ConvNextV2Model:()=>iC,ConvNextV2PreTrainedModel:()=>Vl,DFineForObjectDetection:()=>hC,DFineModel:()=>dC,DFinePreTrainedModel:()=>jl,DINOv3ConvNextModel:()=>$C,DINOv3ConvNextPreTrainedModel:()=>Tm,DINOv3ViTModel:()=>GC,DINOv3ViTPreTrainedModel:()=>Em,DPTForDepthEstimation:()=>XC,DPTModel:()=>QC,DPTPreTrainedModel:()=>Jl,DacDecoderModel:()=>ym,DacDecoderOutput:()=>wm,DacEncoderModel:()=>vm,DacEncoderOutput:()=>gm,DacModel:()=>fC,DacPreTrainedModel:()=>Ga,DebertaForMaskedLM:()=>pC,DebertaForQuestionAnswering:()=>wC,DebertaForSequenceClassification:()=>mC,DebertaForTokenClassification:()=>gC,DebertaModel:()=>_C,DebertaPreTrainedModel:()=>In,DebertaV2ForMaskedLM:()=>kC,DebertaV2ForQuestionAnswering:()=>AC,DebertaV2ForSequenceClassification:()=>TC,DebertaV2ForTokenClassification:()=>EC,DebertaV2Model:()=>xC,DebertaV2PreTrainedModel:()=>Ln,DecisionTransformerModel:()=>CC,DecisionTransformerPreTrainedModel:()=>bm,DeepseekV3ForCausalLM:()=>yC,DeepseekV3Model:()=>vC,DeepseekV3PreTrainedModel:()=>Wl,DeepseekV4ForCausalLM:()=>MC,DeepseekV4Model:()=>bC,DeepseekV4PreTrainedModel:()=>ql,DeiTForImageClassification:()=>PC,DeiTModel:()=>SC,DeiTPreTrainedModel:()=>Hl,DepthAnythingForDepthEstimation:()=>FC,DepthAnythingPreTrainedModel:()=>Mm,DepthProForDepthEstimation:()=>IC,DepthProPreTrainedModel:()=>xm,DetrForObjectDetection:()=>OC,DetrForSegmentation:()=>NC,DetrModel:()=>LC,DetrObjectDetectionOutput:()=>Ql,DetrPreTrainedModel:()=>Va,DetrSegmentationOutput:()=>km,Dinov2ForImageClassification:()=>zC,Dinov2Model:()=>DC,Dinov2PreTrainedModel:()=>Xl,Dinov2WithRegistersForImageClassification:()=>RC,Dinov2WithRegistersModel:()=>BC,Dinov2WithRegistersPreTrainedModel:()=>Yl,DistilBertForMaskedLM:()=>qC,DistilBertForQuestionAnswering:()=>WC,DistilBertForSequenceClassification:()=>UC,DistilBertForTokenClassification:()=>jC,DistilBertModel:()=>VC,DistilBertPreTrainedModel:()=>On,DonutSwinModel:()=>HC,DonutSwinPreTrainedModel:()=>Am,EdgeTamModel:()=>fL,EfficientNetForImageClassification:()=>JC,EfficientNetModel:()=>YC,EfficientNetPreTrainedModel:()=>Kl,ElectraForMaskedLM:()=>ZC,ElectraForQuestionAnswering:()=>rS,ElectraForSequenceClassification:()=>eS,ElectraForTokenClassification:()=>tS,ElectraModel:()=>KC,ElectraPreTrainedModel:()=>Nn,EmbeddingGemma2Model:()=>Sm,EmbeddingGemma2PreTrainedModel:()=>Cm,Ernie4_5ForCausalLM:()=>sS,Ernie4_5Model:()=>nS,Ernie4_5PretrainedModel:()=>Zl,EsmForMaskedLM:()=>oS,EsmForSequenceClassification:()=>iS,EsmForTokenClassification:()=>lS,EsmModel:()=>aS,EsmPreTrainedModel:()=>vs,EuroBertForMaskedLM:()=>uS,EuroBertForSequenceClassification:()=>dS,EuroBertForTokenClassification:()=>hS,EuroBertModel:()=>cS,EuroBertPreTrainedModel:()=>ys,ExaoneForCausalLM:()=>_S,ExaoneModel:()=>fS,ExaonePreTrainedModel:()=>ec,FalconForCausalLM:()=>mS,FalconH1ForCausalLM:()=>wS,FalconH1Model:()=>gS,FalconH1PreTrainedModel:()=>rc,FalconModel:()=>pS,FalconPreTrainedModel:()=>tc,FastViTForImageClassification:()=>yS,FastViTModel:()=>vS,FastViTPreTrainedModel:()=>nc,Florence2ForConditionalGeneration:()=>bS,Florence2PreTrainedModel:()=>Pm,GLPNForDepthEstimation:()=>BS,GLPNModel:()=>zS,GLPNPreTrainedModel:()=>dc,GPT2LMHeadModel:()=>QS,GPT2Model:()=>HS,GPT2PreTrainedModel:()=>mc,GPTBigCodeForCausalLM:()=>$S,GPTBigCodeModel:()=>RS,GPTBigCodePreTrainedModel:()=>hc,GPTJForCausalLM:()=>YS,GPTJModel:()=>XS,GPTJPreTrainedModel:()=>gc,GPTNeoForCausalLM:()=>VS,GPTNeoModel:()=>GS,GPTNeoPreTrainedModel:()=>fc,GPTNeoXForCausalLM:()=>jS,GPTNeoXModel:()=>US,GPTNeoXPreTrainedModel:()=>_c,Gemma2ForCausalLM:()=>TS,Gemma2Model:()=>kS,Gemma2PreTrainedModel:()=>ac,Gemma3ForCausalLM:()=>SS,Gemma3ForConditionalGeneration:()=>Lm,Gemma3Model:()=>CS,Gemma3PreTrainedModel:()=>Im,Gemma3nForCausalLM:()=>PS,Gemma3nForConditionalGeneration:()=>Ua,Gemma3nPreTrainedModel:()=>Om,Gemma4ForCausalLM:()=>FS,Gemma4ForConditionalGeneration:()=>oc,GemmaForCausalLM:()=>xS,GemmaModel:()=>MS,GemmaPreTrainedModel:()=>sc,GlmForCausalLM:()=>LS,GlmModel:()=>IS,GlmMoeDsaForCausalLM:()=>NS,GlmMoeDsaModel:()=>OS,GlmMoeDsaPreTrainedModel:()=>lc,GlmOcrForConditionalGeneration:()=>DS,GlmPreTrainedModel:()=>ic,GptOssForCausalLM:()=>qS,GptOssModel:()=>WS,GptOssPreTrainedModel:()=>pc,GraniteForCausalLM:()=>KS,GraniteModel:()=>JS,GraniteMoeHybridForCausalLM:()=>eP,GraniteMoeHybridModel:()=>ZS,GraniteMoeHybridPreTrainedModel:()=>vc,GranitePreTrainedModel:()=>wc,GraniteSpeechForConditionalGeneration:()=>tP,GroundingDinoForObjectDetection:()=>rP,GroundingDinoPreTrainedModel:()=>Rm,GroupViTModel:()=>nP,GroupViTPreTrainedModel:()=>$m,HeliumForCausalLM:()=>aP,HeliumModel:()=>sP,HeliumPreTrainedModel:()=>bc,HieraForImageClassification:()=>iP,HieraModel:()=>oP,HieraPreTrainedModel:()=>Mc,HrmTextForCausalLM:()=>cP,HrmTextModel:()=>lP,HrmTextPreTrainedModel:()=>xc,HubertForCTC:()=>mP,HubertForSequenceClassification:()=>gP,HubertModel:()=>pP,HubertPreTrainedModel:()=>_P,HunYuanDenseV1ForCausalLM:()=>vP,HunYuanDenseV1Model:()=>wP,HunYuanDenseV1PreTrainedModel:()=>kc,IJepaForImageClassification:()=>bP,IJepaModel:()=>yP,IJepaPreTrainedModel:()=>Tc,Idefics3ForConditionalGeneration:()=>Gm,ImageMattingOutput:()=>Qp,JAISLMHeadModel:()=>xP,JAISModel:()=>MP,JAISPreTrainedModel:()=>Ec,JinaCLIPModel:()=>kP,JinaCLIPPreTrainedModel:()=>ja,JinaCLIPTextModel:()=>Vm,JinaCLIPVisionModel:()=>TP,Lfm2ForCausalLM:()=>AP,Lfm2Model:()=>EP,Lfm2MoeForCausalLM:()=>PP,Lfm2MoeModel:()=>SP,Lfm2MoePreTrainedModel:()=>Cc,Lfm2PreTrainedModel:()=>Ac,Lfm2VlForConditionalGeneration:()=>FP,LightOnOcrForConditionalGeneration:()=>CP,LiteWhisperForConditionalGeneration:()=>OO,Llama4ForCausalLM:()=>OP,Llama4PreTrainedModel:()=>Um,LlamaForCausalLM:()=>LP,LlamaModel:()=>IP,LlamaPreTrainedModel:()=>Sc,LlavaForConditionalGeneration:()=>ir,LlavaOnevisionForConditionalGeneration:()=>ir,LlavaPreTrainedModel:()=>Fm,LlavaQwen2ForCausalLM:()=>AS,LongT5ForConditionalGeneration:()=>DP,LongT5Model:()=>NP,LongT5PreTrainedModel:()=>Pc,M2M100ForConditionalGeneration:()=>BP,M2M100Model:()=>zP,M2M100PreTrainedModel:()=>Fc,MBartForCausalLM:()=>qP,MBartForConditionalGeneration:()=>jP,MBartForSequenceClassification:()=>WP,MBartModel:()=>UP,MBartPreTrainedModel:()=>bs,MPNetForMaskedLM:()=>zF,MPNetForQuestionAnswering:()=>$F,MPNetForSequenceClassification:()=>BF,MPNetForTokenClassification:()=>RF,MPNetModel:()=>DF,MPNetPreTrainedModel:()=>Dn,MT5ForConditionalGeneration:()=>jF,MT5Model:()=>UF,MT5PreTrainedModel:()=>jc,MarianMTModel:()=>$P,MarianModel:()=>RP,MarianPreTrainedModel:()=>Ic,MaskFormerForInstanceSegmentation:()=>VP,MaskFormerModel:()=>GP,MaskFormerPreTrainedModel:()=>Lc,MaskedLMOutput:()=>Je,Metric3DForDepthEstimation:()=>HP,Metric3DPreTrainedModel:()=>jm,Metric3Dv2ForDepthEstimation:()=>QP,Metric3Dv2PreTrainedModel:()=>Wm,MgpstrForSceneTextRecognition:()=>XP,MgpstrModelOutput:()=>qm,MgpstrPreTrainedModel:()=>Hm,MimiDecoderModel:()=>Jm,MimiDecoderOutput:()=>Xm,MimiEncoderModel:()=>Ym,MimiEncoderOutput:()=>Qm,MimiModel:()=>YP,MimiPreTrainedModel:()=>Wa,Ministral3ForCausalLM:()=>eF,Ministral3Model:()=>ZP,Ministral3PreTrainedModel:()=>Nc,MinistralForCausalLM:()=>KP,MinistralModel:()=>JP,MinistralPreTrainedModel:()=>Oc,Mistral3ForConditionalGeneration:()=>nF,Mistral4ForCausalLM:()=>aF,Mistral4Model:()=>sF,Mistral4PreTrainedModel:()=>zc,MistralForCausalLM:()=>rF,MistralModel:()=>tF,MistralPreTrainedModel:()=>Dc,MobileBertForMaskedLM:()=>iF,MobileBertForQuestionAnswering:()=>cF,MobileBertForSequenceClassification:()=>lF,MobileBertModel:()=>oF,MobileBertPreTrainedModel:()=>Ms,MobileLLMForCausalLM:()=>dF,MobileLLMModel:()=>uF,MobileLLMPreTrainedModel:()=>Bc,MobileNetV1ForImageClassification:()=>fF,MobileNetV1ForSemanticSegmentation:()=>_F,MobileNetV1Model:()=>hF,MobileNetV1PreTrainedModel:()=>qa,MobileNetV2ForImageClassification:()=>mF,MobileNetV2ForSemanticSegmentation:()=>gF,MobileNetV2Model:()=>pF,MobileNetV2PreTrainedModel:()=>Ha,MobileNetV3ForImageClassification:()=>vF,MobileNetV3ForSemanticSegmentation:()=>yF,MobileNetV3Model:()=>wF,MobileNetV3PreTrainedModel:()=>Qa,MobileNetV4ForImageClassification:()=>MF,MobileNetV4ForSemanticSegmentation:()=>xF,MobileNetV4Model:()=>bF,MobileNetV4PreTrainedModel:()=>Xa,MobileViTForImageClassification:()=>TF,MobileViTModel:()=>kF,MobileViTPreTrainedModel:()=>Rc,MobileViTV2ForImageClassification:()=>AF,MobileViTV2Model:()=>EF,MobileViTV2PreTrainedModel:()=>$c,ModelOutput:()=>je,ModernBertDecoderForCausalLM:()=>LF,ModernBertDecoderModel:()=>IF,ModernBertDecoderPreTrainedModel:()=>Gc,ModernBertForMaskedLM:()=>SF,ModernBertForSequenceClassification:()=>PF,ModernBertForTokenClassification:()=>FF,ModernBertModel:()=>CF,ModernBertPreTrainedModel:()=>xs,Moondream1ForConditionalGeneration:()=>ES,MoonshineForConditionalGeneration:()=>NF,MoonshineModel:()=>OF,MoonshinePreTrainedModel:()=>Vc,MptForCausalLM:()=>VF,MptModel:()=>GF,MptPreTrainedModel:()=>Uc,MultiModalityCausalLM:()=>WF,MultiModalityPreTrainedModel:()=>Km,MusicgenForCausalLM:()=>HF,MusicgenForConditionalGeneration:()=>Zm,MusicgenModel:()=>qF,MusicgenPreTrainedModel:()=>Wc,NanoChatForCausalLM:()=>XF,NanoChatModel:()=>QF,NanoChatPreTrainedModel:()=>qc,NemotronHForCausalLM:()=>JF,NemotronHModel:()=>YF,NemotronHPreTrainedModel:()=>Hc,NeoBertForMaskedLM:()=>ZF,NeoBertForQuestionAnswering:()=>rI,NeoBertForSequenceClassification:()=>eI,NeoBertForTokenClassification:()=>tI,NeoBertModel:()=>KF,NeoBertPreTrainedModel:()=>zn,NomicBertModel:()=>nI,NomicBertPreTrainedModel:()=>eg,OPTForCausalLM:()=>gI,OPTModel:()=>mI,OPTPreTrainedModel:()=>eu,Olmo2ForCausalLM:()=>iI,Olmo2Model:()=>oI,Olmo2PreTrainedModel:()=>Xc,Olmo3ForCausalLM:()=>cI,Olmo3Model:()=>lI,Olmo3PreTrainedModel:()=>Yc,OlmoForCausalLM:()=>aI,OlmoHybridForCausalLM:()=>dI,OlmoHybridModel:()=>uI,OlmoHybridPreTrainedModel:()=>Jc,OlmoModel:()=>sI,OlmoPreTrainedModel:()=>Qc,OpenAIPrivacyFilterForTokenClassification:()=>fI,OpenAIPrivacyFilterModel:()=>hI,OpenAIPrivacyFilterPreTrainedModel:()=>Kc,OpenELMForCausalLM:()=>pI,OpenELMModel:()=>_I,OpenELMPreTrainedModel:()=>Zc,OwlViTForObjectDetection:()=>bI,OwlViTModel:()=>yI,OwlViTPreTrainedModel:()=>ru,Owlv2ForObjectDetection:()=>vI,Owlv2Model:()=>wI,Owlv2PreTrainedModel:()=>tu,PaliGemmaForConditionalGeneration:()=>MI,ParakeetForCTC:()=>xI,ParakeetPreTrainedModel:()=>tg,PatchTSMixerForPrediction:()=>TI,PatchTSMixerModel:()=>kI,PatchTSMixerPreTrainedModel:()=>nu,PatchTSTForPrediction:()=>AI,PatchTSTModel:()=>EI,PatchTSTPreTrainedModel:()=>su,Phi3ForCausalLM:()=>FI,Phi3Model:()=>PI,Phi3PreTrainedModel:()=>ou,Phi3VForCausalLM:()=>ng,Phi3VPreTrainedModel:()=>rg,PhiForCausalLM:()=>SI,PhiModel:()=>CI,PhiPreTrainedModel:()=>au,PreTrainedModel:()=>I,PvtForImageClassification:()=>LI,PvtModel:()=>II,PvtPreTrainedModel:()=>iu,PyAnnoteForAudioFrameClassification:()=>NI,PyAnnoteModel:()=>OI,PyAnnotePreTrainedModel:()=>lu,QuestionAnsweringModelOutput:()=>it,Qwen2ForCausalLM:()=>zI,Qwen2Model:()=>DI,Qwen2MoeForCausalLM:()=>RI,Qwen2MoeModel:()=>BI,Qwen2MoePreTrainedModel:()=>uu,Qwen2PreTrainedModel:()=>cu,Qwen2VLForCausalLM:()=>Dm,Qwen2VLForConditionalGeneration:()=>cc,Qwen2VLPreTrainedModel:()=>Nm,Qwen2_5_VLForCausalLM:()=>zm,Qwen2_5_VLForConditionalGeneration:()=>uc,Qwen3ForCausalLM:()=>GI,Qwen3Model:()=>$I,Qwen3MoeForCausalLM:()=>UI,Qwen3MoeModel:()=>VI,Qwen3MoePreTrainedModel:()=>hu,Qwen3NextForCausalLM:()=>WI,Qwen3NextModel:()=>jI,Qwen3NextPreTrainedModel:()=>fu,Qwen3PreTrainedModel:()=>du,Qwen3VLForCausalLM:()=>sg,Qwen3VLForConditionalGeneration:()=>_u,Qwen3VLMoeForCausalLM:()=>HI,Qwen3VLMoeForConditionalGeneration:()=>qI,Qwen3_5ForCausalLM:()=>ag,Qwen3_5ForConditionalGeneration:()=>pu,Qwen3_5MoeForCausalLM:()=>XI,Qwen3_5MoeForConditionalGeneration:()=>QI,RFDetrForObjectDetection:()=>ZI,RFDetrModel:()=>KI,RFDetrObjectDetectionOutput:()=>og,RFDetrPreTrainedModel:()=>gu,RTDetrForObjectDetection:()=>uC,RTDetrModel:()=>cC,RTDetrObjectDetectionOutput:()=>ws,RTDetrPreTrainedModel:()=>Ul,RTDetrV2ForObjectDetection:()=>dL,RTDetrV2Model:()=>uL,RTDetrV2ObjectDetectionOutput:()=>ig,RTDetrV2PreTrainedModel:()=>wu,ResNetForImageClassification:()=>JI,ResNetModel:()=>YI,ResNetPreTrainedModel:()=>mu,RoFormerForMaskedLM:()=>oL,RoFormerForQuestionAnswering:()=>cL,RoFormerForSequenceClassification:()=>iL,RoFormerForTokenClassification:()=>lL,RoFormerModel:()=>aL,RoFormerPreTrainedModel:()=>Rn,RobertaForMaskedLM:()=>tL,RobertaForQuestionAnswering:()=>sL,RobertaForSequenceClassification:()=>rL,RobertaForTokenClassification:()=>nL,RobertaModel:()=>eL,RobertaPreTrainedModel:()=>Bn,Sam2ImageSegmentationOutput:()=>ug,Sam2Model:()=>vu,Sam2PreTrainedModel:()=>dg,Sam3TrackerModel:()=>_L,SamImageSegmentationOutput:()=>lg,SamModel:()=>hL,SamPreTrainedModel:()=>cg,SapiensForDepthEstimation:()=>mL,SapiensForNormalEstimation:()=>gL,SapiensForSemanticSegmentation:()=>pL,SapiensPreTrainedModel:()=>Ya,SegformerForImageClassification:()=>vL,SegformerForSemanticSegmentation:()=>yL,SegformerModel:()=>wL,SegformerPreTrainedModel:()=>Ja,Seq2SeqLMOutput:()=>S2,SequenceClassifierOutput:()=>le,SiglipModel:()=>bL,SiglipPreTrainedModel:()=>yu,SiglipTextModel:()=>hg,SiglipVisionModel:()=>ML,SmolLM3ForCausalLM:()=>kL,SmolLM3Model:()=>xL,SmolLM3PreTrainedModel:()=>bu,SmolVLMForConditionalGeneration:()=>TL,SnacDecoderModel:()=>_g,SnacEncoderModel:()=>fg,SnacModel:()=>EL,SnacPreTrainedModel:()=>Ka,SolarOpenForCausalLM:()=>CL,SolarOpenModel:()=>AL,SolarOpenPreTrainedModel:()=>Mu,SpeechT5ForSpeechToText:()=>PL,SpeechT5ForTextToSpeech:()=>FL,SpeechT5HifiGan:()=>IL,SpeechT5Model:()=>SL,SpeechT5PreTrainedModel:()=>Za,SqueezeBertForMaskedLM:()=>OL,SqueezeBertForQuestionAnswering:()=>DL,SqueezeBertForSequenceClassification:()=>NL,SqueezeBertModel:()=>LL,SqueezeBertPreTrainedModel:()=>ks,StableLmForCausalLM:()=>BL,StableLmModel:()=>zL,StableLmPreTrainedModel:()=>xu,Starcoder2ForCausalLM:()=>$L,Starcoder2Model:()=>RL,Starcoder2PreTrainedModel:()=>ku,StyleTextToSpeech2Model:()=>GL,StyleTextToSpeech2PreTrainedModel:()=>pg,SupertonicForConditionalGeneration:()=>gg,SupertonicPreTrainedModel:()=>mg,Swin2SRForImageSuperResolution:()=>qL,Swin2SRModel:()=>WL,Swin2SRPreTrainedModel:()=>Tu,SwinForImageClassification:()=>UL,SwinForSemanticSegmentation:()=>jL,SwinModel:()=>VL,SwinPreTrainedModel:()=>eo,T5ForConditionalGeneration:()=>QL,T5Model:()=>HL,T5PreTrainedModel:()=>Eu,TableTransformerForObjectDetection:()=>YL,TableTransformerModel:()=>XL,TableTransformerObjectDetectionOutput:()=>wg,TableTransformerPreTrainedModel:()=>Au,TokenClassifierOutput:()=>Xe,TrOCRForCausalLM:()=>JL,TrOCRPreTrainedModel:()=>vg,UltravoxModel:()=>yc,UltravoxPreTrainedModel:()=>Bm,UniSpeechForCTC:()=>ZL,UniSpeechForSequenceClassification:()=>eO,UniSpeechModel:()=>KL,UniSpeechPreTrainedModel:()=>to,UniSpeechSatForAudioFrameClassification:()=>sO,UniSpeechSatForCTC:()=>rO,UniSpeechSatForSequenceClassification:()=>nO,UniSpeechSatModel:()=>tO,UniSpeechSatPreTrainedModel:()=>Ts,VaultGemmaForCausalLM:()=>oO,VaultGemmaModel:()=>aO,VaultGemmaPreTrainedModel:()=>Cu,ViTForImageClassification:()=>cO,ViTMAEModel:()=>uO,ViTMAEPreTrainedModel:()=>yg,ViTMSNForImageClassification:()=>hO,ViTMSNModel:()=>dO,ViTMSNPreTrainedModel:()=>Pu,ViTModel:()=>lO,ViTPreTrainedModel:()=>Su,VisionEncoderDecoderModel:()=>iO,VitMatteForImageMatting:()=>fO,VitMattePreTrainedModel:()=>bg,VitPoseForPoseEstimation:()=>_O,VitPosePreTrainedModel:()=>Mg,VitsModel:()=>pO,VitsModelOutput:()=>xg,VitsPreTrainedModel:()=>kg,VoxtralForConditionalGeneration:()=>mO,VoxtralRealtimeForConditionalGeneration:()=>Ag,VoxtralRealtimePreTrainedModel:()=>Eg,Wav2Vec2BertForCTC:()=>kO,Wav2Vec2BertForSequenceClassification:()=>TO,Wav2Vec2BertModel:()=>xO,Wav2Vec2BertPreTrainedModel:()=>ro,Wav2Vec2ForAudioFrameClassification:()=>fP,Wav2Vec2ForCTC:()=>dP,Wav2Vec2ForSequenceClassification:()=>hP,Wav2Vec2Model:()=>uP,Wav2Vec2PreTrainedModel:()=>$r,WavLMForAudioFrameClassification:()=>PO,WavLMForCTC:()=>AO,WavLMForSequenceClassification:()=>CO,WavLMForXVector:()=>SO,WavLMModel:()=>EO,WavLMPreTrainedModel:()=>$n,WeSpeakerResNetModel:()=>FO,WeSpeakerResNetPreTrainedModel:()=>Sg,WhisperForConditionalGeneration:()=>Pg,WhisperModel:()=>LO,WhisperPreTrainedModel:()=>Iu,XLMForQuestionAnswering:()=>RO,XLMForSequenceClassification:()=>zO,XLMForTokenClassification:()=>BO,XLMModel:()=>NO,XLMPreTrainedModel:()=>Gn,XLMRobertaForMaskedLM:()=>GO,XLMRobertaForQuestionAnswering:()=>jO,XLMRobertaForSequenceClassification:()=>VO,XLMRobertaForTokenClassification:()=>UO,XLMRobertaModel:()=>$O,XLMRobertaPreTrainedModel:()=>Vn,XLMWithLMHeadModel:()=>DO,XVectorOutput:()=>Cg,YolosForObjectDetection:()=>qO,YolosModel:()=>WO,YolosObjectDetectionOutput:()=>Fg,YolosPreTrainedModel:()=>Lu,YoutuForCausalLM:()=>QO,YoutuModel:()=>HO,YoutuPreTrainedModel:()=>Ou,ZayaForCausalLM:()=>YO,ZayaModel:()=>XO,ZayaPreTrainedModel:()=>Nu});var gs=class extends I{},nA=class extends gs{},sA=class extends gs{async _call(e){return new le(await super._call(e))}},aA=class extends gs{async _call(e){return new it(await super._call(e))}},oA=class extends gs{async _call(e){return new Je(await super._call(e))}},Cl=class extends I{},iA=class extends Cl{},lA=class extends Cl{},Sl=class extends I{},cA=class extends Sl{},uA=class extends Sl{},Pl=class extends I{},dA=class extends Pl{},hA=class extends Pl{},Fl=class extends I{},fA=class extends Fl{},_A=class extends Fl{},Ra=class extends I{},pA=class extends Ra{},mA=class extends Ra{},gA=class extends Ra{async _call(e){return new le(await super._call(e))}},Il=class extends I{},wA=class extends Il{},vA=class extends Il{async _call(e){return new le(await super._call(e))}},Sn=class extends I{},yA=class extends Sn{},bA=class extends Sn{async _call(e){return new Je(await super._call(e))}},MA=class extends Sn{async _call(e){return new le(await super._call(e))}},xA=class extends Sn{async _call(e){return new Xe(await super._call(e))}},kA=class extends Sn{async _call(e){return new it(await super._call(e))}},Ll=class extends I{},TA=class extends Ll{},EA=class extends Ll{},Ol=class extends I{},AA=class extends Ol{},CA=class extends Ol{},Nl=class extends I{},SA=class extends Nl{},PA=class extends Nl{},Pn=class extends I{},FA=class extends Pn{},IA=class extends Pn{async _call(e){return new Je(await super._call(e))}},LA=class extends Pn{async _call(e){return new le(await super._call(e))}},OA=class extends Pn{async _call(e){return new Xe(await super._call(e))}},NA=class extends Pn{async _call(e){return new it(await super._call(e))}},DA=4299n,cm=6561n,um=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);T(this,"main_input_name","input_ids");T(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},dm=class extends um{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,num_logits_to_keep:c=null,audio_features:d=null,audio_tokens:h=null,speaker_embeddings:_=null,speaker_features:p=null,...w}){let v;if(!a){const x=this.sessions.embed_tokens.inputNames,k={input_ids:e};if(x.includes("exaggeration")){if(!(n instanceof j)){const A=e.dims[0];if(n==null)n=dt([A],.5);else if(typeof n=="number")n=dt([A],n);else if(Array.isArray(n))n=new j("float32",n,[A]);else throw new Error("Unsupported type for `exaggeration` input")}k.exaggeration=n}if(x.includes("position_ids")&&(k.position_ids=s),{inputs_embeds:a}=await ye(this.sessions.embed_tokens,k),d&&h&&_&&p&&(v={audio_features:d,audio_tokens:h,speaker_embeddings:_,speaker_features:p}),v||r)v??(v=await this.encode_speech(r)),a=Re([v.audio_features,a],1),t=xt([a.dims[0],a.dims[1]]);else{const A=a.dims[1];if(!o||A!==1)throw new Error("Incorrect state encountered during generation.");const S=o.get_seq_length();t=xt([a.dims[0],S+A])}}return{...await vr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1),...v}}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==cm)-1);t.position_ids=new j("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=cm?0:o++)});t.position_ids=new j("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),Cn(this,e,t)}async generate(e){const t=e.past_key_values,{sequences:r,audio_tokens:n,speaker_embeddings:s,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{const i=r.slice(null,[e.input_ids.dims[1],-1]),l=dt([i.dims[0],3],DA),c=Re([n,i,l],1),{waveform:d}=await ye(this.sessions.conditional_decoder,{speech_tokens:c,speaker_features:a,speaker_embeddings:s});return d}finally{o!==t&&await(o==null?void 0:o.dispose())}}},hm=class extends I{},zA=class extends hm{},fm=class extends I{},BA=class extends fm{},$a=class extends I{},RA=class extends $a{},_m=class extends $a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},pm=class extends $a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},nn=class extends I{},$A=class extends nn{},GA=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},mm=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},VA=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},UA=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Dl=class extends I{},jA=class extends Dl{},WA=class extends Dl{},zl=class extends I{},qA=class extends zl{},HA=class extends zl{},Bl=class extends I{},QA=class extends Bl{},XA=class extends Bl{},Rl=class extends I{},YA=class extends Rl{},JA=class extends Rl{},$l=class extends I{constructor(){super(...arguments);T(this,"requires_attention_mask",!1);T(this,"main_input_name","input_features");T(this,"forward_params",["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"])}},KA=class extends $l{},ZA=class extends $l{},Fn=class extends I{},eC=class extends Fn{},tC=class extends Fn{async _call(e){return new Je(await super._call(e))}},rC=class extends Fn{async _call(e){return new le(await super._call(e))}},nC=class extends Fn{async _call(e){return new Xe(await super._call(e))}},sC=class extends Fn{async _call(e){return new it(await super._call(e))}},Gl=class extends I{},aC=class extends Gl{},oC=class extends Gl{async _call(e){return new le(await super._call(e))}},Vl=class extends I{},iC=class extends Vl{},lC=class extends Vl{async _call(e){return new le(await super._call(e))}},Ul=class extends I{},cC=class extends Ul{},uC=class extends Ul{async _call(e){return new ws(await super._call(e))}},ws=class extends je{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},jl=class extends I{},dC=class extends jl{},hC=class extends jl{async _call(e){return new ws(await super._call(e))}},gm=class extends je{constructor({audio_codes:e}){super(),this.audio_codes=e}},wm=class extends je{constructor({audio_values:e}){super(),this.audio_values=e}},Ga=class extends I{constructor(){super(...arguments);T(this,"main_input_name","input_values");T(this,"forward_params",["input_values"])}},fC=class extends Ga{async encode(e){return new gm(await ye(this.sessions.encoder_model,e))}async decode(e){return new wm(await ye(this.sessions.decoder_model,e))}},vm=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},ym=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},In=class extends I{},_C=class extends In{},pC=class extends In{async _call(e){return new Je(await super._call(e))}},mC=class extends In{async _call(e){return new le(await super._call(e))}},gC=class extends In{async _call(e){return new Xe(await super._call(e))}},wC=class extends In{async _call(e){return new it(await super._call(e))}},Wl=class extends I{},vC=class extends Wl{},yC=class extends Wl{},ql=class extends I{},bC=class extends ql{},MC=class extends ql{},Ln=class extends I{},xC=class extends Ln{},kC=class extends Ln{async _call(e){return new Je(await super._call(e))}},TC=class extends Ln{async _call(e){return new le(await super._call(e))}},EC=class extends Ln{async _call(e){return new Xe(await super._call(e))}},AC=class extends Ln{async _call(e){return new it(await super._call(e))}},bm=class extends I{},CC=class extends bm{},Hl=class extends I{},SC=class extends Hl{},PC=class extends Hl{async _call(e){return new le(await super._call(e))}},Mm=class extends I{},FC=class extends Mm{},xm=class extends I{},IC=class extends xm{},Va=class extends I{},LC=class extends Va{},OC=class extends Va{async _call(e){return new Ql(await super._call(e))}},NC=class extends Va{async _call(e){return new km(await super._call(e))}},Ql=class extends je{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},km=class extends je{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},Xl=class extends I{},DC=class extends Xl{},zC=class extends Xl{async _call(e){return new le(await super._call(e))}},Yl=class extends I{},BC=class extends Yl{},RC=class extends Yl{async _call(e){return new le(await super._call(e))}},Tm=class extends I{},$C=class extends Tm{},Em=class extends I{},GC=class extends Em{},On=class extends I{},VC=class extends On{},UC=class extends On{async _call(e){return new le(await super._call(e))}},jC=class extends On{async _call(e){return new Xe(await super._call(e))}},WC=class extends On{async _call(e){return new it(await super._call(e))}},qC=class extends On{async _call(e){return new Je(await super._call(e))}},Am=class extends I{},HC=class extends Am{},Jl=class extends I{},QC=class extends Jl{},XC=class extends Jl{},Kl=class extends I{},YC=class extends Kl{},JC=class extends Kl{async _call(e){return new le(await super._call(e))}},Nn=class extends I{},KC=class extends Nn{},ZC=class extends Nn{async _call(e){return new Je(await super._call(e))}},eS=class extends Nn{async _call(e){return new le(await super._call(e))}},tS=class extends Nn{async _call(e){return new Xe(await super._call(e))}},rS=class extends Nn{async _call(e){return new it(await super._call(e))}},Cm=class extends I{},Sm=class extends Cm{async forward({input_ids:e,attention_mask:t,pixel_values:r=null,image_position_ids:n=null,pixel_values_videos:s=null,video_position_ids:a=null,input_features:o=null,input_features_mask:i=null}){const l={image_features:r&&await this.encode_image({pixel_values:r,pixel_position_ids:n}),video_features:s&&await this.encode_image({pixel_values:s,pixel_position_ids:a}),audio_features:o&&await this.encode_audio({input_features:o,input_features_mask:i})},{image_token_id:c,video_token_id:d,audio_token_id:h,text_config:_}=this.config,p={image:c,video:d,audio:h};for(const[w,v]of Object.entries(p)){const y=`${w}_features`;l[y]??(l[y]=new j("float32",new Float32Array(0),[0,_.hidden_size]));let x=0;for(const k of e.data)Number(k)===v&&++x;if(x!==l[y].dims[0])throw new Error(`The number of ${w} tokens (${x}) and ${w} features (${l[y].dims[0]}) do not match.`)}return await ye(this.sessions.model,{input_ids:e,attention_mask:t,...l})}},Zl=class extends I{},nS=class extends Zl{},sS=class extends Zl{},vs=class extends I{},aS=class extends vs{},oS=class extends vs{async _call(e){return new Je(await super._call(e))}},iS=class extends vs{async _call(e){return new le(await super._call(e))}},lS=class extends vs{async _call(e){return new Xe(await super._call(e))}},ys=class extends I{},cS=class extends ys{},uS=class extends ys{async _call(e){return new Je(await super._call(e))}},dS=class extends ys{async _call(e){return new le(await super._call(e))}},hS=class extends ys{async _call(e){return new Xe(await super._call(e))}},ec=class extends I{},fS=class extends ec{},_S=class extends ec{},tc=class extends I{},pS=class extends tc{},mS=class extends tc{},rc=class extends I{},gS=class extends rc{},wS=class extends rc{},nc=class extends I{},vS=class extends nc{},yS=class extends nc{async _call(e){return new le(await super._call(e))}},Pm=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);T(this,"main_input_name","inputs_embeds")}},bS=class extends Pm{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Re([t,e],1),attention_mask:Re([xt(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,num_logits_to_keep:c=null}){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:h}=await Rr(this,{inputs_embeds:i,attention_mask:r});a=h}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 vr(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:c},!0)}},sc=class extends I{},MS=class extends sc{},xS=class extends sc{},ac=class extends I{},kS=class extends ac{},TS=class extends ac{},Fm=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},ir=class extends Fm{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return El({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},ES=class extends ir{},AS=class extends ir{},Im=class extends I{},CS=class extends Im{},Lm=class extends ir{},SS=class extends Lm{},Om=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},Ua=class extends Om{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:c=null,logits_processor:d=null,num_logits_to_keep:h=null,..._}){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:w}=await this._encode_vision({pixel_values:r,..._});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){const{audio_features:w}=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:w,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await vr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d,num_logits_to_keep:h},!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 El({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 lm({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},PS=class extends Ua{},oc=class extends Ua{constructor(){super(...arguments);T(this,"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(t){return ye(this.sessions.vision_encoder,{pixel_values:t.pixel_values,pixel_position_ids:t.image_position_ids})}},FS=class extends oc{},ic=class extends I{},IS=class extends ic{},LS=class extends ic{},lc=class extends I{},OS=class extends lc{},NS=class extends lc{},Nm=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},cc=class extends Nm{constructor(){super(...arguments);T(this,"image_grid_thw_name","grid_thw")}_get_text_only_rope_index(t,r){if(r){const{data:n,dims:s}=om(r),a=BigInt64Array.from({length:3*n.length},(i,l)=>n[l%n.length]),o=Array.from({length:s[0]},(i,l)=>Qe(n.subarray(s[1]*l,s[1]*(l+1)))[0]+1n+BigInt(s[1]));return[new j("int64",a,[3,...s]),new j("int64",o,[o.length,1])]}else{const[n,s]=t.dims,a=BigInt64Array.from({length:3*n*s},(o,i)=>BigInt(Math.floor(i%s/n)));return[new j("int64",a,[3,...t.dims]),W_([n,1])]}}_reorder_and_write_positions(t,r,n,s){const a=t.reduce((c,d)=>c+d.length,0),o=new Array(a);let i=0;for(let c=0;c<3;++c)for(const d of t){const h=d.length/3;for(let _=c*h;_<(c+1)*h;++_)o[i++]=d[_]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let d=0;d<3;++d)n[d][s][c]=o[d*a/3+l];++l}return o}_get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:r,video_grid_thw_list:n,spatial_merge_size:s,state:a}){const{image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,c=t,h=c.reduce((k,A,S)=>(A==l&&k.push(S),k),[]).map(k=>c[k+1]),_=h.filter(k=>k==o).length,p=h.filter(k=>k==i).length,w=[];let v=0,y=_,x=p;for(let k=0;k<h.length;++k){const A=c.findIndex((D,R)=>R>v&&D==o),S=c.findIndex((D,R)=>R>v&&D==i),C=y>0&&A!==-1?A:c.length+1,O=x>0&&S!==-1?S:c.length+1;let M,V,G,U;C<O?([V,G,U]=r[a.image_index],++a.image_index,--y,M=C):([V,G,U]=n[a.video_index],++a.video_index,--x,M=O);const[J,Q,B]=[Number(V),Math.floor(Number(G)/s),Math.floor(Number(U)/s)],L=M-v,ee=w.length>0?Qe(w.at(-1))[0]+1:0;w.push(Array.from({length:3*L},(D,R)=>ee+R%L));const H=L+ee,ne=J*Q*B,Se=Array.from({length:ne},(D,R)=>H+Math.floor(R/(Q*B))),Y=Array.from({length:ne},(D,R)=>H+Math.floor(R/B)%Q),N=Array.from({length:ne},(D,R)=>H+R%B);w.push([Se,Y,N].flat()),v=M+ne}if(v<c.length){const k=w.length>0?Qe(w.at(-1))[0]+1:0,A=c.length-v;w.push(Array.from({length:3*A},(S,C)=>k+C%A))}return w}get_rope_index(t,r,n,s){const{vision_config:a}=this.config,o=a.spatial_merge_size??2;if(r||n){const i=t.tolist();s||(s=el(t));const l=s.tolist(),c=Array.from({length:3},()=>Array.from({length:t.dims[0]},()=>Array.from({length:t.dims[1]},()=>0))),d=r?r.tolist():[],h=n?n.tolist():[],_={image_index:0,video_index:0},p=[];for(let w=0;w<i.length;++w){const v=i[w].filter((k,A)=>l[w][A]==1),y=this._get_multimodal_rope_positions({filtered_ids:v,image_grid_thw_list:d,video_grid_thw_list:h,spatial_merge_size:o,state:_}),x=this._reorder_and_write_positions(y,l[w],c,w);p.push(Qe(x)[0]+1-i[w].length)}return[new j("int64",c.flat(1/0),[3,t.dims[0],t.dims[1]]),new j("int64",p,[p.length,1])]}else return this._get_text_only_rope_index(t,s)}async encode_image({pixel_values:t,image_grid_thw:r}){return(await ye(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return El({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,n){if(ms(this,r,1n),!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;const a=r.past_key_values.get_seq_length();if(a<r.input_ids.dims[1]){const[o,i]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=i,r.position_ids=o.slice(null,null,[a,null]),r.input_ids=r.input_ids.slice(null,[a,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));const o=BigInt(a),i=r.rope_deltas.map(l=>o+l);r.position_ids=pr([i,i,i],0)}}return r}},Dm=class extends cc{},uc=class extends cc{constructor(){super(...arguments);T(this,"image_grid_thw_name","image_grid_thw")}},zm=class extends Dm{constructor(){super(...arguments);T(this,"image_grid_thw_name","image_grid_thw")}},DS=class extends uc{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),c=Array.from({length:i},(h,_)=>e+Math.floor(_/(o*s))),d=Array.from({length:i},(h,_)=>e+_%o);return[...l,...c,...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 h=1;h<=e.length;++h){const _=h<e.length?e[h]==a?1:0:-1;_!==l&&(o.push([l,i,h]),i=h,l=_)}let c=0;const d=[];for(const[h,_,p]of o)if(h===0){const w=p-_;d.push(Array.from({length:3*w},(v,y)=>c+y%w)),c+=w}else{const w=t[s.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(c,w,v,n)),c+=Math.max(w[1],w[2])/n}return d}},dc=class extends I{},zS=class extends dc{},BS=class extends dc{},hc=class extends I{},RS=class extends hc{},$S=class extends hc{},fc=class extends I{},GS=class extends fc{},VS=class extends fc{},_c=class extends I{},US=class extends _c{},jS=class extends _c{},pc=class extends I{},WS=class extends pc{},qS=class extends pc{},mc=class extends I{},HS=class extends mc{},QS=class extends mc{},gc=class extends I{},XS=class extends gc{},YS=class extends gc{},wc=class extends I{},JS=class extends wc{},KS=class extends wc{},vc=class extends I{},ZS=class extends vc{},eP=class extends vc{},Bm=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}},yc=class extends Bm{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return lm({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},tP=class extends yc{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","input_features","past_key_values"])}},Rm=class extends I{},rP=class extends Rm{},$m=class extends I{},nP=class extends $m{},bc=class extends I{},sP=class extends bc{},aP=class extends bc{},Mc=class extends I{},oP=class extends Mc{},iP=class extends Mc{async _call(e){return new le(await super._call(e))}},xc=class extends I{},lP=class extends xc{},cP=class extends xc{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","token_type_ids","past_key_values"])}prepare_inputs_for_generation(t,r,n){const s=Cn(this,t,r);return s.token_type_ids=(s.past_key_values?tl:el)(s.input_ids),s}},$r=class extends I{},uP=class extends $r{},dP=class extends $r{async _call(e){return new Br(await super._call(e))}},hP=class extends $r{async _call(e){return new le(await super._call(e))}},fP=class extends $r{async _call(e){return new Xe(await super._call(e))}},_P=class extends I{},pP=class extends $r{},mP=class extends $r{async _call(e){return new Br(await super._call(e))}},gP=class extends $r{async _call(e){return new le(await super._call(e))}},kc=class extends I{},wP=class extends kc{},vP=class extends kc{},Gm=class extends ir{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},Tc=class extends I{},yP=class extends Tc{},bP=class extends Tc{async _call(e){return new le(await super._call(e))}},Ec=class extends I{},MP=class extends Ec{},xP=class extends Ec{},ja=class extends I{},kP=class extends ja{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=xt([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=dt([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}},Vm=class extends ja{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},TP=class extends ja{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ac=class extends I{},EP=class extends Ac{},AP=class extends Ac{},CP=class extends ir{},Cc=class extends I{},SP=class extends Cc{},PP=class extends Cc{},FP=class extends ir{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"])}},Sc=class extends I{},IP=class extends Sc{},LP=class extends Sc{},Um=class extends I{},OP=class extends Um{},Pc=class extends I{},NP=class extends Pc{},DP=class extends Pc{},Fc=class extends I{},zP=class extends Fc{},BP=class extends Fc{},Ic=class extends I{},RP=class extends Ic{},$P=class extends Ic{},Lc=class extends I{},GP=class extends Lc{},VP=class extends Lc{},bs=class extends I{},UP=class extends bs{},jP=class extends bs{},WP=class extends bs{async _call(e){return new le(await super._call(e))}},qP=class extends bs{},jm=class extends I{},HP=class extends jm{},Wm=class extends I{},QP=class extends Wm{},qm=class extends je{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]}},Hm=class extends I{},XP=class extends Hm{async _call(e){return new qm(await super._call(e))}},Qm=class extends je{constructor({audio_codes:e}){super(),this.audio_codes=e}},Xm=class extends je{constructor({audio_values:e}){super(),this.audio_values=e}},Wa=class extends I{constructor(){super(...arguments);T(this,"main_input_name","input_values");T(this,"forward_params",["input_values"])}},YP=class extends Wa{async encode(e){return new Qm(await ye(this.sessions.encoder_model,e))}async decode(e){return new Xm(await ye(this.sessions.decoder_model,e))}},Ym=class extends Wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Jm=class extends Wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Oc=class extends I{},JP=class extends Oc{},KP=class extends Oc{},Nc=class extends I{},ZP=class extends Nc{},eF=class extends Nc{},Dc=class extends I{},tF=class extends Dc{},rF=class extends Dc{},nF=class extends ir{},zc=class extends I{},sF=class extends zc{},aF=class extends zc{},Ms=class extends I{},oF=class extends Ms{},iF=class extends Ms{async _call(e){return new Je(await super._call(e))}},lF=class extends Ms{async _call(e){return new le(await super._call(e))}},cF=class extends Ms{async _call(e){return new it(await super._call(e))}},Bc=class extends I{},uF=class extends Bc{},dF=class extends Bc{},qa=class extends I{},hF=class extends qa{},fF=class extends qa{async _call(e){return new le(await super._call(e))}},_F=class extends qa{},Ha=class extends I{},pF=class extends Ha{},mF=class extends Ha{async _call(e){return new le(await super._call(e))}},gF=class extends Ha{},Qa=class extends I{},wF=class extends Qa{},vF=class extends Qa{async _call(e){return new le(await super._call(e))}},yF=class extends Qa{},Xa=class extends I{},bF=class extends Xa{},MF=class extends Xa{async _call(e){return new le(await super._call(e))}},xF=class extends Xa{},Rc=class extends I{},kF=class extends Rc{},TF=class extends Rc{async _call(e){return new le(await super._call(e))}},$c=class extends I{},EF=class extends $c{},AF=class extends $c{async _call(e){return new le(await super._call(e))}},xs=class extends I{},CF=class extends xs{},SF=class extends xs{async _call(e){return new Je(await super._call(e))}},PF=class extends xs{async _call(e){return new le(await super._call(e))}},FF=class extends xs{async _call(e){return new Xe(await super._call(e))}},Gc=class extends I{},IF=class extends Gc{},LF=class extends Gc{},Vc=class extends I{constructor(){super(...arguments);T(this,"requires_attention_mask",!1);T(this,"main_input_name","input_values");T(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},OF=class extends Vc{},NF=class extends Vc{},Dn=class extends I{},DF=class extends Dn{},zF=class extends Dn{async _call(e){return new Je(await super._call(e))}},BF=class extends Dn{async _call(e){return new le(await super._call(e))}},RF=class extends Dn{async _call(e){return new Xe(await super._call(e))}},$F=class extends Dn{async _call(e){return new it(await super._call(e))}},Uc=class extends I{},GF=class extends Uc{},VF=class extends Uc{},jc=class extends I{},UF=class extends jc{},jF=class extends jc{},Km=class extends I{},WF=class extends Km{constructor(...t){super(...t);T(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(t){const r=this._generation_mode??"text";let n;if(r==="text"||!t.past_key_values){const l=this.sessions.prepare_inputs_embeds,c=rt(t,l.inputNames);n=await ye(l,c)}else{const l=this.sessions.gen_img_embeds,c=rt({image_ids:t.input_ids},l.inputNames);n=await ye(l,c)}const s={...t,...n},a=await vr(this,s),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await ye(o,rt(a,o.inputNames));return{...n,...a,...i}}prepare_inputs_for_generation(t,r,n){const s=!!r.past_key_values;return ms(this,r,1n),n.guidance_scale!==null&&n.guidance_scale>1&&(s?r.input_ids=Re([r.input_ids,r.input_ids],0):(r.input_ids=Re([r.input_ids,Zi(r.input_ids,BigInt(n.pad_token_id))],0),r.attention_mask=Re([r.attention_mask,Zi(r.attention_mask,0n)],0))),(s||!r.pixel_values)&&(r.pixel_values=dt([0,0,3,384,384],1)),s&&(r.images_seq_mask=new j("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new j("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(t){return this._generation_mode="text",super.generate(t)}async generate_images(t){this._generation_mode="image";const r=(t.inputs??t[this.main_input_name]).dims[1],s=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await ye(a,{generated_tokens:s}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(const c of i){const d=Ht.fromTensor(c);l.push(d)}return l}},Wc=class extends I{},qF=class extends Wc{},HF=class extends Wc{},Zm=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(t){const[r,n]=t.dims,s=this.config.decoder.num_codebooks,a=n-s;let o=0;for(let c=0;c<t.size;++c){if(t.data[c]==this.config.decoder.pad_token_id)continue;const d=c%n,h=Math.floor(c/n)%s,_=d-h;_>0&&_<=a&&(t.data[o++]=t.data[c])}const i=Math.floor(r/s),l=o/(i*s);return new j(t.type,t.data.slice(0,o),[i,s,l])}prepare_inputs_for_generation(t,r,n){const s=BigInt(this.config.decoder.pad_token_id);let a=structuredClone(t);for(let o=0;o<a.length;++o)for(let i=0;i<a[o].length;++i)o%this.config.decoder.num_codebooks>=i&&(a[o][i]=s);return n.guidance_scale!==null&&n.guidance_scale>1&&(a=a.concat(a)),za(this,a,r)}async generate(t){const r=await super.generate(t),n=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:s}=await ye(this.sessions.encodec_decode,{audio_codes:n});return s}},qc=class extends I{},QF=class extends qc{},XF=class extends qc{},Hc=class extends I{},YF=class extends Hc{},JF=class extends Hc{},zn=class extends I{},KF=class extends zn{},ZF=class extends zn{async _call(e){return new Je(await super._call(e))}},eI=class extends zn{async _call(e){return new le(await super._call(e))}},tI=class extends zn{async _call(e){return new Xe(await super._call(e))}},rI=class extends zn{async _call(e){return new it(await super._call(e))}},eg=class extends I{},nI=class extends eg{},Qc=class extends I{},sI=class extends Qc{},aI=class extends Qc{},Xc=class extends I{},oI=class extends Xc{},iI=class extends Xc{},Yc=class extends I{},lI=class extends Yc{},cI=class extends Yc{},Jc=class extends I{},uI=class extends Jc{},dI=class extends Jc{},Kc=class extends I{},hI=class extends Kc{},fI=class extends Kc{async _call(e){return new le(await super._call(e))}},Zc=class extends I{},_I=class extends Zc{},pI=class extends Zc{},eu=class extends I{},mI=class extends eu{},gI=class extends eu{},tu=class extends I{},wI=class extends tu{},vI=class extends tu{},ru=class extends I{},yI=class extends ru{},bI=class extends ru{},MI=class extends ir{},tg=class extends I{},xI=class extends tg{async _call(e){return new Br(await super._call(e))}},nu=class extends I{},kI=class extends nu{},TI=class extends nu{},su=class extends I{},EI=class extends su{},AI=class extends su{},au=class extends I{},CI=class extends au{},SI=class extends au{},ou=class extends I{},PI=class extends ou{},FI=class extends ou{},rg=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},ng=class extends rg{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,num_logits_to_keep:c=null,...d}){if(!a){let _;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await ye(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const p=this.config.normalized_config.hidden_size;_=new j("float32",[],[0,p])}({inputs_embeds:a}=await ye(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await vr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1)}},iu=class extends I{},II=class extends iu{},LI=class extends iu{async _call(e){return new le(await super._call(e))}},lu=class extends I{},OI=class extends lu{},NI=class extends lu{async _call(e){return new Xe(await super._call(e))}},cu=class extends I{},DI=class extends cu{},zI=class extends cu{},uu=class extends I{},BI=class extends uu{},RI=class extends uu{},du=class extends I{},$I=class extends du{},GI=class extends du{},hu=class extends I{},VI=class extends hu{},UI=class extends hu{},fu=class extends I{},jI=class extends fu{},WI=class extends fu{},_u=class extends uc{},sg=class extends zm{},qI=class extends _u{},HI=class extends sg{},pu=class extends _u{},ag=class extends pu{},QI=class extends pu{},XI=class extends ag{},mu=class extends I{},YI=class extends mu{},JI=class extends mu{async _call(e){return new le(await super._call(e))}},gu=class extends I{},KI=class extends gu{},ZI=class extends gu{async _call(e){return new og(await super._call(e))}},og=class extends ws{},Bn=class extends I{},eL=class extends Bn{},tL=class extends Bn{async _call(e){return new Je(await super._call(e))}},rL=class extends Bn{async _call(e){return new le(await super._call(e))}},nL=class extends Bn{async _call(e){return new Xe(await super._call(e))}},sL=class extends Bn{async _call(e){return new it(await super._call(e))}},Rn=class extends I{},aL=class extends Rn{},oL=class extends Rn{async _call(e){return new Je(await super._call(e))}},iL=class extends Rn{async _call(e){return new le(await super._call(e))}},lL=class extends Rn{async _call(e){return new Xe(await super._call(e))}},cL=class extends Rn{async _call(e){return new it(await super._call(e))}},wu=class extends I{},uL=class extends wu{},dL=class extends wu{async _call(e){return new ig(await super._call(e))}},ig=class extends ws{},lg=class extends je{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},cg=class extends I{},hL=class extends cg{async get_image_embeddings({pixel_values:e}){return await Rr(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??(e.input_labels=xt(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 lg(await super._call(e))}},ug=class extends je{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}},dg=class extends I{},vu=class extends dg{async get_image_embeddings({pixel_values:e}){return await Rr(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??(e.input_labels=xt(a.slice(0,-1))),e.input_boxes??(e.input_boxes=dt([a[0],0,4],0))}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=dt([a[0],a[1],0],-1n),e.input_points=dt([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=rt(e,n.inputNames);return await ye(n,s)}async _call(e){return new ug(await super._call(e))}},fL=class extends vu{},_L=class extends vu{},Ya=class extends I{},pL=class extends Ya{},mL=class extends Ya{},gL=class extends Ya{},Ja=class extends I{},wL=class extends Ja{},vL=class extends Ja{},yL=class extends Ja{},yu=class extends I{},bL=class extends yu{},hg=class extends yu{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},ML=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},bu=class extends I{},xL=class extends bu{},kL=class extends bu{},TL=class extends Gm{},Ka=class extends I{constructor(){super(...arguments);T(this,"main_input_name","input_values");T(this,"forward_params",["input_values"])}},EL=class extends Ka{async encode(e){return await ye(this.sessions.encoder_model,e)}async decode(e){return await ye(this.sessions.decoder_model,e)}},fg=class extends Ka{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},_g=class extends Ka{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Mu=class extends I{},AL=class extends Mu{},CL=class extends Mu{},Za=class extends I{},SL=class extends Za{},PL=class extends Za{},FL=class extends Za{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 Rr(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*s),h=Math.floor(c*n),_=this.config.num_mel_bins;let p=[],w=null,v=null,y=0;for(;;){++y;const A=tm(!!v);let S;v?S=v.output_sequence_out:S=new j("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:A,output_sequence:S,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};Tl(this,C,w),v=await ye(this.sessions.decoder_model_merged,C),w=kl(v,w);const{prob:O,spectrum:M}=v;if(p.push(M),y>=h&&(Array.from(O.data).filter(V=>V>=r).length>0||y>=d))break}const x=Re(p),{waveform:k}=await ye(a.sessions.model,{spectrogram:x});return{spectrogram:x,waveform:k}}},IL=class extends I{constructor(){super(...arguments);T(this,"main_input_name","spectrogram")}},ks=class extends I{},LL=class extends ks{},OL=class extends ks{async _call(e){return new Je(await super._call(e))}},NL=class extends ks{async _call(e){return new le(await super._call(e))}},DL=class extends ks{async _call(e){return new it(await super._call(e))}},xu=class extends I{},zL=class extends xu{},BL=class extends xu{},ku=class extends I{},RL=class extends ku{},$L=class extends ku{},pg=class extends I{},GL=class extends pg{},mg=class extends I{},gg=class extends mg{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:c,durations:d}=await ye(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),h=d.div(s).mul_(a),_=i*o,p=h.data,w=Int32Array.from(p,G=>Math.ceil(G/_)),v=Math.max(...w),y=e.dims[0],x=new BigInt64Array(y*v);for(let G=0;G<y;++G)x.fill(1n,G*v,G*v+w[G]);const k=new j("int64",x,[y,v]),A=l*o,S=A*v;let C=rk([y,A,v]);const O=C.data;for(let G=0;G<y;++G)if(w[G]!==v)for(let U=0;U<A;++U)O.fill(0,G*S+U*v+w[G],G*S+(U+1)*v);const M=dt([y],n);for(let G=0;G<n;++G){const U=dt([y],G);({denoised_latents:C}=await ye(this.sessions.latent_denoiser,{style:r,noisy_latents:C,latent_mask:k,encoder_outputs:c,attention_mask:t,timestep:U,num_inference_steps:M}))}const{waveform:V}=await ye(this.sessions.voice_decoder,{latents:C});return{waveform:V,durations:h}}},eo=class extends I{},VL=class extends eo{},UL=class extends eo{async _call(e){return new le(await super._call(e))}},jL=class extends eo{},Tu=class extends I{},WL=class extends Tu{},qL=class extends Tu{},Eu=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}},HL=class extends Eu{},QL=class extends Eu{},Au=class extends I{},XL=class extends Au{},YL=class extends Au{async _call(e){return new wg(await super._call(e))}},wg=class extends Ql{},vg=class extends I{},JL=class extends vg{},to=class extends I{},KL=class extends to{},ZL=class extends to{async _call(e){return new Br(await super._call(e))}},eO=class extends to{async _call(e){return new le(await super._call(e))}},Ts=class extends I{},tO=class extends Ts{},rO=class extends Ts{async _call(e){return new Br(await super._call(e))}},nO=class extends Ts{async _call(e){return new le(await super._call(e))}},sO=class extends Ts{async _call(e){return new Xe(await super._call(e))}},Cu=class extends I{},aO=class extends Cu{},oO=class extends Cu{},iO=class extends I{constructor(){super(...arguments);T(this,"main_input_name","pixel_values");T(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}},Su=class extends I{},lO=class extends Su{},cO=class extends Su{async _call(e){return new le(await super._call(e))}},yg=class extends I{},uO=class extends yg{},Pu=class extends I{},dO=class extends Pu{},hO=class extends Pu{async _call(e){return new le(await super._call(e))}},bg=class extends I{},fO=class extends bg{async _call(e){return new Qp(await super._call(e))}},Mg=class extends I{},_O=class extends Mg{},xg=class extends je{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},kg=class extends I{},pO=class extends kg{async _call(e){return new xg(await super._call(e))}},mO=class extends yc{},Tg=2,gO=1,Fu=new WeakMap;function wO(e,t){var v,y;const{text_config:r,audio_config:n}=e.config,s=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=n,i=a+o,l=new bl,c=La(n),d={batch_size:1};let h="float32";for(const x of s.inputMetadata){if(x.name==="past_padding_cache"){h=x.type;continue}if(!c.has(x.name))continue;const k=sm(x.shape,d),A=k.reduce((C,O)=>C*O,1),S=hs[x.type];l[x.name]=new j(x.type,new S(A),k)}const _=hs[h],p=new j(h,new _(i*Tg),[1,i,Tg]),w=((v=t[Symbol.asyncIterator])==null?void 0:v.call(t))??((y=t[Symbol.iterator])==null?void 0:y.call(t));if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:s,enc_kv_cache:l,enc_padding_cache:p,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 vO(e,t){const r=t.dims[2],n=Math.floor((gO+r-3)/2)+1,s=new j("int64",BigInt64Array.from({length:n},(d,h)=>BigInt(e.enc_past_seq_len+h)),[1,n]),a=e.enc_past_seq_len+n,o=xt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=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 c)if(d.startsWith("present.")){const h=d.replace("present","past_key_values"),_=e.enc_kv_cache[h];(_==null?void 0:_.location)==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[h]=c[d]}return e.enc_past_seq_len=a,i}async function yO(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){const r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}const n=await vO(e,r.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function bO(e,t,r){if(e.audio_embed_queue.length===0)return;const n=t.data;let s=0,a=r;for(;a>0&&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),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)n[s*e.text_hidden_size+d]+=o.data[c+d];s+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}var MO=class extends Oa{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)}},Eg=class extends I{constructor(){super(...arguments);T(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values"])}},Ag=class extends Eg{async forward({input_ids:e,past_key_values:t,...r}){const n=e.dims[1],s=Fu.get(this);s&&await yO(s,s.audio_consumed+n);const{inputs_embeds:a}=await ye(this.sessions.embed_tokens,{input_ids:e});s&&bO(s,a,n);const o={inputs_embeds:a,...r};Tl(this,o,t);const i=this.sessions.decoder_model_merged,l=rt(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=wO(this,e);Fu.set(this,n);const s=new Jp;s.push(new MO(n)),t&&s.extend(t);try{return await super.generate({...r,stopping_criteria:s})}finally{n.enc_kv_cache.dispose(),Fu.delete(this)}}},ro=class extends I{},xO=class extends ro{},kO=class extends ro{async _call(e){return new Br(await super._call(e))}},TO=class extends ro{async _call(e){return new le(await super._call(e))}},Cg=class extends je{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},$n=class extends I{},EO=class extends $n{},AO=class extends $n{async _call(e){return new Br(await super._call(e))}},CO=class extends $n{async _call(e){return new le(await super._call(e))}},SO=class extends $n{async _call(e){return new Cg(await super._call(e))}},PO=class extends $n{async _call(e){return new Xe(await super._call(e))}},Sg=class extends I{},FO=class extends Sg{},IO=class extends Yp{constructor(){super(...arguments);T(this,"return_timestamps",null);T(this,"return_token_timestamps",null);T(this,"num_frames",null);T(this,"alignment_heads",null);T(this,"task",null);T(this,"language",null);T(this,"no_timestamps_token_id",null);T(this,"prompt_ids",null);T(this,"is_multilingual",null);T(this,"lang_to_id",null);T(this,"task_to_id",null);T(this,"max_initial_timestamp_index",1)}},Iu=class extends I{constructor(){super(...arguments);T(this,"requires_attention_mask",!1);T(this,"main_input_name","input_features");T(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}},LO=class extends Iu{},Pg=class extends Iu{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,IO)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const n=e.task;if(e.is_multilingual){r||(he.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${Jk(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&&(he.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 j?rl(s.decoder_input_ids):s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new yl),r.push(new O2(t,a))),t.begin_suppress_tokens&&(r??(r=new yl),r.push(new Xp(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"&&he.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,c=l.dims[2],d=2,h=this.config.max_source_positions,_=d*h;let p=0;const w=[],v=[];for(;p<c;){const x=Math.min(p+_,c),k=l.slice(null,null,[p,x]);let A;const S=k.dims[2];if(S<_){const H=l.dims[1],ne=new Float32Array(H*_),Se=k.data;for(let Y=0;Y<H;++Y)ne.set(Se.subarray(Y*S,(Y+1)*S),Y*_);A=new j("float32",ne,[1,H,_])}else A=k;if(r)for(const H of r)"begin_index"in H&&(H.begin_index=n.length);const C=await super.generate({inputs:A,generation_config:t,logits_processor:r,decoder_input_ids:n,...s}),M=(i?C.sequences:C)[0].tolist().map(Number).slice(n.length);let V;if(i){C.token_timestamps=this._extract_token_timestamps(C,t.alignment_heads,Math.floor((x-p)/d),.02,n.length);const H=p/d*.02;V=C.token_timestamps[0].tolist().slice(n.length).map(ne=>ne+H)}if(M.length>0&&M.at(-1)===o&&M.pop(),M.length===0)break;const G=M.map(H=>H>=a),U=M.length>=2&&G[M.length-1]&&!G[M.length-2],J=[];for(let H=0;H<M.length-1;++H)G[H]&&G[H+1]&&J.push(H+1);let Q,B=M.length;if(J.length>0)if(U)Q=x-p;else{const H=J.at(-1);Q=(M[H-1]-a)*d,B=H}else Q=x-p;const L=Math.floor(p/d),ee=a+1500;for(let H=0;H<B;++H)M[H]>=a&&(M[H]=Math.min(M[H]+L,ee));w.push(...M.slice(0,B)),V&&v.push(...V.slice(0,B)),p+=Q}w.push(o);const y=[...n,...w];if(i){const x=new j("int64",y.map(BigInt),[1,y.length]),k=[...new Array(n.length).fill(0),...v,0],A=new j("float32",new Float32Array(k),[1,k.length]);return{sequences:x,token_timestamps:A}}return new j("int64",y.map(BigInt),[1,y.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&&he.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&&(he.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},(y,x)=>Re(o.map(k=>k[x]),2)),l=pr(t.map(([y,x])=>{if(y>=i.length)throw new Error(`Layer index ${y} is out of bounds for cross attentions (length ${i.length}).`);return r?i[y].slice(null,x,null,[0,r]):i[y].slice(null,x)})).permute(1,0,2,3),[c,d]=tk(l,-2,0,!0),h=l.clone();for(let y=0;y<h.dims[0];++y){const x=h[y];for(let k=0;k<x.dims[0];++k){const A=x[k],S=c[y][k][0].data,C=d[y][k][0].data;for(let O=0;O<A.dims[0];++O){let M=A[O].data;for(let V=0;V<M.length;++V)M[V]=(M[V]-C[V])/S[V];M.set(z1(M,a))}}}const _=s>0?h.slice(null,null,[s,h.dims[2]],null):h,p=[Yi(_,1)],w=e.sequences.dims,v=new j("float32",new Float32Array(w[0]*w[1]),w);for(let y=0;y<w[0];++y){const x=p[y].neg().squeeze_(0),[k,A]=R1(x.tolist()),S=Array.from({length:k.length-1},(V,G)=>k[G+1]-k[G]),C=er([1],S).map(V=>!!V),O=[];for(let V=0;V<C.length;++V)C[V]&&O.push(A[V]*n);const M=new Array(s).fill(0);M.push(...O),O.length>0&&M.push(O.at(-1)),v[y].data.set(M)}return v}},OO=class extends Pg{},Gn=class extends I{},NO=class extends Gn{},DO=class extends Gn{async _call(e){return new Je(await super._call(e))}},zO=class extends Gn{async _call(e){return new le(await super._call(e))}},BO=class extends Gn{async _call(e){return new Xe(await super._call(e))}},RO=class extends Gn{async _call(e){return new it(await super._call(e))}},Vn=class extends I{},$O=class extends Vn{},GO=class extends Vn{async _call(e){return new Je(await super._call(e))}},VO=class extends Vn{async _call(e){return new le(await super._call(e))}},UO=class extends Vn{async _call(e){return new Xe(await super._call(e))}},jO=class extends Vn{async _call(e){return new it(await super._call(e))}},Lu=class extends I{},WO=class extends Lu{},qO=class extends Lu{async _call(e){return new Fg(await super._call(e))}},Fg=class extends je{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ou=class extends I{},HO=class extends Ou{},QO=class extends Ou{},Nu=class extends I{},XO=class extends Nu{},YO=class extends Nu{},JO=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"],["embedding_gemma2","EmbeddingGemma2Model"]]),KO=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"]]),ZO=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),eN=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"],["deepseek_v4","DeepseekV4Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"],["zaya","ZayaModel"],["hrm_text","HrmTextModel"]]),Ig=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Lg=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Og=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Ng=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"]]),zg=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Bg=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"],["deepseek_v4","DeepseekV4ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["zaya","ZayaForCausalLM"],["hrm_text","HrmTextForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),tN=new Map([["multi_modality","MultiModalityCausalLM"]]),Rg=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"]]),$g=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"]]),Gg=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Vg=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"]]),Ug=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),rN=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),jg=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"]]),Wg=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),qg=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Un=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Hg=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Qg=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Xg=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Yg=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Jg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Kg=new Map([["wavlm","WavLMForXVector"]]),Zg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),ew=new Map([["vitmatte","VitMatteForImageMatting"]]),nN=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),tw=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),rw=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),nw=new Map([["sapiens","SapiensForNormalEstimation"]]),sw=new Map([["vitpose","VitPoseForPoseEstimation"]]),aw=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),ow=[[JO,q.EncoderOnly],[KO,q.EncoderDecoder],[eN,q.DecoderOnlyWithoutHead],[ZO,q.AutoEncoder],[Ng,q.EncoderOnly],[Dg,q.EncoderOnly],[zg,q.Seq2Seq],[Ig,q.Seq2Seq],[Bg,q.DecoderOnly],[tN,q.MultiModality],[Rg,q.EncoderOnly],[$g,q.EncoderOnly],[Gg,q.Vision2Seq],[Vg,q.ImageTextToText],[Ug,q.AudioTextToText],[jg,q.EncoderOnly],[Un,q.EncoderOnly],[Qg,q.EncoderOnly],[Hg,q.EncoderOnly],[ew,q.EncoderOnly],[nN,q.EncoderOnly],[tw,q.EncoderOnly],[rw,q.EncoderOnly],[nw,q.EncoderOnly],[sw,q.EncoderOnly],[Wg,q.EncoderOnly],[qg,q.EncoderOnly],[Xg,q.MaskGeneration],[Yg,q.EncoderOnly],[Jg,q.EncoderOnly],[Lg,q.Seq2Seq],[Og,q.EncoderOnly],[Kg,q.EncoderOnly],[Zg,q.EncoderOnly],[aw,q.EncoderOnly]];for(const[e,t]of ow)for(const r of e.values()){wr.set(r,t);const n=Al[r];An.set(n,r),xl.set(r,n)}var sN=[["MusicgenForConditionalGeneration",Zm,q.Musicgen],["Phi3VForCausalLM",ng,q.Phi3V],["CLIPTextModelWithProjection",mm,q.EncoderOnly],["SiglipTextModel",hg,q.EncoderOnly],["JinaCLIPTextModel",Vm,q.EncoderOnly],["ClapTextModelWithProjection",_m,q.EncoderOnly],["ClapAudioModelWithProjection",pm,q.EncoderOnly],["DacEncoderModel",vm,q.EncoderOnly],["DacDecoderModel",ym,q.EncoderOnly],["MimiEncoderModel",Ym,q.EncoderOnly],["MimiDecoderModel",Jm,q.EncoderOnly],["SnacEncoderModel",fg,q.EncoderOnly],["SnacDecoderModel",_g,q.EncoderOnly],["Gemma3nForConditionalGeneration",Ua,q.ImageAudioTextToText],["Gemma4ForConditionalGeneration",oc,q.ImageAudioTextToText],["SupertonicForConditionalGeneration",gg,q.Supertonic],["ChatterboxModel",dm,q.Chatterbox],["EmbeddingGemma2Model",Sm,q.MultimodalEncoder],["VoxtralRealtimeForConditionalGeneration",Ag,q.VoxtralRealtime]];for(const[e,t,r]of sN)wr.set(e,r),An.set(t,e),xl.set(e,t);var iw=new Map([["modnet",Un],["birefnet",Un],["isnet",Un],["ben",Un]]);for(const[e,t]of iw.entries())t.set(e,"PreTrainedModel"),wr.set(e,q.EncoderOnly),xl.set(e,I);var aN=new Set(iw.keys());wr.set("PreTrainedModel",q.EncoderOnly),An.set(I,"PreTrainedModel");var Ae={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Ng,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Dg,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Lg,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Og,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Rg,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:$g,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:jg,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Un,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Hg,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Qg,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Wg,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:qg,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Xg,MODEL_FOR_CTC_MAPPING_NAMES:Yg,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Jg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Kg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Zg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:rN,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:ew,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:tw,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:rw,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:nw,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:sw,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:aw,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Vg,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Ug,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:zg,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Ig,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Bg,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Gg};Y2(Ae);var Ce=(yo=class{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:c=null,use_external_data_format:d=null,session_options:h={}}={}){const _={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h};if(_.config=await ps.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:p}=_.config;for(const w of this.MODEL_CLASS_MAPPINGS){let v=w.get(p);if(!v){for(const y of w.values())if(y[0]===p){v=y;break}if(!v)continue}return await Al[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return aN.has(p)||he.warn(`Unknown model class "${p}", attempting to construct from base class.`),await I.from_pretrained(e,_);throw Error(`Unsupported model type: ${p}`)}},T(yo,"MODEL_CLASS_MAPPINGS",null),T(yo,"BASE_IF_FAIL",!1),yo),Es=(bo=class extends Ce{},T(bo,"MODEL_CLASS_MAPPINGS",ow.map(e=>e[0])),T(bo,"BASE_IF_FAIL",!0),bo),lw=(ju=class extends Ce{},T(ju,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),ju),oN=(Wu=class extends Ce{},T(Wu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),Wu),Du=(qu=class extends Ce{},T(qu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),qu),iN=(Hu=class extends Ce{},T(Hu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),Hu),lN=(Qu=class extends Ce{},T(Qu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),Qu),cN=(Xu=class extends Ce{},T(Xu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),Xu),uN=(Yu=class extends Ce{},T(Yu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),Yu),dN=(Ju=class extends Ce{},T(Ju,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),Ju),hN=(Ku=class extends Ce{},T(Ku,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),Ku),fN=(Zu=class extends Ce{},T(Zu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),Zu),_N=(ed=class extends Ce{},T(ed,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),ed),cw=(td=class extends Ce{},T(td,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),td),uw=(rd=class extends Ce{},T(rd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),rd),dw=(nd=class extends Ce{},T(nd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),nd),pN=(sd=class extends Ce{},T(sd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),sd),mN=(ad=class extends Ce{},T(ad,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),ad);od=class extends Ce{},T(od,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);var gN=(id=class extends Ce{},T(id,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CTC_MAPPING_NAMES]),id),wN=(ld=class extends Ce{},T(ld,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),ld);cd=class extends Ce{},T(cd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]),ud=class extends Ce{},T(ud,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);var vN=(dd=class extends Ce{},T(dd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),dd);hd=class extends Ce{},T(hd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);var yN=(fd=class extends Ce{},T(fd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),fd),bN=(_d=class extends Ce{},T(_d,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),_d);pd=class extends Ce{},T(pd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]),md=class extends Ce{},T(md,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]);var MN=(gd=class extends Ce{},T(gd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),gd);wd=class extends Ce{},T(wd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]),vd=class extends Ce{},T(vd,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]);async function Xt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>Ht.read(t)))}async function jn(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?oT(r,t):r instanceof Float64Array?new Float32Array(r):r))}function zu(e,t){t&&(e=e.map(o=>o|0));const[r,n,s,a]=e;return{xmin:r,ymin:n,xmax:s,ymax:a}}var qe=class extends gt{constructor({task:e,model:t,tokenizer:r=null,processor:n=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=n}async dispose(){await this.model.dispose()}},xN=class extends qe{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(r),{problem_type:s,id2label:a}=this.model.config,o=s==="multi_label_classification"?l=>l.sigmoid():l=>new j("float32",at(l.data),l.dims),i=[];for(const l of n.logits){const c=o(l),d=await Mn(c,t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:a?a[w]:`LABEL_${w}`,score:h[v]}));t===1?i.push(...p):i.push(p)}return Array.isArray(e)||t===1?i:i[0]}},kN=class extends qe{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:r="none"}={}){if(r!=="none"&&r!=="simple")throw new Error(`Invalid aggregation_strategy: "${r}". Must be one of "none" or "simple".`);const n=Array.isArray(e),s=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),o=(await this.model(s)).logits,i=this.model.config.id2label,l=[];for(let c=0;c<o.dims[0];++c){const d=s.input_ids[c].tolist(),h=o[c],_=[];for(let p=0;p<h.dims[0];++p){const w=h[p],v=Qe(w.data)[1],y=i?i[v]:`LABEL_${v}`;if(t.includes(y))continue;const x=this.tokenizer.decode([d[p]],{skip_special_tokens:!0});if(x==="")continue;const k=at(w.data);_.push({entity:y,score:k[v],index:p,word:x})}l.push(r==="simple"?EN(_,d,this.tokenizer):_)}return n?l:l[0]}};function TN(e){const t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function EN(e,t,r){const n=[];let s=null;for(let a=0;a<e.length;++a){const[o,i]=TN(e[a].entity);s===i&&o!=="B"&&o!=="S"?(n[n.length-1].end=a+1,o==="E"&&(s=null)):(n.push({tag:i,start:a,end:a+1}),s=o==="S"?null:i)}return n.map(({tag:a,start:o,end:i})=>{let l=0;const c=[];for(let d=o;d<i;++d)l+=e[d].score,c.push(t[e[d].index]);return{entity_group:a,score:l/(i-o),word:r.decode(c,{skip_special_tokens:!0})}})}var AN=class extends qe{async _call(e,t,{top_k:r=1}={}){const n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),s=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(n),i=n.input_ids.tolist(),l=n.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,h=[];for(let _=0;_<a.dims[0];++_){const p=i[_],w=p.findIndex(C=>C==d),v=a[_].tolist(),y=o[_].tolist();for(let C=1;C<v.length;++C)(l[_]==0||C<=w||c.findIndex(O=>O==p[C])!==-1)&&(v[C]=-1/0,y[C]=-1/0);const x=at(v).map((C,O)=>[C,O]),k=at(y).map((C,O)=>[C,O]);x[0][0]=0,k[0][0]=0;const A=Ub(x,k).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,O)=>O[2]-C[2]),S=[];for(let C=0;C<Math.min(A.length,r);++C){const[O,M,V]=A[C],G=p.slice(O,M+1),U=this.tokenizer.decode(G,{skip_special_tokens:!0});S.push({answer:U,score:V})}r===1?h.push(...S):h.push(S)}return s?h:h[0]}},CN=class extends qe{async _call(e,{top_k:t=5}={}){const{mask_token_id:r,mask_token:n}=this.tokenizer,s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(s),o=[],i=s.input_ids.tolist();for(let l=0;l<i.length;++l){const c=i[l],d=c.findIndex(v=>v==r);if(d===-1)throw Error(`Mask token (${n}) not found in text.`);const h=a[l][d],_=await Mn(new j("float32",at(h.data),h.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((v,y)=>{const x=c.slice();return x[d]=v,{score:p[y],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(x,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Bu=class extends qe{constructor(){super(...arguments);T(this,"_default_generation_config",{max_new_tokens:256});T(this,"_key","generated_text")}async _call(t,r={}){Array.isArray(t)||(t=[t]),this.model.config.prefix&&(t=t.map(l=>this.model.config.prefix+l));const n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(t=t.map(l=>n[this.task].prefix+l));const s=this.tokenizer,a={padding:!0,truncation:!0};let o;this.task==="translation"&&"_build_translation_inputs"in s?o=s._build_translation_inputs(t,a,r):o=s(t,a);const i=await this.model.generate({...o,...this._default_generation_config,...r});return s.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}},SN=class extends Bu{constructor(){super(...arguments);T(this,"_key","summary_text")}},PN=class extends Bu{constructor(){super(...arguments);T(this,"_key","translation_text")}};function hw(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var FN=class extends qe{constructor(){super(...arguments);T(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r={}){const{add_special_tokens:n,return_full_text:s,tools:a,documents:o,chat_template:i,tokenizer_encode_kwargs:l,...c}=r;let d=!1,h=!1,_=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,p=l,w;if(typeof t=="string")w=t=[t];else if(Array.isArray(t)&&t.every(C=>typeof C=="string"))d=!0,w=t;else{if(hw(t))t=[t];else if(Array.isArray(t)&&t.every(hw))d=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");h=!0;const C={tokenize:!1,add_generation_prompt:!0,...rt({tools:a,documents:o,chat_template:i},["tools","documents","chat_template"]),...p};w=t.map(O=>this.tokenizer.apply_chat_template(O,C)),_=!1,p=void 0}const v=h?!1:s??!0;this.tokenizer.padding_side="left";const y=this.tokenizer(w,{add_special_tokens:_,padding:!0,truncation:!0,...p}),x=await this.model.generate({...y,...this._default_generation_config,...c}),k=this.tokenizer.batch_decode(x,{skip_special_tokens:!0});let A;!v&&y.input_ids.dims.at(-1)>0&&(A=this.tokenizer.batch_decode(y.input_ids,{skip_special_tokens:!0}).map(C=>C.length));const S=Array.from({length:t.length},C=>[]);for(let C=0;C<k.length;++C){const O=Math.floor(C/x.dims[0]*t.length);A&&(k[C]=k[C].slice(A[O])),S[O].push({generated_text:h?[...t[O],{role:"assistant",content:k[C]}]:k[C]})}return!d&&S.length===1?S[0]:S}},IN=class extends qe{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(he.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(he.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:n=!1}={}){const s=Array.isArray(e);s||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>r.replace("{}",l)),o=n||t.length===1,i=[];for(const l of e){const c=[];for(const _ of a){const p=this.tokenizer(l,{text_pair:_,padding:!0,truncation:!0}),w=await this.model(p);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id])}const h=(o?c.map(_=>at(_)[1]):at(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:h.map(_=>t[_[1]]),scores:h.map(_=>_[0])})}return s?i:i[0]}},LN=class extends qe{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,n=await jn(e,r),s=this.model.config.id2label,a=[];for(const o of n){const i=await this.processor(o),c=(await this.model(i)).logits[0],d=await Mn(new j("float32",at(c.data),c.dims),t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:s?s[w]:`LABEL_${w}`,score:h[v]}));a.push(p)}return Array.isArray(e)?a:a[0]}},ON=class extends qe{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const n=!Array.isArray(e);n&&(e=[e]);const s=t.map(c=>r.replace("{}",c)),a=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await jn(e,o),l=[];for(const c of i){const d=await this.processor(c),h=await this.model({...a,...d}),_=at(h.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})))}return n?l[0]:l}},NN=class extends qe{constructor(){super(...arguments);T(this,"_default_generation_config",{})}async _call(t,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(t,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(t,r);case"moonshine":return this._call_moonshine(t,r);case"cohere_asr":return this._call_cohere_asr(t,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(t,r){r.language&&he.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&he.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(t),s=n?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await jn(s,a),i=[];for(const l of o){const c=await this.processor(l),h=(await this.model(c)).logits[0],_=[];for(const w of h)_.push(Qe(w.data)[1]);const p=this.tokenizer.decode(_,{skip_special_tokens:!0}).trim();i.push({text:p})}return n?i[0]:i}async _call_whisper(t,r){const n=r.return_timestamps??!1,s=r.chunk_length_s??0,a=r.force_full_sequences??!1;let o=r.stride_length_s??null;const i={...r};n==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);const l=!Array.isArray(t),c=l?[t]:t,d=this.processor.feature_extractor.config,h=d.chunk_length/this.model.config.max_source_positions,_=d.hop_length,p=d.sampling_rate,w=await jn(c,p),v=[];for(const y of w){let x=[];if(s>0){if(o===null)o=s/6;else if(s<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const S=p*s,C=p*o,O=S-2*C;let M=0;for(;;){const V=M+S,G=y.subarray(M,V),U=await this.processor(G),J=M===0,Q=V>=y.length;if(x.push({stride:[G.length,J?0:C,Q?0:C],input_features:U.input_features,is_last:Q}),Q)break;M+=O}}else x=[{stride:[y.length,0,0],input_features:(await this.processor(y)).input_features,is_last:!0}];for(const S of x){i.num_frames=Math.floor(S.stride[0]/_);const C=await this.model.generate({inputs:S.input_features,...i});if(n==="word"){const O=C.sequences.tolist()[0],M=C.token_timestamps.tolist()[0],V=this.tokenizer.timestamp_begin,G=Math.max(O.findIndex(U=>Number(U)>=V),0);S.tokens=O.slice(G),S.token_timestamps=M.slice(G).map(U=>ds(U,2))}else S.tokens=C[0].tolist();S.stride=S.stride.map(O=>O/p)}const[k,A]=this.tokenizer._decode_asr(x,{time_precision:h,return_timestamps:n,force_full_sequences:a});v.push({text:k,...A})}return l?v[0]:v}async _call_moonshine(t,r){const n=!Array.isArray(t),s=n?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await jn(s,a),i=[];for(const l of o){const c=await this.processor(l),d=Math.floor(l.length/a)*6,h=await this.model.generate({max_new_tokens:d,...r,...c}),_=this.tokenizer.batch_decode(h,{skip_special_tokens:!0})[0];i.push({text:_})}return n?i[0]:i}async _call_cohere_asr(t,r){const n=!Array.isArray(t),s=n?[t]:t,a=this.processor.feature_extractor,o=a.config.sampling_rate,i=await jn(s,o),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),d=[];for(const h of i){const _=a.split_audio(h),p=[];for(const v of _){const y=await this.processor(v),x=await this.model.generate({...y,decoder_input_ids:c,...r}),k=this.tokenizer.decode(x[0].tolist(),{skip_special_tokens:!0}).trim();p.push(k)}const w=this.processor.constructor.join_chunks(p,l);d.push({text:w})}return n?d[0]:d}},DN=class extends qe{constructor(t){super(t);T(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=t.vocoder??null}async _prepare_speaker_embeddings(t,r){if((typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await ve.fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new j("float32",t,[t.length]);else if(!(t instanceof j))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(t.dims[0]===1)t=t.repeat(r,1);else if(t.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${t.dims[0]}.`)}return t}_postprocess_waveform(t,r,n,s=null){const a=r.data,[o,i]=r.dims,l=s?s.data:null,c=[];for(let d=0;d<o;++d){const h=l?Math.min(Math.ceil(l[d]),i):i,_=d*i;c.push(new mT(a.slice(_,_+h),n))}return Array.isArray(t)?c:c[0]}async _call(t,r){return this.processor?this._call_text_to_spectrogram(t,r):this.model.config.model_type==="supertonic"?this._call_supertonic(t,r):this._call_text_to_waveform(t)}async _call_supertonic(t,{speaker_embeddings:r,num_inference_steps:n,speed:s}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:a,style_dim:o}=this.model.config,i=this.tokenizer(t,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,o);const{waveform:c,durations:d}=await this.model.generate_speech({...i,style:r,num_inference_steps:n,speed:s});return this._postprocess_waveform(t,c,a,d)}async _call_text_to_waveform(t){const r=this.tokenizer(t,{padding:!0,truncation:!0}),{waveform:n}=await this.model(r),s=this.model.config.sampling_rate;return this._postprocess_waveform(t,n,s)}async _call_text_to_spectrogram(t,{speaker_embeddings:r}){this.vocoder||(he.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Es.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:n}=this.tokenizer(t,{padding:!0,truncation:!0}),s=n.dims[0];r=await this._prepare_speaker_embeddings(r,s),r=r.view(s,-1);const{waveform:a}=await this.model.generate_speech(n,r,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(t,a,o)}},zN=class extends qe{async _call(e,t={}){const r=Array.isArray(e),n=await Xt(e),{pixel_values:s}=await this.processor(n),a=[];for(const o of s){o.dims=[1,...o.dims];const i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(l)}return r?a:a[0]}},BN=class extends qe{async _call(e,{top_k:t=5}={}){const r=await Xt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),{id2label:a}=this.model.config,o=[];for(const i of s.logits){const l=await Mn(new j("float32",at(i.data),i.dims),t),c=l[0].tolist(),h=l[1].tolist().map((_,p)=>({label:a?a[_]:`LABEL_${_}`,score:c[p]}));o.push(h)}return Array.isArray(e)?o:o[0]}},fw={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},_w=class extends qe{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:s=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const l=await Xt(e),c=l.map(x=>[x.height,x.width]),d=await this.processor(l),{inputNames:h,outputNames:_}=this.model.sessions.model;if(!h.includes("pixel_values")){if(h.length!==1)throw Error(`Expected a single input name, but got ${h.length} inputs: ${h}.`);const x=h[0];if(x in d)throw Error(`Input name ${x} already exists in the inputs.`);d[x]=d.pixel_values}const p=await this.model(d);let w=null;if(o!==null)w=fw[o];else if(this.processor.image_processor){for(const[x,k]of Object.entries(fw))if(k in this.processor.image_processor){w=this.processor.image_processor[k].bind(this.processor.image_processor),o=x;break}}const v=this.model.config.id2label,y=[];if(o)if(o==="panoptic"||o==="instance"){const x=w(p,t,r,n,s,a??c)[0],k=x.segmentation;for(const A of x.segments_info){const S=new Uint8ClampedArray(k.data.length);for(let O=0;O<k.data.length;++O)k.data[O]===A.id&&(S[O]=255);const C=new Ht(S,k.dims[1],k.dims[0],1);y.push({score:A.score,label:v[A.label_id],mask:C})}}else if(o==="semantic"){const{segmentation:x,labels:k}=w(p,a??c)[0];for(const A of k){const S=new Uint8ClampedArray(x.data.length);for(let O=0;O<x.data.length;++O)x.data[O]===A&&(S[O]=255);const C=new Ht(S,x.dims[1],x.dims[0],1);y.push({score:null,label:v[A],mask:C})}}else throw Error(`Subtask ${o} not supported.`);else{const k=p[_[0]];for(let A=0;A<c.length;++A){const S=c[A],C=k[A];C.data.some(M=>M<-1e-5||M>1+1e-5)&&C.sigmoid_();const O=await Ht.fromTensor(C.mul_(255).to("uint8")).resize(S[1],S[0]);y.push({label:null,score:null,mask:O})}}return y}},RN=class extends _w{async _call(e,t={}){const r=await Xt(e),n=await super._call(e,t),s=r.map((a,o)=>{const i=a.clone();return i.putAlpha(n[o].mask),i});return Array.isArray(e)?s:s[0]}},$N=class extends qe{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const n=Array.isArray(e),s=await Xt(e),a=t.map(h=>r.replace("{}",h)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(s),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>at(h.data),d=[];for(const h of l.logits_per_image){const p=[...c(h)].map((w,v)=>({score:w,label:t[v]}));p.sort((w,v)=>v.score-w.score),d.push(p)}return n?d:d[0]}},GN=class extends qe{async _call(e,{threshold:t=.9,percentage:r=!1}={}){const n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const s=await Xt(e),a=r?null:s.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(s),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=c.map(_=>_.boxes.map((p,w)=>({score:_.scores[w],label:d[_.classes[w]],box:zu(p,!r)})));return n?h:h[0]}},VN=class extends qe{async _call(e,t,{threshold:r=.1,top_k:n=null,percentage:s=!1}={}){const a=Array.isArray(e),o=await Xt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){const h=o[d],_=s?null:[[h.height,h.width]],p=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:p});let v;if("post_process_grounded_object_detection"in this.processor){const y=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];v=y.boxes.map((x,k)=>({score:y.scores[k],label:y.labels[k],box:zu(x,!s)}))}else{const y=this.processor.image_processor.post_process_object_detection(w,r,_,!0)[0];v=y.boxes.map((x,k)=>({score:y.scores[k],label:t[y.classes[k]],box:zu(x,!s)}))}v.sort((y,x)=>x.score-y.score),n!==null&&(v=v.slice(0,n)),c.push(v)}return a?c:c[0]}},UN=class extends qe{constructor(){super(...arguments);T(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r,n={}){if(Array.isArray(t)){if(t.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");t=t[0]}const s=(await Xt(t))[0],{pixel_values:a}=await this.processor(s),o=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:a,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...n}),d=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/);let h=null;return d&&d.length>=2&&(h=d[1].trim()),[{answer:h}]}},jN=class extends qe{async _call(e){const t=await Xt(e),r=await this.processor(t),n=await this.model(r),s=[];for(const a of n.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(Ht.fromTensor(o))}return Array.isArray(e)?s:s[0]}},WN=class extends qe{async _call(e){const t=await Xt(e),r=await this.processor(t),{predicted_depth:n}=await this.model(r),s=[];for(let a=0;a<t.length;++a){const o=n[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,h=(await qt(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=h.min().item(),p=h.max().item(),w=h.sub(_).div_(p-_).mul_(255).to("uint8").unsqueeze(0),v=Ht.fromTensor(w);s.push({predicted_depth:h,depth:v})}return Array.isArray(e)?s:s[0]}},qN=class extends qe{async _call(e,{pooling:t="none",normalize:r=!1,quantize:n=!1,precision:s="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=ek(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),n&&(i=nk(i,s)),i}},HN=class extends qe{async _call(e,{pool:t=null}={}){const r=await Xt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n});let a;if(t){if(!("pooler_output"in s))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=s.pooler_output}else a=s.last_hidden_state??s.logits??s.image_embeds;return a}},no=Object.freeze({"text-classification":{pipeline:xN,model:lw,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:kN,model:oN,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:AN,model:hN,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:CN,model:dN,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:SN,model:Du,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:PN,model:Du,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Bu,model:Du,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:FN,model:uN,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:IN,model:lw,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:LN,model:wN,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:ON,model:Es,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:NN,model:[iN,gN],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:DN,model:[cN,lN],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:zN,model:fN,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:BN,model:_N,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:_w,model:[cw,uw,dw],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:RN,model:[cw,uw,dw],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:$N,model:Es,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:GN,model:pN,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:VN,model:mN,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:UN,model:vN,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:jN,model:yN,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:WN,model:bN,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:qN,model:Es,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:HN,model:[MN,Es],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),pw=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function QN(e){if(!e)throw new Error("modelId is required");return(await cs(e,_s,{})).exists?[_s]:[]}async function XN(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await em(e,{config:t,dtype:r,device:n,model_file_name:s});if(a){const l=await q_(e);i.push(...l)}if(o){const l=await QN(e);i.push(...l)}return i}async function YN(e,t,r={}){e=pw[e]??e;const n=no[e];if(!n)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(no).join(", ")}]`);const{type:s}=n,i=await XN(t,{...r,include_tokenizer:s!=="audio"&&s!=="image",include_processor:s!=="text"});if(e==="text-generation"){const l=await Zp(t,r),c=Kp(l),d=Q2(c);if(d){const h=Object.values(d).map(_=>`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||h.some(p=>_.startsWith(p)))}}return i}async function JN(e,t=null,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:_={}}={}){e=pw[e]??e;const p=no[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(no)}]`);t||(t=p.default.model,he.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype&&(l=p.default.dtype));const w=await YN(e,t,{device:i,dtype:l});let v={};if(r)try{(await Promise.all(w.map(async J=>cs(t,J)))).forEach((J,Q)=>{J.exists&&(v[w[Q]]={loaded:0,total:J.size??0})})}catch(U){he.warn(`Unable to fetch model file metadata for total progress tracking: ${U}`)}const y={progress_callback:r?new la(r,v):void 0,config:n,cache_dir:s,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:h,session_options:_},x=w.includes("tokenizer.json"),k=w.includes("preprocessor_config.json"),A=p.model;let S;if(Array.isArray(A)){const U=n??await ps.from_pretrained(t,y),{model_type:J}=U,Q=A.find(B=>B.supports(J));if(!Q)throw Error(`Unsupported model type "${J}" for task "${e}". None of the candidate model classes support this type.`);S=Q.from_pretrained(t,{...y,config:U})}else S=A.from_pretrained(t,y);const[C,O,M]=await Promise.all([x?Te.from_pretrained(t,y):null,k?v2.from_pretrained(t,y):null,S]),V={task:e,model:M};C&&(V.tokenizer=C),O&&(V.processor=O),Pr(r,{status:"ready",task:e,model:t});const G=p.pipeline;return new G(V)}pe.IS_PROCESS_AVAILABLE;let so;self.addEventListener("message",async({data:e})=>{if((e==null?void 0:e.type)!=="transcribe")return;const{id:t,audio:r}=e;try{so||(so=JN("automatic-speech-recognition","onnx-community/whisper-small",{dtype:"q8",progress_callback:a=>self.postMessage({type:"progress",id:t,progress:{status:a.status,file:a.file,progress:a.progress}})}));const s=await(await so)(new Float32Array(r),{chunk_length_s:30,stride_length_s:5,num_beams:2});self.postMessage({type:"result",id:t,text:String((s==null?void 0:s.text)||"").trim()})}catch(n){so=null,self.postMessage({type:"error",id:t,message:(n==null?void 0:n.message)||"Local Whisper could not transcribe this audio."})}})})();
|