zerogterm 0.1.0-alpha.2 → 0.2.0-alpha.2
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 +5 -2
- package/bin/zerogterm.cjs +0 -0
- package/dist/main/main/main.js +53 -4
- package/dist/main/main/preload.cjs +8 -0
- package/dist/main/main/session-history.js +105 -0
- package/dist/main/main/session-service.js +92 -29
- package/dist/main/main/ssh-inventory.js +116 -0
- package/dist/renderer/assets/index-5pgRaxBt.css +1 -0
- package/dist/renderer/assets/index-BWVjX0UX.js +17 -0
- package/dist/renderer/assets/ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm +0 -0
- package/dist/renderer/assets/voice-worker-Bde9NFkO.js +37 -0
- package/dist/renderer/index.html +3 -3
- package/package.json +5 -5
- package/dist/main/main/preload.js +0 -12
- package/dist/renderer/assets/index-BouOz_9d.css +0 -1
- package/dist/renderer/assets/index-wAR4K515.js +0 -17
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var li=Object.defineProperty,ab=Object.getOwnPropertyDescriptor,ob=Object.getOwnPropertyNames,ib=Object.prototype.hasOwnProperty,lb=(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')}),pe=(e,t)=>()=>(e&&(t=e(e=0)),t),en=(e,t)=>{for(var r in t)li(e,r,{get:t[r],enumerable:!0})},cb=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ob(t))!ib.call(e,n)&&n!==r&&li(e,n,{get:()=>t[n],enumerable:!(s=ab(t,n))||s.enumerable});return e},jn=e=>cb(li({},"__esModule",{value:!0}),e),Ds,_r,Or,nh,Nf,Df=pe(()=>{Ds=new Map,_r=[],Or=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=Ds.get(e);if(s===void 0)Ds.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=_r.indexOf(e);n!==-1&&_r.splice(n,1);for(let a=0;a<_r.length;a++)if(Ds.get(_r[a]).priority<=r){_r.splice(a,0,e);return}_r.push(e)}return}throw new TypeError("not a valid backend")},nh=async e=>{let t=Ds.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(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Nf=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),s=r.length===0?_r:r,n,a=[],o=new Set;for(let l of s){let c=await nh(l);typeof c=="string"?a.push({name:l,err:c}):(n||(n=c),n===c&&o.add(l))}if(!n)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[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),ub=pe(()=>{Df()}),zf,db=pe(()=>{zf="1.24.0-dev.20251116-b39e144322"}),io,Ye,Bf=pe(()=>{db(),io="warning",Ye={wasm:{},webgl:{},webgpu:{},versions:{common:zf},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}`);io=e}},get logLevel(){return io}},Object.defineProperty(Ye,"logLevel",{enumerable:!0})}),De,hb=pe(()=>{Bf(),De=Ye}),Rf,Gf,fb=pe(()=>{Rf=(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 s=r.getContext("2d");if(s!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=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*n,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 M=0;M<n;M++){let y=(e.data[h++]-c[0])*l[0],k=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],E=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+y+","+k+","+A+","+E+")",s.fillRect(M,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")},Gf=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,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*n;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,M=3,y=0,k=h,A=h*2,E=-1;i==="RGBA"?(y=0,k=h,A=h*2,E=h*3):i==="RGB"?(y=0,k=h,A=h*2):i==="RBG"&&(y=0,A=h,k=h*2),s=r.createImageData(n,a);for(let C=0;C<a*n;p+=_,w+=_,v+=_,M+=_,C++)s.data[p]=(e.data[y++]-d[0])*c[0],s.data[w]=(e.data[k++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[M]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw new Error("Can not access image data");return s}}),Tn,$f,Vf,Uf,jf,qf,_b=pe(()=>{ci(),Tn=(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:s}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.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*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,v=3,M=0,y=c,k=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(M=0,k=c,y=c*2):l==="BGR"&&(k=0,y=c,M=c*2);for(let E=0;E<c;E++,_+=h,w+=h,p+=h,v+=h)d[M++]=(e[_]+o[0])/a[0],d[y++]=(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 wt("float32",d,[1,4,r,s]):new wt("float32",d,[1,3,r,s])},$f=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=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(s){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(n){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,Tn(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(Tn(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Tn(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Vf=(e,t)=>{let{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new wt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Uf=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new wt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},jf=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new wt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},qf=(e,t,r)=>new wt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Lr,Us,lo,Wf,pb=pe(()=>{Lr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Us=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),lo=!1,Wf=()=>{if(!lo){lo=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Lr.set("int64",BigInt64Array),Us.set(BigInt64Array,"int64")),t&&(Lr.set("uint64",BigUint64Array),Us.set(BigUint64Array,"uint64")),s?(Lr.set("float16",r),Us.set(r,"float16")):Lr.set("float16",Uint16Array)}}}),Hf,Qf,mb=pe(()=>{ci(),Hf=e=>{let t=1;for(let r=0;r<e.length;r++){let s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},Qf=(e,t)=>{switch(e.location){case"cpu":return new wt(e.type,e.data,t);case"cpu-pinned":return new wt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new wt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new wt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new wt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),wt,ci=pe(()=>{fb(),_b(),pb(),mb(),wt=class{constructor(e,t,r){Wf();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=Lr.get(s);if(!o)throw new TypeError(`unsupported type "${s}" 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(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.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=e.gpuBuffer,this.downloader=e.download,this.disposer=e.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=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(s=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=Lr.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 ${s} 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")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=Us.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=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");n=i,this.cpuData=o,this.dataLocation="cpu"}let a=Hf(n);if(this.cpuData&&a!==this.cpuData.length&&!((s==="uint4"||s==="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=s,this.dims=n,this.size=a}static async fromImage(e,t){return $f(e,t)}static fromTexture(e,t){return Vf(e,t)}static fromGpuBuffer(e,t){return Uf(e,t)}static fromMLTensor(e,t){return jf(e,t)}static fromPinnedBuffer(e,t,r){return qf(e,t,r)}toDataURL(e){return Rf(this,e)}toImageData(e){return Gf(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 Qf(this,e)}}}),St,Xf=pe(()=>{ci(),St=wt}),qn,co,Dr,zr,br,Mr,Yf=pe(()=>{Bf(),qn=(e,t)=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.timeStamp(`${e}::ORT::${t}`)},co=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let a=`FUNC_${e}::${r[n].trim().split(" ")[1]}`;t&&(a+=`::${t}`),qn("CPU",a);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},Dr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||co("BEGIN",e)},zr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||co("END",e)},br=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.time(`ORT::${e}`)},Mr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.timeEnd(`ORT::${e}`)}}),Jf,gb=pe(()=>{Df(),Xf(),Yf(),Jf=class Kf{constructor(t){this.handler=t}async run(t,r,s){Dr(),br("InferenceSession.run");let n={},a={};if(typeof t!="object"||t===null||t instanceof St||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 St)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}.`);n[c]=null}if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"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 St)&&(c=!0,o=!1,n[h]=_)}if(c){if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"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)n[c]=null;let i=await this.handler.run(t,n,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof St?l[c]=d:l[c]=new St(d.type,d.data,d.dims)}return Mr("InferenceSession.run"),zr(),l}async release(){return this.handler.dispose()}static async create(t,r,s,n){Dr(),br("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 s=="number"){if(_=s,!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 n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"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 Nf(o),c=await i.createInferenceSessionHandler(a,l);return Mr("InferenceSession.create"),zr(),new Kf(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}}}),ui,wb=pe(()=>{gb(),ui=Jf}),vb=pe(()=>{}),yb=pe(()=>{}),bb=pe(()=>{}),Mb=pe(()=>{}),Zf={};en(Zf,{InferenceSession:()=>ui,TRACE:()=>qn,TRACE_EVENT_BEGIN:()=>br,TRACE_EVENT_END:()=>Mr,TRACE_FUNC_BEGIN:()=>Dr,TRACE_FUNC_END:()=>zr,Tensor:()=>St,env:()=>De,registerBackend:()=>Or});var Br=pe(()=>{ub(),hb(),wb(),Xf(),vb(),yb(),Yf(),bb(),Mb()}),di=pe(()=>{}),e_={};en(e_,{default:()=>t_});var uo,ho,t_,xb=pe(()=>{m_(),Rr(),hi(),uo="ort-wasm-proxy-worker",ho=globalThis.self?.name===uo,ho&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":fi(r.wasm).then(()=>{wi(r).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})})},s=>{postMessage({type:t,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;vi(n,s).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:s}=r,n=Qn(s);postMessage({type:t,out:n});break}case"create":{let{model:s,options:n}=r;yi(s,n).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":bi(r),postMessage({type:t});break;case"run":{let{sessionId:s,inputIndices:n,inputs:a,outputIndices:o,options:i}=r;Mi(s,n,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},ki([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":xi(r),postMessage({type:t});break;default:}}catch(s){postMessage({type:t,err:s})}}),t_=ho?null:e=>new Worker(e??mt,{type:"module",name:uo})}),r_={};en(r_,{default:()=>s_});async function ah(e={}){var t=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,f)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let u=f=>(...m)=>{let g=$t;return m=f(...m),$t!=g?new Promise((b,T)=>{$a={resolve:b,reject:T}}):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?.()};var o,i,l=(u,f)=>{throw f},c=import.meta.url,d="";if(r||s){try{d=new URL(".",c).href}catch{}s&&(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(L(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,M,y=console.log.bind(console),k=console.error.bind(console),A=y,E=k,C=!1,L=u=>u.startsWith("file://");function x(){hr.buffer!=B.buffer&&H()}if(n){let u=function(f){try{var m=f.data,g=m.Oc;if(g==="load"){let b=[];self.onmessage=T=>b.push(T),M=()=>{postMessage({Oc:"loaded"});for(let T of b)u(T);self.onmessage=u};for(let T of m.ce)t[T]&&!t[T].proxy||(t[T]=(...P)=>{postMessage({Oc:"callHandler",be:T,args:P})},T=="print"&&(A=t[T]),T=="printErr"&&(E=t[T]));hr=m.ie,H(),_=m.je,ut(),kn()}else if(g==="run"){(function(b){var T=(x(),O)[b+52>>>2>>>0];b=(x(),O)[b+56>>>2>>>0],pd(T,T-b),te(T)})(m.Nc),Za(m.Nc,0,0,1,0,0),ru(),Ba(m.Nc),G||(Ju(),G=!0);try{lw(m.ge,m.Wc)}catch(b){if(b!="unwind")throw b}}else m.target!=="setimmediate"&&(g==="checkMailbox"?G&&mn():g&&(E(`worker: received unknown command ${g}`),E(m)))}catch(b){throw ud(),b}};var G=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var B,j,X,W,N,O,U,Q,ee,I,D,R=!1;function H(){var u=hr.buffer;t.HEAP8=B=new Int8Array(u),X=new Int16Array(u),t.HEAPU8=j=new Uint8Array(u),W=new Uint16Array(u),t.HEAP32=N=new Int32Array(u),t.HEAPU32=O=new Uint32Array(u),U=new Float32Array(u),Q=new Float64Array(u),ee=new BigInt64Array(u),I=new BigUint64Array(u)}function he(){R=!0,n?M():sr._b()}function ke(u){throw E(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v?.(u),u}function oe(){return{a:{f:cw,J:uw,k:dw,p:hw,l:fw,sa:_w,b:pw,ca:mw,Ja:lu,q:gw,da:hu,Za:fu,Fa:_u,Ha:pu,_a:mu,Xa:gu,Qa:wu,Wa:vu,oa:yu,Ga:bu,Xb:Mu,Ya:xu,Yb:ku,db:ww,Da:vw,Sb:yw,Qb:Mw,Ca:kw,M:Tw,I:Ew,Rb:Aw,ja:Ow,Tb:Nw,Ta:Dw,Vb:Bw,Ka:Rw,Ob:Gw,ka:$w,Sa:Ba,ab:Vw,U:Ww,n:Jw,c:Da,rb:Kw,w:Zw,L:ev,z:tv,j:rv,o:Lu,sb:sv,G:nv,T:av,h:ov,u:iv,m:lv,i:cv,Na:uv,Oa:dv,Pa:hv,La:Du,Ma:zu,Pb:Bu,eb:_v,cb:mv,Y:gv,qb:wv,la:vv,bb:pv,fb:yv,$a:bv,Wb:Mv,N:fv,gb:xv,X:kv,Ub:Tv,nb:Ov,C:Nv,ra:Dv,qa:zv,pb:Bv,W:Rv,v:Gv,mb:$v,lb:Vv,kb:Uv,ob:jv,jb:qv,ib:Wv,hb:Hv,Ua:ju,Va:qu,Ia:Ur,V:Wu,na:Hu,Ra:Qu,ma:Xu,Cb:sb,xa:Jy,Db:rb,ya:Yy,F:Ry,e:Ey,s:ky,x:xy,B:Dy,Fb:Hy,ba:Wy,D:Sy,za:Qy,$:Ky,ga:qy,Gb:jy,Hb:Uy,Ba:Gy,Aa:Vy,Ib:$y,wa:tb,aa:Xy,d:Ty,A:Cy,r:Ay,Bb:nb,t:Fy,y:zy,H:Py,E:Ly,K:By,R:Zy,ia:Ny,_:eb,Jb:Oy,Kb:Iy,g:Xv,a:hr,Nb:Vr,Eb:Yv,ha:Jv,O:Kv,pa:Zv,Lb:ey,ta:ty,Q:ry,yb:sy,zb:ny,ua:ay,ea:oy,P:iy,Ea:ly,va:cy,Z:uy,wb:dy,Zb:hy,S:fy,Ab:_y,tb:py,ub:gy,vb:wy,fa:vy,xb:yy,Mb:by}}}async function ut(){function u(g,b){var T=sr=g.exports;g={};for(let[P,F]of Object.entries(T))typeof F=="function"?(T=Uw(F),g[P]=T):g[P]=F;return sr=g,sr=(function(){var P=sr,F=Y=>me=>Y(me)>>>0,$=Y=>()=>Y()>>>0;return(P=Object.assign({},P)).$b=F(P.$b),P.Cc=$(P.Cc),P.Ec=F(P.Ec),P.rd=(Y=>(me,J)=>Y(me,J)>>>0)(P.rd),P.wd=F(P.wd),P.xd=$(P.xd),P.Bd=F(P.Bd),P})(),eu.push(sr.id),Yu=(g=sr).$b,Ju=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,Ha=t._OrtGetWebGpuDevice=g.Bc,Mn=g.Cc,Ct=t._free=g.Dc,Qr=t._malloc=g.Ec,Ku=t._wgpuBufferRelease=g.Fc,Zu=t._wgpuCreateInstance=g.Gc,ed=g.Hc,td=g.Ic,rd=g.Jc,sd=g.Kc,nd=g.Lc,ad=g.Pc,od=g.Zc,id=g._c,ld=g.$c,Qa=g.bd,Xa=g.cd,Ya=g.dd,Ja=g.ed,Is=g.fd,Ka=g.gd,cd=g.hd,Za=g.kd,ud=g.ld,dd=g.md,hd=g.nd,eo=g.od,fd=g.pd,_d=g.qd,to=g.rd,fe=g.sd,Os=g.td,pd=g.ud,te=g.vd,xn=g.wd,re=g.xd,md=g.yd,ro=g.zd,gd=g.Ad,wd=g.Bd,vd=g.Cd,so=g.Dd,yd=g.Ed,bd=g.Fd,Md=g.Gd,xd=g.Hd,kd=g.Id,Td=g.Jd,Ed=g.Kd,Ad=g.Ld,Cd=g.Md,Sd=g.Nd,Pd=g.Od,Fd=g.Pd,Ld=g.Qd,Id=g.Rd,Od=g.Td,Nd=g.Ud,Dd=g.Vd,zd=g.Wd,Bd=g.Yd,Rd=g.Zd,Gd=g._d,$d=g.$d,Vd=g.ae,Ud=g.oe,jd=g.pe,qd=g.qe,Wd=g.re,Hd=g.se,Qd=g.te,Xd=g.ue,Yd=g.ve,Jd=g.we,Kd=g.xe,Zd=g.ye,eh=g.Ye,th=g.Ze,rh=g._e,sh=g.$e,_=b,sr}var f,m=oe();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(m,(b,T)=>{g(u(b,T))})}):n?u(new WebAssembly.Instance(_,oe()),_):(D??=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-DMmc6YqF.wasm",import.meta.url).href,import.meta.url).href,f=await(async function(g){var b=D;if(!h&&!L(b))try{var T=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(P){E(`wasm streaming compile failed: ${P}`),E("falling back to ArrayBuffer instantiation")}return(async function(P,F){try{var $=await(async function(Y){if(!h)try{var me=await o(Y);return new Uint8Array(me)}catch{}if(Y==D&&h)Y=new Uint8Array(h);else{if(!i)throw"both async and sync fetching of the wasm failed";Y=i(Y)}return Y})(P);return await WebAssembly.instantiate($,F)}catch(Y){E(`failed to asynchronously prepare wasm: ${Y}`),ke(Y)}})(b,g)})(m),u(f.instance,f.module))}class Le{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var Qe=u=>{u.terminate(),u.onmessage=()=>{}},dt=[],Se=0,ve=null,nt=u=>{dr.length==0&&(nu(),su(dr[0]));var f=dr.pop();if(!f)return 6;Ps.push(f),Tr[u.Nc]=f,f.Nc=u.Nc;var m={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return f.postMessage(m,u.Yc),0},be=0,Me=(u,f,...m)=>{var g,b=16*m.length,T=re(),P=xn(b),F=P>>>3;for(g of m)typeof g=="bigint"?((x(),ee)[F++>>>0]=1n,(x(),ee)[F++>>>0]=g):((x(),ee)[F++>>>0]=0n,(x(),Q)[F++>>>0]=g);return u=dd(u,0,b,P,f),te(T),u};function Vr(u){if(n)return Me(0,1,u);if(p=u,!(0<be)){for(var f of Ps)Qe(f);for(f of dr)Qe(f);dr=[],Ps=[],Tr={},C=!0}l(0,new Le(u))}function Ss(u){if(n)return Me(1,0,u);Ur(u)}var Ur=u=>{if(p=u,n)throw Ss(u),"unwind";Vr(u)},dr=[],Ps=[],eu=[],Tr={},tu=u=>{var f=u.Nc;delete Tr[f],dr.push(u),Ps.splice(Ps.indexOf(u),1),u.Nc=0,hd(f)};function ru(){eu.forEach(u=>u())}var su=u=>new Promise(f=>{u.onmessage=b=>{var T=b.data;if(b=T.Oc,T.Vc&&T.Vc!=Mn()){var P=Tr[T.Vc];P?P.postMessage(T,T.Yc):E(`Internal error! Worker sent a message "${b}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?mn():b==="spawnThread"?nt(T):b==="cleanupThread"?ht(()=>{tu(Tr[T.he])}):b==="loaded"?(u.loaded=!0,f(u)):T.target==="setimmediate"?u.postMessage(T):b==="uncaughtException"?u.onerror(T.error):b==="callHandler"?t[T.be](...T.args):b&&E(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw E(`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({Oc:"load",ce:g,ie:hr,je:_})});function nu(){var u=new Worker((()=>{let f=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new f("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});dr.push(u)}var hr,lw=(u,f)=>{be=0,u=so(u,f),0<be?p=u:eo(u)},_n=[],pn=0,Ze=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function cw(u){var f=new La(u>>>=0);return(x(),B)[f.Qc+12>>>0]==0&&(au(f,!0),pn--),ou(f,!1),_n.push(f),wd(u)}var jr=0,uw=()=>{fe(0,0);var u=_n.pop();md(u.Xc),jr=0};function au(u,f){f=f?1:0,(x(),B)[u.Qc+12>>>0]=f}function ou(u,f){f=f?1:0,(x(),B)[u.Qc+13>>>0]=f}class La{constructor(f){this.Xc=f,this.Qc=f-24}}var Ia=u=>{var f=jr;if(!f)return Os(0),0;var m=new La(f);(x(),O)[m.Qc+16>>>2>>>0]=f;var g=(x(),O)[m.Qc+4>>>2>>>0];if(!g)return Os(0),f;for(var b of u){if(b===0||b===g)break;if(gd(b,g,m.Qc+16))return Os(b),f}return Os(g),f};function dw(){return Ia([])}function hw(u){return Ia([u>>>0])}function fw(u,f,m,g){return Ia([u>>>0,f>>>0,m>>>0,g>>>0])}var _w=()=>{var u=_n.pop();u||ke("no exception to throw");var f=u.Xc;throw(x(),B)[u.Qc+13>>>0]==0&&(_n.push(u),ou(u,!0),au(u,!1),pn++),ro(f),jr=f};function pw(u,f,m){var g=new La(u>>>=0);throw f>>>=0,m>>>=0,(x(),O)[g.Qc+16>>>2>>>0]=0,(x(),O)[g.Qc+4>>>2>>>0]=f,(x(),O)[g.Qc+8>>>2>>>0]=m,ro(u),pn++,jr=u}var mw=()=>pn;function iu(u,f,m,g){return n?Me(2,1,u,f,m,g):lu(u,f,m,g)}function lu(u,f,m,g){if(u>>>=0,f>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?iu(u,f,m,g):(u={fe:m,Nc:u,Wc:g,Yc:b},n?(u.Oc="spawnThread",postMessage(u,b),0):nt(u))}function gw(u){throw jr||=u>>>0,jr}var cu=globalThis.TextDecoder&&new TextDecoder,uu=(u,f,m,g)=>{if(m=f+m,g)return m;for(;u[f]&&!(f>=m);)++f;return f},du=(u,f=0,m,g)=>{if(16<(m=uu(u,f>>>=0,m,g))-f&&u.buffer&&cu)return cu.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 T=63&u[f++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|T);else{var P=63&u[f++];65536>(b=(240&b)==224?(15&b)<<12|T<<6|P:(7&b)<<18|T<<12|P<<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},qr=(u,f,m)=>(u>>>=0)?du((x(),j),u,f,m):"";function hu(u,f,m){return n?Me(3,1,u,f,m):0}function fu(u,f){if(n)return Me(4,1,u,f)}function _u(u,f){if(n)return Me(5,1,u,f)}function pu(u,f,m){if(n)return Me(6,1,u,f,m)}function mu(u,f,m){return n?Me(7,1,u,f,m):0}function gu(u,f){if(n)return Me(8,1,u,f)}function wu(u,f,m){if(n)return Me(9,1,u,f,m)}function vu(u,f,m,g){if(n)return Me(10,1,u,f,m,g)}function yu(u,f,m,g){if(n)return Me(11,1,u,f,m,g)}function bu(u,f,m,g){if(n)return Me(12,1,u,f,m,g)}function Mu(u){if(n)return Me(13,1,u)}function xu(u,f){if(n)return Me(14,1,u,f)}function ku(u,f,m){if(n)return Me(15,1,u,f,m)}var ww=()=>ke(""),Gt=u=>{u>>>=0;for(var f="";;){var m=(x(),j)[u++>>>0];if(!m)return f;f+=String.fromCharCode(m)}},Oa={},Na={},Wr=class extends Error{constructor(u){super(u),this.name="BindingError"}};function Kt(u,f,m={}){return(function(g,b,T={}){var P=b.name;if(!g)throw new Wr(`type "${P}" must have a positive integer typeid pointer`);if(Na.hasOwnProperty(g)){if(T.de)return;throw new Wr(`Cannot register type '${P}' twice`)}Na[g]=b,Oa.hasOwnProperty(g)&&(b=Oa[g],delete Oa[g],b.forEach(F=>F()))})(u,f,m)}var Tu=(u,f,m)=>{switch(f){case 1:return m?g=>(x(),B)[g>>>0]:g=>(x(),j)[g>>>0];case 2:return m?g=>(x(),X)[g>>>1>>>0]:g=>(x(),W)[g>>>1>>>0];case 4:return m?g=>(x(),N)[g>>>2>>>0]:g=>(x(),O)[g>>>2>>>0];case 8:return m?g=>(x(),ee)[g>>>3>>>0]:g=>(x(),I)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function vw(u,f,m,g,b){u>>>=0,m>>>=0,f=Gt(f>>>0);let T=P=>P;if(g=g===0n){let P=8*m;T=F=>BigInt.asUintN(P,F),b=T(b)}Kt(u,{name:f,Mc:T,Sc:(P,F)=>(typeof F=="number"&&(F=BigInt(F)),F),Rc:Tu(f,m,!g),Tc:null})}function yw(u,f,m,g){Kt(u>>>=0,{name:f=Gt(f>>>0),Mc:function(b){return!!b},Sc:function(b,T){return T?m:g},Rc:function(b){return this.Mc((x(),j)[b>>>0])},Tc:null})}var Eu=[],Er=[0,1,,1,null,1,!0,1,!1,1];function Da(u){9<(u>>>=0)&&--Er[u+1]==0&&(Er[u]=void 0,Eu.push(u))}var bt=u=>{if(!u)throw new Wr(`Cannot use deleted val. handle = ${u}`);return Er[u]},At=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Eu.pop()||Er.length;return Er[f]=u,Er[f+1]=1,f}};function za(u){return this.Mc((x(),O)[u>>>2>>>0])}var bw={name:"emscripten::val",Mc:u=>{var f=bt(u);return Da(u),f},Sc:(u,f)=>At(f),Rc:za,Tc:null};function Mw(u){return Kt(u>>>0,bw)}var xw=(u,f)=>{switch(f){case 4:return function(m){return this.Mc((x(),U)[m>>>2>>>0])};case 8:return function(m){return this.Mc((x(),Q)[m>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function kw(u,f,m){m>>>=0,Kt(u>>>=0,{name:f=Gt(f>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:xw(f,m),Tc:null})}function Tw(u,f,m,g,b){u>>>=0,m>>>=0,f=Gt(f>>>0);let T=F=>F;if(g===0){var P=32-8*m;T=F=>F<<P>>>P,b=T(b)}Kt(u,{name:f,Mc:T,Sc:(F,$)=>$,Rc:Tu(f,m,g!==0),Tc:null})}function Ew(u,f,m){function g(T){var P=(x(),O)[T>>>2>>>0];return T=(x(),O)[T+4>>>2>>>0],new b((x(),B).buffer,T,P)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];Kt(u>>>=0,{name:m=Gt(m>>>0),Mc:g,Rc:g},{de:!0})}var Zt=(u,f,m)=>{var g=(x(),j);if(f>>>=0,0<m){var b=f;m=f+m-1;for(var T=0;T<u.length;++T){var P=u.codePointAt(T);if(127>=P){if(f>=m)break;g[f++>>>0]=P}else if(2047>=P){if(f+1>=m)break;g[f++>>>0]=192|P>>6,g[f++>>>0]=128|63&P}else if(65535>=P){if(f+2>=m)break;g[f++>>>0]=224|P>>12,g[f++>>>0]=128|P>>6&63,g[f++>>>0]=128|63&P}else{if(f+3>=m)break;g[f++>>>0]=240|P>>18,g[f++>>>0]=128|P>>12&63,g[f++>>>0]=128|P>>6&63,g[f++>>>0]=128|63&P,T++}}g[f>>>0]=0,u=f-b}else u=0;return u},er=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 Aw(u,f){Kt(u>>>=0,{name:f=Gt(f>>>0),Mc(m){var g=(x(),O)[m>>>2>>>0];return g=qr(m+4,g,!0),Ct(m),g},Sc(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 Wr("Cannot pass non-string to std::string");var T=b?er(g):g.length,P=Qr(4+T+1),F=P+4;return(x(),O)[P>>>2>>>0]=T,b?Zt(g,F,T+1):(x(),j).set(g,F>>>0),m!==null&&m.push(Ct,P),P},Rc:za,Tc(m){Ct(m)}})}var Au=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Cw=(u,f,m)=>{if(u>>>=1,16<(f=uu((x(),W),u,f/2,m))-u&&Au)return Au.decode((x(),W).slice(u,f));for(m="";u<f;++u){var g=(x(),W)[u>>>0];m+=String.fromCharCode(g)}return m},Sw=(u,f,m)=>{if(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 T=u.charCodeAt(b);(x(),X)[f>>>1>>>0]=T,f+=2}return(x(),X)[f>>>1>>>0]=0,f-g},Pw=u=>2*u.length,Fw=(u,f,m)=>{var g="";u>>>=2;for(var b=0;!(b>=f/4);b++){var T=(x(),O)[u+b>>>0];if(!T&&!m)break;g+=String.fromCodePoint(T)}return g},Lw=(u,f,m)=>{if(f>>>=0,m??=2147483647,4>m)return 0;var g=f;m=g+m-4;for(var b=0;b<u.length;++b){var T=u.codePointAt(b);if(65535<T&&b++,(x(),N)[f>>>2>>>0]=T,(f+=4)+4>m)break}return(x(),N)[f>>>2>>>0]=0,f-g},Iw=u=>{for(var f=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,f+=4;return f};function Ow(u,f,m){if(u>>>=0,f>>>=0,m=Gt(m>>>=0),f===2)var g=Cw,b=Sw,T=Pw;else g=Fw,b=Lw,T=Iw;Kt(u,{name:m,Mc:P=>{var F=(x(),O)[P>>>2>>>0];return F=g(P+4,F*f,!0),Ct(P),F},Sc:(P,F)=>{if(typeof F!="string")throw new Wr(`Cannot pass non-string to C++ string type ${m}`);var $=T(F),Y=Qr(4+$+f);return(x(),O)[Y>>>2>>>0]=$/f,b(F,Y+4,$+f),P!==null&&P.push(Ct,Y),Y},Rc:za,Tc(P){Ct(P)}})}function Nw(u,f){Kt(u>>>=0,{ee:!0,name:f=Gt(f>>>0),Mc:()=>{},Sc:()=>{}})}function Dw(u){Za(u>>>0,!s,1,!r,131072,!1),ru()}var ht=u=>{if(!C)try{if(u(),!(0<be))try{n?Mn()&&eo(p):Ur(p)}catch(f){f instanceof Le||f=="unwind"||l(0,f)}}catch(f){f instanceof Le||f=="unwind"||l(0,f)}},zw=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ba(u){u>>>=0,zw||(Atomics.waitAsync((x(),N),u>>>2,u).value.then(mn),u+=128,Atomics.store((x(),N),u>>>2,1))}var mn=()=>ht(()=>{var u=Mn();u&&(Ba(u),_d())});function Bw(u,f){(u>>>=0)==f>>>0?setTimeout(mn):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Tr[u])&&u.postMessage({Oc:"checkMailbox"})}var Ra=[];function Rw(u,f,m,g,b){for(f>>>=0,b>>>=0,Ra.length=0,m=b>>>3,g=b+g>>>3;m<g;){var T;T=(x(),ee)[m++>>>0]?(x(),ee)[m++>>>0]:(x(),Q)[m++>>>0],Ra.push(T)}return(f?no[f]:My[u])(...Ra)}var Gw=()=>{be=0};function $w(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):tu(Tr[u])}function Vw(u){}var gn=u=>{try{u()}catch(f){ke(f)}};function Uw(u){var f=(...m)=>{wn.push(u);try{return u(...m)}finally{C||(wn.pop(),$t&&fr===1&&wn.length===0&&(fr=0,be+=1,gn(th),typeof Fibers<"u"&&Fibers.Be()))}};return Pu.set(u,f),f}var fr=0,$t=null,Cu=0,wn=[],Ga=new Map,Su=new Map,Pu=new Map,jw=0,$a=null,qw=[],Fu=u=>(function(f){if(!C){if(fr===0){var m=!1,g=!1;f((b=0)=>{if(!C&&(Cu=b,m=!0,g)){fr=2,gn(()=>rh($t)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var T=(function(){var $=(x(),N)[$t+8>>>2>>>0];return $=Su.get($),$=Pu.get($),--be,$()})()}catch($){T=$,b=!0}var P=!1;if(!$t){var F=$a;F&&($a=null,(b?F.reject:F.resolve)(T),P=!0)}if(b&&!P)throw T}}),g=!0,m||(fr=1,$t=(function(){var b=Qr(65548),T=b+12;if((x(),O)[b>>>2>>>0]=T,(x(),O)[b+4>>>2>>>0]=T+65536,T=wn[0],!Ga.has(T)){var P=jw++;Ga.set(T,P),Su.set(P,T)}return T=Ga.get(T),(x(),N)[b+8>>>2>>>0]=T,b})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),gn(()=>eh($t)))}else fr===2?(fr=0,gn(sh),Ct($t),$t=null,qw.forEach(ht)):ke(`invalid state: ${fr}`);return Cu}})(f=>{u().then(f)});function Ww(u){return u>>>=0,Fu(async()=>{var f=await bt(u);return At(f)})}var Va=[],Hw=u=>{var f=Va.length;return Va.push(u),f},Qw=(u,f)=>{for(var m=Array(u),g=0;g<u;++g){var b=g,T=(x(),O)[f+4*g>>>2>>>0],P=Na[T];if(P===void 0)throw u=`parameter ${g}`,T=Yu(T),f=Gt(T),Ct(T),new Wr(`${u} has unknown type ${f}`);m[b]=P}return m},Xw=(u,f,m)=>{var g=[];return u=u(g,m),g.length&&((x(),O)[f>>>2>>>0]=At(g)),u},Yw={},vn=u=>{var f=Yw[u];return f===void 0?Gt(u):f};function Jw(u,f,m){var[g,...b]=Qw(u,f>>>0);f=g.Sc.bind(g);var T=b.map($=>$.Rc.bind($));u--;var P={toValue:bt};switch(u=T.map(($,Y)=>{var me=`argFromPtr${Y}`;return P[me]=$,`${me}(args${Y?"+"+8*Y:""})`}),m){case 0:var F="toValue(handle)";break;case 2:F="new (toValue(handle))";break;case 3:F="";break;case 1:P.getStringOrSymbol=vn,F="toValue(handle)[getStringOrSymbol(methodName)]"}return F+=`(${u})`,g.ee||(P.toReturnWire=f,P.emval_returnValue=Xw,F=`return emval_returnValue(toReturnWire, destructorsRef, ${F})`),F=`return function (handle, methodName, destructorsRef, args) {
|
|
2
|
+
${F}
|
|
3
|
+
}`,m=new Function(Object.keys(P),F)(...Object.values(P)),F=`methodCaller<(${b.map($=>$.name)}) => ${g.name}>`,Hw(Object.defineProperty(m,"name",{value:F}))}function Kw(u,f){return f>>>=0,(u=bt(u>>>0))==bt(f)}function Zw(u){return(u>>>=0)?(u=vn(u),At(globalThis[u])):At(globalThis)}function ev(u){return u=vn(u>>>0),At(t[u])}function tv(u,f){return f>>>=0,u=bt(u>>>0),f=bt(f),At(u[f])}function rv(u){9<(u>>>=0)&&(Er[u+1]+=1)}function Lu(u,f,m,g,b){return Va[u>>>0](f>>>0,m>>>0,g>>>0,b>>>0)}function sv(u,f,m,g,b){return Lu(u>>>0,f>>>0,m>>>0,g>>>0,b>>>0)}function nv(){return At([])}function av(u){u=bt(u>>>0);for(var f=Array(u.length),m=0;m<u.length;m++)f[m]=u[m];return At(f)}function ov(u){return At(vn(u>>>0))}function iv(){return At({})}function lv(u){for(var f=bt(u>>>=0);f.length;){var m=f.pop();f.pop()(m)}Da(u)}function cv(u,f,m){f>>>=0,m>>>=0,u=bt(u>>>0),f=bt(f),m=bt(m),u[f]=m}function uv(u,f){u=Ze(u),f>>>=0,u=new Date(1e3*u),(x(),N)[f>>>2>>>0]=u.getUTCSeconds(),(x(),N)[f+4>>>2>>>0]=u.getUTCMinutes(),(x(),N)[f+8>>>2>>>0]=u.getUTCHours(),(x(),N)[f+12>>>2>>>0]=u.getUTCDate(),(x(),N)[f+16>>>2>>>0]=u.getUTCMonth(),(x(),N)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(x(),N)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),N)[f+28>>>2>>>0]=u}var Iu=u=>u%4==0&&(u%100!=0||u%400==0),Ou=[0,31,60,91,121,152,182,213,244,274,305,335],Nu=[0,31,59,90,120,151,181,212,243,273,304,334];function dv(u,f){u=Ze(u),f>>>=0,u=new Date(1e3*u),(x(),N)[f>>>2>>>0]=u.getSeconds(),(x(),N)[f+4>>>2>>>0]=u.getMinutes(),(x(),N)[f+8>>>2>>>0]=u.getHours(),(x(),N)[f+12>>>2>>>0]=u.getDate(),(x(),N)[f+16>>>2>>>0]=u.getMonth(),(x(),N)[f+20>>>2>>>0]=u.getFullYear()-1900,(x(),N)[f+24>>>2>>>0]=u.getDay();var m=(Iu(u.getFullYear())?Ou:Nu)[u.getMonth()]+u.getDate()-1|0;(x(),N)[f+28>>>2>>>0]=m,(x(),N)[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)),(x(),N)[f+32>>>2>>>0]=u}function hv(u){u>>>=0;var f=new Date((x(),N)[u+20>>>2>>>0]+1900,(x(),N)[u+16>>>2>>>0],(x(),N)[u+12>>>2>>>0],(x(),N)[u+8>>>2>>>0],(x(),N)[u+4>>>2>>>0],(x(),N)[u>>>2>>>0],0),m=(x(),N)[u+32>>>2>>>0],g=f.getTimezoneOffset(),b=new Date(f.getFullYear(),6,1).getTimezoneOffset(),T=new Date(f.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(T,b);return 0>m?(x(),N)[u+32>>>2>>>0]=+(b!=T&&P==g):0<m!=(P==g)&&(b=Math.max(T,b),f.setTime(f.getTime()+6e4*((0<m?P:b)-g))),(x(),N)[u+24>>>2>>>0]=f.getDay(),m=(Iu(f.getFullYear())?Ou:Nu)[f.getMonth()]+f.getDate()-1|0,(x(),N)[u+28>>>2>>>0]=m,(x(),N)[u>>>2>>>0]=f.getSeconds(),(x(),N)[u+4>>>2>>>0]=f.getMinutes(),(x(),N)[u+8>>>2>>>0]=f.getHours(),(x(),N)[u+12>>>2>>>0]=f.getDate(),(x(),N)[u+16>>>2>>>0]=f.getMonth(),(x(),N)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function Du(u,f,m,g,b,T,P){return n?Me(16,1,u,f,m,g,b,T,P):-52}function zu(u,f,m,g,b,T){if(n)return Me(17,1,u,f,m,g,b,T)}var Fs={},fv=()=>performance.timeOrigin+performance.now();function Bu(u,f){if(n)return Me(18,1,u,f);if(Fs[u]&&(clearTimeout(Fs[u].id),delete Fs[u]),!f)return 0;var m=setTimeout(()=>{delete Fs[u],ht(()=>fd(u,performance.timeOrigin+performance.now()))},f);return Fs[u]={id:m,Ae:f},0}function _v(u,f,m,g){u>>>=0,f>>>=0,m>>>=0,g>>>=0;var b=new Date().getFullYear(),T=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var P=Math.max(T,b);(x(),O)[u>>>2>>>0]=60*P,(x(),N)[f>>>2>>>0]=+(T!=b),u=(f=F=>{var $=Math.abs(F);return`UTC${0<=F?"-":"+"}${String(Math.floor($/60)).padStart(2,"0")}${String($%60).padStart(2,"0")}`})(T),f=f(b),b<T?(Zt(u,m,17),Zt(f,g,17)):(Zt(u,g,17),Zt(f,m,17))}var pv=()=>Date.now();function mv(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),(x(),ee)[m>>>3>>>0]=BigInt(u),0):28}var Ua=[],Ru=(u,f)=>{Ua.length=0;for(var m;m=(x(),j)[u++>>>0];){var g=m!=105;f+=(g&=m!=112)&&f%8?4:0,Ua.push(m==112?(x(),O)[f>>>2>>>0]:m==106?(x(),ee)[f>>>3>>>0]:m==105?(x(),N)[f>>>2>>>0]:(x(),Q)[f>>>3>>>0]),f+=g?8:4}return Ua};function gv(u,f,m){return u>>>=0,f=Ru(f>>>0,m>>>0),no[u](...f)}function wv(u,f,m){return u>>>=0,f=Ru(f>>>0,m>>>0),no[u](...f)}var vv=()=>{};function yv(u,f){return E(qr(u>>>0,f>>>0))}var bv=()=>{throw be+=1,"unwind"};function Mv(){return 4294901760}var xv=()=>1,kv=()=>navigator.hardwareConcurrency;function Tv(u){u>>>=0;var f=(x(),j).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))-hr.buffer.byteLength+65535)/65536|0;try{hr.grow(g),H();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var Vt=u=>{var f=er(u)+1,m=xn(f);return Zt(u,m,f),m},ja=(u,f)=>{(x(),O)[u>>>2>>>0]=f;var m=(x(),O)[u>>>2>>>0];(x(),O)[u+4>>>2>>>0]=(f-m)/4294967296},Ls=u=>(x(),O)[u>>>2>>>0]+4294967296*(x(),N)[u+4>>>2>>>0],et=[],Ev=(u,f)=>{et[u>>>0]=f},tr=[],yn=[],Hr=(u,f)=>{yn[u]=new Promise(m=>f.finally(()=>m(u)))},Z=u=>{if(u)return et[u>>>0]},Av=(u,f)=>{for(u=(x(),O)[u>>>2>>>0];u;u=(x(),O)[u>>>2>>>0])f[(x(),N)[u+4>>>2>>>0]](u)},bn=(u,f,m)=>{(x(),O)[u>>>2>>>0]=f,(x(),O)[u+4>>>2>>>0]=m},Gu=u=>{var f=(x(),O)[u>>>2>>>0];return u=(x(),O)[u+4>>>2>>>0],qr(f,u)},rr=u=>{var f=(x(),O)[u>>>2>>>0];return u=(x(),O)[u+4>>>2>>>0],f?qr(f,u):u===0?"":void 0},Cv=u=>{var f=rr(u+4),m=(m=(x(),O)[u+12>>>2>>>0])?Z(m):"auto";if(u+=16){var g=Z((x(),O)[u+4>>>2>>>0]),b=(x(),O)[u+16>>>2>>>0],T=(x(),O)[u+20>>>2>>>0];if(b){for(var P={},F=0;F<b;++F){var $=T+24*F;P[Gu($+4)]=(x(),Q)[$+16>>>3>>>0]}b=P}else b=void 0;u={module:g,constants:b,entryPoint:rr(u+8)}}else u=void 0;return{label:f,layout:m,compute:u}},$u=(u,f)=>{function m(g,b){g=u[g],(x(),O)[f+b>>>2>>>0]=g}m("maxTextureDimension1D",4),m("maxTextureDimension2D",8),m("maxTextureDimension3D",12),m("maxTextureArrayLayers",16),m("maxBindGroups",20),m("maxBindGroupsPlusVertexBuffers",24),m("maxBindingsPerBindGroup",28),m("maxDynamicUniformBuffersPerPipelineLayout",32),m("maxDynamicStorageBuffersPerPipelineLayout",36),m("maxSampledTexturesPerShaderStage",40),m("maxSamplersPerShaderStage",44),m("maxStorageBuffersPerShaderStage",48),m("maxStorageTexturesPerShaderStage",52),m("maxUniformBuffersPerShaderStage",56),m("minUniformBufferOffsetAlignment",80),m("minStorageBufferOffsetAlignment",84),ja(f+64,u.maxUniformBufferBindingSize),ja(f+72,u.maxStorageBufferBindingSize),m("maxVertexBuffers",88),ja(f+96,u.maxBufferSize),m("maxVertexAttributes",104),m("maxVertexBufferArrayStride",108),m("maxInterStageShaderVariables",112),m("maxColorAttachments",116),m("maxColorAttachmentBytesPerSample",120),m("maxComputeWorkgroupStorageSize",124),m("maxComputeInvocationsPerWorkgroup",128),m("maxComputeWorkgroupSizeX",132),m("maxComputeWorkgroupSizeY",136),m("maxComputeWorkgroupSizeZ",140),m("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&m("maxImmediateSize",148)},Sv=[,"validation","out-of-memory","internal"],Pv=[,"compatibility","core"],Vu={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},Fv=[,"low-power","high-performance"],Lv=[,"occlusion","timestamp"],Iv={undefined:1,unknown:1,destroyed:2};function Ov(u,f,m,g,b,T){f=Ze(f),m=Ze(m),g>>>=0,b>>>=0,T>>>=0;var P=Z(u>>>0);if(u={},T){var F=(x(),O)[T+12>>>2>>>0];if(F){var $=(x(),O)[T+16>>>2>>>0];u.requiredFeatures=Array.from((x(),O).subarray($>>>2>>>0,$+4*F>>>2>>>0),J=>Vu[J])}var Y=(x(),O)[T+20>>>2>>>0];if(Y){let J=function(Fe,Xe,Ns=!1){Xe=Y+Xe,(Xe=(x(),O)[Xe>>>2>>>0])==4294967295||Ns&&Xe==0||(me[Fe]=Xe)},ue=function(Fe,Xe){Xe=Y+Xe;var Ns=(x(),O)[Xe>>>2>>>0],ao=(x(),O)[Xe+4>>>2>>>0];Ns==4294967295&&ao==4294967295||(me[Fe]=Ls(Xe))};var me={};J("maxTextureDimension1D",4),J("maxTextureDimension2D",8),J("maxTextureDimension3D",12),J("maxTextureArrayLayers",16),J("maxBindGroups",20),J("maxBindGroupsPlusVertexBuffers",24),J("maxDynamicUniformBuffersPerPipelineLayout",32),J("maxDynamicStorageBuffersPerPipelineLayout",36),J("maxSampledTexturesPerShaderStage",40),J("maxSamplersPerShaderStage",44),J("maxStorageBuffersPerShaderStage",48),J("maxStorageTexturesPerShaderStage",52),J("maxUniformBuffersPerShaderStage",56),J("minUniformBufferOffsetAlignment",80),J("minStorageBufferOffsetAlignment",84),ue("maxUniformBufferBindingSize",64),ue("maxStorageBufferBindingSize",72),J("maxVertexBuffers",88),ue("maxBufferSize",96),J("maxVertexAttributes",104),J("maxVertexBufferArrayStride",108),J("maxInterStageShaderVariables",112),J("maxColorAttachments",116),J("maxColorAttachmentBytesPerSample",120),J("maxComputeWorkgroupStorageSize",124),J("maxComputeInvocationsPerWorkgroup",128),J("maxComputeWorkgroupSizeX",132),J("maxComputeWorkgroupSizeY",136),J("maxComputeWorkgroupSizeZ",140),J("maxComputeWorkgroupsPerDimension",144),J("maxImmediateSize",148,!0),u.requiredLimits=me}(F=(x(),O)[T+24>>>2>>>0])&&(F={label:rr(F+4)},u.defaultQueue=F),u.label=rr(T+4)}be+=1,Hr(f,P.requestDevice(u).then(J=>{--be,ht(()=>{et[b>>>0]=J.queue,et[g>>>0]=J,be+=1,Hr(m,J.lost.then(ue=>{ht(()=>{J.onuncapturederror=()=>{};var Fe=re(),Xe=Vt(ue.message);Xa(m,Iv[ue.reason],Xe),te(Fe)}),--be})),J.onuncapturederror=ue=>{var Fe=5;ue.error instanceof GPUValidationError?Fe=2:ue.error instanceof GPUOutOfMemoryError?Fe=3:ue.error instanceof GPUInternalError&&(Fe=4);var Xe=re();ue=Vt(ue.error.message),cd(g,Fe,ue),te(Xe)},"adapterInfo"in J||(J.adapterInfo=P.info),Ka(f,1,g,0)})},J=>{--be,ht(()=>{var ue=re(),Fe=Vt(J.message);Ka(f,3,g,Fe),m&&Xa(m,4,Fe),te(ue)})}))}function Nv(u){var f=Z(u>>>=0),m=tr[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete tr[u]}f.destroy()}function Dv(u,f,m){m>>>=0;var g=Z(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var T=to(16,b.byteLength);return(x(),j).set(new Uint8Array(b),T>>>0),tr[u].push(()=>Ct(T)),T}function zv(u,f,m){m>>>=0;var g=Z(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var T=to(16,b.byteLength);return(x(),j).fill(0,T,b.byteLength),tr[u].push(()=>{new Uint8Array(b).set((x(),j).subarray(T>>>0,T+b.byteLength>>>0)),Ct(T)}),T}function Bv(u,f,m,g,b){u>>>=0,f=Ze(f),m=Ze(m),b>>>=0;var T=Z(u);tr[u]=[],b==4294967295&&(b=void 0),be+=1,Hr(f,T.mapAsync(m,g>>>0,b).then(()=>{--be,ht(()=>{Ya(f,1,0)})},P=>{--be,ht(()=>{re();var F=Vt(P.message);Ya(f,P.name==="AbortError"?4:P.name==="OperationError"?3:0,F),delete tr[u]})}))}function Rv(u){var f=Z(u>>>=0),m=tr[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete tr[u],f.unmap()}}function Gv(u){delete et[u>>>0]}function $v(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=!!(x(),O)[f+32>>>2>>>0];f={label:rr(f+4),usage:(x(),O)[f+16>>>2>>>0],size:Ls(f+24),mappedAtCreation:g},u=Z(u);try{var b=u.createBuffer(f)}catch{return!1}return et[m>>>0]=b,g&&(tr[m]=[]),!0}function Vv(u,f,m,g){u>>>=0,f=Ze(f),g>>>=0,m=Cv(m>>>0),u=Z(u),be+=1,Hr(f,u.createComputePipelineAsync(m).then(b=>{--be,ht(()=>{et[g>>>0]=b,Qa(f,1,g,0)})},b=>{--be,ht(()=>{var T=re(),P=Vt(b.message);Qa(f,b.reason==="validation"?3:b.reason==="internal"?4:0,g,P),te(T)})}))}function Uv(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=(x(),O)[f>>>2>>>0],b=(x(),N)[g+4>>>2>>>0];f={label:rr(f+4),code:""},b===2&&(f.code=Gu(g+8)),u=Z(u).createShaderModule(f),et[m>>>0]=u}var jv=u=>{(u=Z(u)).onuncapturederror=null,u.destroy()};function qv(u,f){f=Ze(f),u=Z(u>>>0),be+=1,Hr(f,u.popErrorScope().then(m=>{--be,ht(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var b=re(),T=m?Vt(m.message):0;Ja(f,1,g,T),te(b)})},m=>{--be,ht(()=>{var g=re(),b=Vt(m.message);Ja(f,1,5,b),te(g)})}))}function Wv(u,f,m,g){if(f=Ze(f),g>>>=0,m>>>=0){var b={featureLevel:Pv[(x(),N)[m+4>>>2>>>0]],powerPreference:Fv[(x(),N)[m+8>>>2>>>0]],forceFallbackAdapter:!!(x(),O)[m+12>>>2>>>0]};(u=(x(),O)[m>>>2>>>0])!==0&&(x(),b.De=!!(x(),O)[u+8>>>2>>>0])}"gpu"in navigator?(be+=1,Hr(f,navigator.gpu.requestAdapter(b).then(T=>{--be,ht(()=>{if(T)et[g>>>0]=T,Is(f,1,g,0);else{var P=re(),F=Vt("WebGPU not available on this browser (requestAdapter returned null)");Is(f,3,g,F),te(P)}})},T=>{--be,ht(()=>{var P=re(),F=Vt(T.message);Is(f,4,g,F),te(P)})}))):(b=re(),u=Vt("WebGPU not available on this browser (navigator.gpu is not available)"),Is(f,3,g,u),te(b))}function Hv(u,f,m){return u>>>=0,f>>>=0,m>>>=0,Fu(async()=>{var g=[];if(m){var b=(x(),N)[m>>>2>>>0];g.length=f+1,g[f]=new Promise(F=>setTimeout(F,b,0))}else g.length=f;for(var T=0;T<f;++T){var P=Ls(u+8*T);if(!(P in yn))return P;g[T]=yn[P]}return g=await Promise.race(g),delete yn[g],g})}var qa,Wa={},Uu=()=>{if(!qa){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Wa)Wa[u]===void 0?delete f[u]:f[u]=Wa[u];var m=[];for(u in f)m.push(`${u}=${f[u]}`);qa=m}return qa};function ju(u,f){if(n)return Me(19,1,u,f);u>>>=0,f>>>=0;var m,g=0,b=0;for(m of Uu()){var T=f+g;(x(),O)[u+b>>>2>>>0]=T,g+=Zt(m,T,1/0)+1,b+=4}return 0}function qu(u,f){if(n)return Me(20,1,u,f);u>>>=0,f>>>=0;var m=Uu();for(var g of((x(),O)[u>>>2>>>0]=m.length,u=0,m))u+=er(g)+1;return(x(),O)[f>>>2>>>0]=u,0}function Wu(u){return n?Me(21,1,u):52}function Hu(u,f,m,g){return n?Me(22,1,u,f,m,g):52}function Qu(u,f,m,g){return n?Me(23,1,u,f,m,g):70}var Qv=[null,[],[]];function Xu(u,f,m,g){if(n)return Me(24,1,u,f,m,g);f>>>=0,m>>>=0,g>>>=0;for(var b=0,T=0;T<m;T++){var P=(x(),O)[f>>>2>>>0],F=(x(),O)[f+4>>>2>>>0];f+=8;for(var $=0;$<F;$++){var Y=u,me=(x(),j)[P+$>>>0],J=Qv[Y];me===0||me===10?((Y===1?A:E)(du(J)),J.length=0):J.push(me)}b+=F}return(x(),O)[g>>>2>>>0]=b,0}function Xv(u){return u>>>0}function Yv(u,f){return $u(Z(u>>>0).limits,f>>>0),1}function Jv(u,f){return Z(u>>>0).features.has(Vu[f])}function Kv(u){return BigInt(Z(u>>>0).size)}function Zv(u){return BigInt(Z(u>>>0).usage)}function ey(u,f){if(u>>>=0,f>>>=0){var m=rr(f+4);m={label:m,timestampWrites:f=(f=(x(),O)[f+12>>>2>>>0])!==0?{querySet:Z((x(),O)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(x(),O)[f+8>>>2>>>0],endOfPassWriteIndex:(x(),O)[f+12>>>2>>>0]}:void 0}}return f=Z(u),u=nd(0),m=f.beginComputePass(m),et[u>>>0]=m,u}function ty(u,f,m,g){m=Ze(m),(g=Ze(g))==-1&&(g=void 0),(u=Z(u>>>0)).clearBuffer(Z(f>>>0),m,g)}function ry(u,f,m,g,b,T){m=Ze(m),b=Ze(b),T=Ze(T),Z(u>>>0).copyBufferToBuffer(Z(f>>>0),m,Z(g>>>0),b,T)}function sy(u){var f=Z(u>>>0);return u=rd(0),f=f.finish(),et[u>>>0]=f,u}function ny(u,f,m,g,b,T){T=Ze(T),Z(u>>>0).resolveQuerySet(Z(f>>>0),m,g,Z(b>>>0),T)}function ay(u,f,m,g){Z(u>>>0).dispatchWorkgroups(f,m,g)}function oy(u,f,m){m=Ze(m),Z(u>>>0).dispatchWorkgroupsIndirect(Z(f>>>0),m)}function iy(u){Z(u>>>0).end()}function ly(u,f,m,g,b){g>>>=0,b>>>=0,u=Z(u>>>0),m=Z(m>>>0),g==0?u.setBindGroup(f,m):u.setBindGroup(f,m,(x(),O),b>>>2,g)}function cy(u,f){Z(u>>>0).setPipeline(Z(f>>>0))}function uy(u,f,m){Z(u>>>0).Ce(Z(f>>>0),m)}function dy(u,f){var m=Z(u>>>0);return u=td(0),f=m.getBindGroupLayout(f),et[u>>>0]=f,u}function hy(u,f){function m(b){var T=(x(),O)[b+8>>>2>>>0],P=(x(),O)[b+32>>>2>>>0],F=(x(),O)[b+36>>>2>>>0],$=0;return Av(b,{327681:Y=>{$=(x(),O)[Y+8>>>2>>>0]}}),T?((P=Ls(b+24))==-1&&(P=void 0),T={buffer:Z(T),offset:Ls(b+16),size:P}):T=Z(P||F||$),{binding:(x(),O)[b+4>>>2>>>0],resource:T}}u>>>=0,f={label:rr(4+(f>>>=0)),layout:Z((x(),O)[f+12>>>2>>>0]),entries:(function(b,T){for(var P=[],F=0;F<b;++F)P.push(m(T+40*F));return P})((x(),O)[f+16>>>2>>>0],(x(),O)[f+20>>>2>>>0])},u=Z(u);var g=ed(0);return Ev(g,u.createBindGroup(f)),g}function fy(u,f){var m;return u>>>=0,(f>>>=0)&&(m={label:rr(f+4)}),f=Z(u),u=sd(0),m=f.createCommandEncoder(m),et[u>>>0]=m,u}function _y(u,f){u>>>=0,f>>>=0,f={type:Lv[(x(),N)[f+12>>>2>>>0]],count:(x(),O)[f+16>>>2>>>0]};var m=Z(u);return u=ad(0),f=m.createQuerySet(f),et[u>>>0]=f,u}function py(u,f){u=Z(u>>>0).adapterInfo,f>>>=0,(x(),O)[f+52>>>2>>>0]=u.subgroupMinSize,(x(),O)[f+56>>>2>>>0]=u.subgroupMaxSize;var m=u.vendor+u.architecture+u.device+u.description,g=er(m)+1,b=Qr(g);return b&&Zt(m,b,g),m=b,g=er(u.vendor),bn(f+4,m,g),m+=g,g=er(u.architecture),bn(f+12,m,g),m+=g,g=er(u.device),bn(f+20,m,g),bn(f+28,m+g,er(u.description)),(x(),N)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(x(),N)[f+40>>>2>>>0]=u,(x(),O)[f+44>>>2>>>0]=0,(x(),O)[f+48>>>2>>>0]=0,1}var my={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function gy(u,f){f>>>=0;var m=Z(u>>>0);u=Qr(4*m.features.size);var g=0,b=0;for(let T of m.features)0<=(m=my[T])&&((x(),N)[u+g>>>2>>>0]=m,g+=4,b++);(x(),O)[f+4>>>2>>>0]=u,(x(),O)[f>>>2>>>0]=b}function wy(u,f){return $u(Z(u>>>0).limits,f>>>0),1}function vy(u,f){Z(u>>>0).pushErrorScope(Sv[f])}function yy(u,f,m){f>>>=0,m>>>=0,u=Z(u>>>0),f=Array.from((x(),N).subarray(m>>>2>>>0,m+4*f>>>2>>>0),g=>Z(g)),u.submit(f)}function by(u,f,m,g,b){m=Ze(m),g>>>=0,b>>>=0,u=Z(u>>>0),f=Z(f>>>0),g=(x(),j).subarray(g>>>0,g+b>>>0),u.writeBuffer(f,m,g,0,b)}n||(function(){for(var u=t.numThreads-1;u--;)nu();dt.push(async()=>{var f=(async function(){if(!n)return Promise.all(dr.map(su))})();Se++,await f,--Se==0&&ve&&(f=ve,ve=null,f())})})(),n||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),H()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>re(),t.stackRestore=u=>te(u),t.stackAlloc=u=>xn(u),t.setValue=function(u,f,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":(x(),B)[u>>>0]=f;break;case"i16":(x(),X)[u>>>1>>>0]=f;break;case"i32":(x(),N)[u>>>2>>>0]=f;break;case"i64":(x(),ee)[u>>>3>>>0]=BigInt(f);break;case"float":(x(),U)[u>>>2>>>0]=f;break;case"double":(x(),Q)[u>>>3>>>0]=f;break;case"*":(x(),O)[u>>>2>>>0]=f;break;default:ke(`invalid type for setValue: ${m}`)}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(x(),B)[u>>>0];case"i16":return(x(),X)[u>>>1>>>0];case"i32":return(x(),N)[u>>>2>>>0];case"i64":return(x(),ee)[u>>>3>>>0];case"float":return(x(),U)[u>>>2>>>0];case"double":return(x(),Q)[u>>>3>>>0];case"*":return(x(),O)[u>>>2>>>0];default:ke(`invalid type for getValue: ${f}`)}},t.UTF8ToString=qr,t.stringToUTF8=Zt,t.lengthBytesUTF8=er;var Yu,Ju,Ha,Mn,Ct,Qr,Ku,Zu,ed,td,rd,sd,nd,ad,od,id,ld,Qa,Xa,Ya,Ja,Is,Ka,cd,Za,ud,dd,hd,eo,fd,_d,to,fe,Os,pd,te,xn,re,md,ro,gd,wd,vd,so,yd,bd,Md,xd,kd,Td,Ed,Ad,Cd,Sd,Pd,Fd,Ld,Id,Od,Nd,Dd,zd,Bd,Rd,Gd,$d,Vd,Ud,jd,qd,Wd,Hd,Qd,Xd,Yd,Jd,Kd,Zd,eh,th,rh,sh,sr,My=[Vr,Ss,iu,hu,fu,_u,pu,mu,gu,wu,vu,yu,bu,Mu,xu,ku,Du,zu,Bu,ju,qu,Wu,Hu,Qu,Xu],no={970348:(u,f,m,g,b)=>{if(t===void 0||!t.Uc)return 1;if((u=qr(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.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 T=u.subarray(f,f+m);switch(b){case 0:(x(),j).set(T,g>>>0);break;case 1:t.ad?t.ad(g,T):t.ne(g,T);break;default:return 4}return 0}catch{return 4}},971172:(u,f,m)=>{t.Sd(u,(x(),j).subarray(f>>>0,f+m>>>0))},971236:()=>t.le(),971278:u=>{t.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function xy(u,f,m,g){var b=re();try{return Ad(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function ky(u,f,m){var g=re();try{return kd(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;fe(1,0)}}function Ty(u){var f=re();try{yd(u)}catch(m){if(te(f),m!==m+0)throw m;fe(1,0)}}function Ey(u,f){var m=re();try{return so(u,f)}catch(g){if(te(m),g!==g+0)throw g;fe(1,0)}}function Ay(u,f,m){var g=re();try{vd(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;fe(1,0)}}function Cy(u,f){var m=re();try{Cd(u,f)}catch(g){if(te(m),g!==g+0)throw g;fe(1,0)}}function Sy(u,f,m,g,b,T,P){var F=re();try{return xd(u,f,m,g,b,T,P)}catch($){if(te(F),$!==$+0)throw $;fe(1,0)}}function Py(u,f,m,g,b,T){var P=re();try{bd(u,f,m,g,b,T)}catch(F){if(te(P),F!==F+0)throw F;fe(1,0)}}function Fy(u,f,m,g){var b=re();try{Ed(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function Ly(u,f,m,g,b,T,P){var F=re();try{Pd(u,f,m,g,b,T,P)}catch($){if(te(F),$!==$+0)throw $;fe(1,0)}}function Iy(u,f,m,g,b,T,P){var F=re();try{Fd(u,f,m,g,b,T,P)}catch($){if(te(F),$!==$+0)throw $;fe(1,0)}}function Oy(u,f,m,g,b,T,P,F){var $=re();try{Gd(u,f,m,g,b,T,P,F)}catch(Y){if(te($),Y!==Y+0)throw Y;fe(1,0)}}function Ny(u,f,m,g,b,T,P,F,$,Y,me,J){var ue=re();try{Ld(u,f,m,g,b,T,P,F,$,Y,me,J)}catch(Fe){if(te(ue),Fe!==Fe+0)throw Fe;fe(1,0)}}function Dy(u,f,m,g,b){var T=re();try{return Sd(u,f,m,g,b)}catch(P){if(te(T),P!==P+0)throw P;fe(1,0)}}function zy(u,f,m,g,b){var T=re();try{Md(u,f,m,g,b)}catch(P){if(te(T),P!==P+0)throw P;fe(1,0)}}function By(u,f,m,g,b,T,P,F){var $=re();try{Td(u,f,m,g,b,T,P,F)}catch(Y){if(te($),Y!==Y+0)throw Y;fe(1,0)}}function Ry(u){var f=re();try{return $d(u)}catch(m){if(te(f),m!==m+0)throw m;fe(1,0)}}function Gy(u,f,m){var g=re();try{return Vd(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;fe(1,0)}}function $y(u,f){var m=re();try{return Zd(u,f)}catch(g){if(te(m),g!==g+0)throw g;return fe(1,0),0n}}function Vy(u){var f=re();try{return Id(u)}catch(m){if(te(f),m!==m+0)throw m;return fe(1,0),0n}}function Uy(u,f,m,g){var b=re();try{return Ud(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function jy(u,f,m,g,b){var T=re();try{return jd(u,f,m,g,b)}catch(P){if(te(T),P!==P+0)throw P;fe(1,0)}}function qy(u,f,m,g,b,T){var P=re();try{return qd(u,f,m,g,b,T)}catch(F){if(te(P),F!==F+0)throw F;fe(1,0)}}function Wy(u,f,m,g,b,T){var P=re();try{return Bd(u,f,m,g,b,T)}catch(F){if(te(P),F!==F+0)throw F;fe(1,0)}}function Hy(u,f,m,g,b,T){var P=re();try{return Wd(u,f,m,g,b,T)}catch(F){if(te(P),F!==F+0)throw F;fe(1,0)}}function Qy(u,f,m,g,b,T,P,F){var $=re();try{return Rd(u,f,m,g,b,T,P,F)}catch(Y){if(te($),Y!==Y+0)throw Y;fe(1,0)}}function Xy(u,f,m,g,b){var T=re();try{return Hd(u,f,m,g,b)}catch(P){if(te(T),P!==P+0)throw P;return fe(1,0),0n}}function Yy(u,f,m,g){var b=re();try{return Qd(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function Jy(u,f,m,g){var b=re();try{return Xd(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function Ky(u,f,m,g,b,T,P,F,$,Y,me,J){var ue=re();try{return Yd(u,f,m,g,b,T,P,F,$,Y,me,J)}catch(Fe){if(te(ue),Fe!==Fe+0)throw Fe;fe(1,0)}}function Zy(u,f,m,g,b,T,P,F,$,Y,me){var J=re();try{Jd(u,f,m,g,b,T,P,F,$,Y,me)}catch(ue){if(te(J),ue!==ue+0)throw ue;fe(1,0)}}function eb(u,f,m,g,b,T,P,F,$,Y,me,J,ue,Fe,Xe,Ns){var ao=re();try{Kd(u,f,m,g,b,T,P,F,$,Y,me,J,ue,Fe,Xe,Ns)}catch(oo){if(te(ao),oo!==oo+0)throw oo;fe(1,0)}}function tb(u,f,m){var g=re();try{return Nd(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;return fe(1,0),0n}}function rb(u,f,m){var g=re();try{return Od(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;fe(1,0)}}function sb(u,f,m){var g=re();try{return Dd(u,f,m)}catch(b){if(te(g),b!==b+0)throw b;fe(1,0)}}function nb(u,f,m,g){var b=re();try{zd(u,f,m,g)}catch(T){if(te(b),T!==T+0)throw T;fe(1,0)}}function kn(){if(0<Se)ve=kn;else if(n)w?.(t),he();else{for(var u=dt;0<u.length;)u.shift()(t);0<Se?ve=kn:(t.calledRun=!0,C||(he(),w?.(t)))}}return n||(sr=await ut(),kn()),t.PTR_SIZE=4,t.webgpuInit=u=>{let f=new WeakMap,m,g,b=1;t.webgpuRegisterDevice=F=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(F){var $=f.get(F);if(!$){let Y=((me,J=0)=>{var ue=ld(J);return J=id(J,ue),et[ue>>>0]=me.queue,et[J>>>0]=me,J})(F,$=Zu(0));$=[b++,$,Y],f.set(F,$)}return m=F,g=$[0],$}m=void 0,g=0};let T=new Map;t.webgpuOnCreateSession=F=>{if(g!==void 0){var $=g;if(g=void 0,F){let Y=Ha($);T.set(F,Y),$===0&&u(m??Z(Y))}m=void 0}},t.webgpuOnReleaseSession=F=>{T.delete(F)};let P=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(F,$,Y)=>{if(Y)return F[P]=[Y,NaN],Y;if(Y=F[P])return Y[1]++,Y[0];if(($=T.get($))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return $=((me,J=0)=>(me.mapState==="unmapped"||ke(),J=od(J),et[J>>>0]=me,J))(F,$),F[P]=[$,1],$},t.webgpuUnregisterBuffer=F=>{let $=F[P];if(!$)throw Error("Buffer is not registered");$[1]--,$[1]===0&&(Ku($[0]),delete F[P])},t.webgpuGetBuffer=F=>Z(F),t.webgpuCreateDownloader=(F,$,Y)=>{if((Y=T.get(Y))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let me=Z(Y),J=16*Math.ceil(Number($)/16);return async()=>{let ue=me.createBuffer({size:J,usage:9});try{let Fe=me.createCommandEncoder();return Fe.copyBufferToBuffer(F,0,ue,0,J),me.queue.submit([Fe.finish()]),await ue.mapAsync(GPUMapMode.READ),ue.getMappedRange().slice(0,$)}finally{ue.destroy()}}},t.ad=(F,$)=>{var Y=$.buffer;let me=$.byteOffset,J=$.byteLength;if($=16*Math.ceil(Number(J)/16),F=Z(F),!m){var ue=Ha(g);m=Z(ue)}let Fe=(ue=m.createBuffer({mappedAtCreation:!0,size:$,usage:6})).getMappedRange();new Uint8Array(Fe).set(new Uint8Array(Y,me,J)),ue.unmap(),(Y=m.createCommandEncoder()).copyBufferToBuffer(ue,0,F,0,$),m.queue.submit([Y.finish()]),ue.destroy()}},t.webnnInit=u=>{let f=u[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,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,T)=>f.registerMLTensor(m,g,b,T),t.webnnCreateMLContext=m=>f.createMLContext(m),t.webnnRegisterMLConstant=(m,g,b,T,P,F)=>f.registerMLConstant(m,g,b,T,P,t.Uc,F),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)},R?t:new Promise((u,f)=>{w=u,v=f})}var s_,oh,kb=pe(()=>{s_=ah,oh=globalThis.self?.name?.startsWith("em-pthread"),oh&&ah()}),fo,Uo,ih,mt,n_,En,lh,ch,_o,uh,po,a_,mo,o_,hi=pe(()=>{di(),fo=typeof location>"u"?void 0:location.origin,Uo=import.meta.url>"file:"&&import.meta.url<"file;",ih=()=>{{if(Uo){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,fo).href}return import.meta.url}},mt=ih(),n_=()=>{if(mt&&!mt.startsWith("blob:"))return mt.substring(0,mt.lastIndexOf("/")+1)},En=(e,t)=>{try{let r=t??mt;return(r?new URL(e,r):new URL(e)).origin===fo}catch{return!1}},lh=(e,t)=>{let r=t??mt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},ch=(e,t)=>`${t??"./"}${e}`,_o=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},uh=async e=>(await import(e)).default,po=(xb(),jn(e_)).default,a_=async()=>{if(!mt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(En(mt))return[void 0,po()];let e=await _o(mt);return[e,po(e)]},mo=(kb(),jn(r_)).default,o_=async(e,t,r,s)=>{let n=mo&&!(e||t);if(n)if(mt)n=En(mt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,mo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??lh(a,t),i=r&&o&&!En(o,t),l=i?await _o(o):o??ch(a,t);return[i?l:void 0,await uh(l)]}}}),go,An,zs,wo,dh,hh,fh,fi,Pe,Rr=pe(()=>{hi(),An=!1,zs=!1,wo=!1,dh=()=>{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}},hh=()=>{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}},fh=()=>{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}},fi=async e=>{if(An)return Promise.resolve();if(zs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(wo)throw new Error("previous call to 'initializeWebAssembly()' failed.");zs=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!fh())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!hh())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=dh();r>1&&!s&&(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 n=e.wasmPaths,a=typeof n=="string"?n:void 0,o=n?.mjs,i=o?.href??o,l=n?.wasm,c=l?.href??l,d=e.wasmBinary,[h,_]=await o_(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,M)=>{let y={numThreads:r};if(d)y.wasmBinary=d,y.locateFile=k=>k;else if(c||a)y.locateFile=k=>c??a+k;else if(i&&i.indexOf("blob:")!==0)y.locateFile=k=>new URL(k,i).href;else if(h){let k=n_();k&&(y.locateFile=A=>k+A)}_(y).then(k=>{zs=!1,An=!0,go=k,v(),h&&URL.revokeObjectURL(h)},k=>{zs=!1,wo=!0,M(k)})})),await Promise.race(w),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Pe=()=>{if(An&&go)return go;throw new Error("WebAssembly is not initialized yet.")}}),gt,Wn,xe,_i=pe(()=>{Rr(),gt=(e,t)=>{let r=Pe(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},Wn=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,a])=>{let o=t?t+n:n;if(typeof a=="object")Wn(a,o+".",r,s);else if(typeof a=="string"||typeof a=="number")s(o,a.toString());else if(typeof a=="boolean")s(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 s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetLastError(n,n+s);let a=Number(t.getValue(n,s===4?"i32":"i64")),o=t.getValue(n+s,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),i_,Tb=pe(()=>{Rr(),_i(),i_=e=>{let t=Pe(),r=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let a=0;return e?.tag!==void 0&&(a=gt(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,a),r===0&&xe("Can't create run options."),e?.extra!==void 0&&Wn(e.extra,"",new WeakSet,(o,i)=>{let l=gt(o,s),c=gt(i,s);t._OrtAddRunConfigEntry(r,l,c)!==0&&xe(`Can't set a run config entry: ${o} - ${i}.`)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),a}}}),_h,ph,mh,Cn,pr,gh,l_,Eb=pe(()=>{Rr(),_i(),_h=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}`)}},ph=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},mh=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)},Cn=(e,t,r,s)=>{let n=gt(t,s),a=gt(r,s);Pe()._OrtAddSessionConfigEntry(e,n,a)!==0&&xe(`Can't set a session config entry: ${t} - ${r}.`)},pr=(e,t,r,s)=>{let n=gt(t,s),a=gt(r,s);e.push([n,a])},gh=async(e,t,r)=>{let s=t.executionProviders;for(let n of s){let a=typeof n=="string"?n:n.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let h=n?.deviceType;h&&Cn(e,"deviceType",h,r)}break;case"webgpu":{a="WebGPU";let h;if(typeof n!="string"){let p=n;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&&pr(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&pr(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let v=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];pr(o,"forceCpuNodeNames",v.join(`
|
|
4
|
+
`),r)}p.validationMode&&pr(o,"validationMode",p.validationMode,r)}let _=Pe().webgpuRegisterDevice(h);if(_){let[p,w,v]=_;pr(o,"deviceId",p.toString(),r),pr(o,"webgpuInstance",w.toString(),r),pr(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=gt(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}.`)}},l_=async e=>{let t=Pe(),r=0,s=[],n=e||{};mh(n);try{let a=_h(n.graphOptimizationLevel??"all"),o=ph(n.executionMode??"sequential"),i=typeof n.logId=="string"?gt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof n.optimizedModelFilePath=="string"?gt(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(a,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,i,l,c,d),r===0&&xe("Can't create session options."),n.executionProviders&&await gh(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Cn(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[h,_]of Object.entries(n.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=gt(h,s);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&xe(`Can't set a free dimension override: ${h} - ${_}.`)}return n.extra!==void 0&&Wn(n.extra,"",new WeakSet,(h,_)=>{Cn(r,h,_,s)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&xe("Can't release session options."),s.forEach(o=>t._free(o)),a}}}),Ir,Rn,es,Xs,Hn,pi,mi,jo,us=pe(()=>{Ir=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}`)}},Rn=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}`)}},es=(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],s=typeof t=="number"?t:t.reduce((n,a)=>n*a,1);return r>0?Math.ceil(s*r):void 0},Xs=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Hn=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}`)}},pi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",mi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",jo=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}`)}}}),gi,c_=pe(()=>{di(),gi=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"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),a;try{a=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),u_,Ab=pe(()=>{us(),u_=(e,t)=>new(Xs(t))(e)}),wh,vh,yh,bh,d_,Mh,at,h_=pe(()=>{us(),wh=["V","I","W","E","F"],vh=(e,t)=>{console.log(`[${wh[e]},${new Date().toISOString()}]${t}`)},d_=(e,t)=>{yh=e,bh=t},Mh=(e,t)=>{let r=Hn(e),s=Hn(yh);r>=s&&vh(r,typeof t=="function"?t():t)},at=(...e)=>{bh&&Mh(...e)}}),vo,qo,yo,xh,bo,kh,Mo,xo,ko,Th,f_,Cb=pe(()=>{us(),h_(),vo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qo=(e,t)=>{if(t==="int32")return e;let r=vo.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let s=r/8;if(e.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=e.byteLength/s,a=new(Xs(t))(e.buffer,e.byteOffset,n);switch(t){case"int64":case"uint64":{let o=new Int32Array(n);for(let i=0;i<n;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'`)}},yo=(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,s=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},xh=1,bo=()=>xh++,kh=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Mo=(e,t)=>{let r=vo.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((s,n)=>s*n)*r/8):0},xo=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:s,dataType:n,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=s,this.dataType=n,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 Mo(this.dataType,this.tensorShape)}destroy(){at("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=yo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(e){this.isDataConverted=e}},ko=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,s){let n=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=kh.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);at("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Mo(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),s&&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=qo(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 at("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?yo(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Th=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=bo();return this.tensorTrackersById.set(e,new ko(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,s,n){at("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,s,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){at("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,s){let n=this.getMLContext(e),a=bo(),o=new xo({sessionId:e,context:n,tensor:t,dataType:r,shape:s});return this.tensorTrackersById.set(a,new ko(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,s,n,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){at("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(c,1)[0];return h.sessionId=e,h}at("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:s,writable:n,readable:a});return new xo({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)}},f_=(...e)=>new Th(...e)}),__={};en(__,{WebNNBackend:()=>p_});var Bs,Eh,p_,Sb=pe(()=>{us(),Rr(),Ab(),Cb(),h_(),Bs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Eh=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),s=Object.keys(t).sort();return r.length===s.length&&r.every((n,a)=>n===s[a]&&e[n]===t[n])},p_=class{constructor(e){this.tensorManager=f_(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,d_(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){at("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){at("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)at("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(s=>s.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let t=this.mlContextCache.findIndex(r=>Eh(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 s=this.mlContextCache.findIndex(n=>n.mlContext===t);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){at("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s,n){let a=Bs.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,s,n)}async createTemporaryTensor(e,t,r){at("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let s=Bs.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!Pe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");at("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 u_(r,t)}}registerMLTensor(e,t,r,s){let n=Bs.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,n,s);return at("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,s,n,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(t,t+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(c);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":d=new Int32Array(c);break;case"uint32":d=new Uint32Array(c);break;case"int64":if(o){let h=qo(new Uint8Array(c),"int64");d=new Int32Array(h.buffer),n.dataType="int32"}else d=new BigInt64Array(c);break;case"uint64":d=new BigUint64Array(c);break;case"int8":d=new Int8Array(c);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return at("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let s=Bs.get(Ir(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),Ah,wi,vi,mr,Ch,To,Qn,yi,bi,Eo,Mi,xi,ki,m_=pe(()=>{Br(),Tb(),Eb(),us(),Rr(),_i(),c_(),Ah=(e,t)=>{Pe()._OrtInit(e,t)!==0&&xe("Can't initialize onnxruntime.")},wi=async e=>{Ah(e.wasm.numThreads,Hn(e.logLevel))},vi=async(e,t)=>{Pe().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!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(s=>{e.webgpu.device=s}),t==="webnn"){let s=new(Sb(),jn(__)).WebNNBackend(e);Pe().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,a,o,i,l)=>s.ensureTensor(n,a,o,i,l),(n,a)=>{s.uploadTensor(n,a)},async(n,a)=>s.downloadTensor(n,a),(n,a)=>s.registerMLContext(n,a),!!e.trace])}},mr=new Map,Ch=e=>{let t=Pe(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetInputOutputCount(e,n,n+s)!==0&&xe("Can't get session input/output count.");let a=s===4?"i32":"i64";return[Number(t.getValue(n,a)),Number(t.getValue(n+s,a))]}finally{t.stackRestore(r)}},To=(e,t)=>{let r=Pe(),s=r.stackSave(),n=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,"*"));n=Number(r.getValue(o+a,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],d=[];for(let h=0;h<c;h++){let _=Number(r.getValue(n+8+h*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(n+8+(h+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},Qn=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]},yi=async(e,t)=>{let r,s,n=Pe();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=Qn(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await l_(t),t?.externalData&&n.mountExternalData){let E=[];for(let C of t.externalData){let L=typeof C=="string"?C:C.path;E.push(gi(typeof C=="string"?C:C.data).then(x=>{n.mountExternalData(L,x)}))}await Promise.all(E)}for(let E of t?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof E!="string"){let C=E,L=C?.context,x=C?.gpuDevice,G=C?.deviceType,B=C?.powerPreference;L?n.currentContext=L:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:B})}else n.currentContext=await n.webnnCreateMLContext();break}a=await n._OrtCreateSession(r,s,o),n.webgpuOnCreateSession?.(a),a===0&&xe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(a,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[h,_]=Ch(a),p=!!t?.enableGraphCapture,w=[],v=[],M=[],y=[],k=[];for(let E=0;E<h;E++){let[C,L,x]=To(a,E);C===0&&xe("Can't get an input name."),c.push(C);let G=n.UTF8ToString(C);w.push(G),M.push(L===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Rn(L),shape:x})}for(let E=0;E<_;E++){let[C,L,x]=To(a,E+h);C===0&&xe("Can't get an output name."),d.push(C);let G=n.UTF8ToString(C);v.push(G),y.push(L===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Rn(L),shape:x});{if(p&&t?.preferredOutputLocation===void 0){k.push("gpu-buffer");continue}let B=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[G]??"cpu",j=n.webnnIsGraphOutput;if(B==="cpu"&&j&&j(a,G)){k.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(p&&B!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${B}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);k.push(B)}}let A=null;return k.some(E=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(a),i===0&&xe("Can't create IO binding."),A={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>jo(E))}),mr.set(a,[a,c,d,A,p,!1]),[a,w,v,M,y]}catch(h){throw c.forEach(_=>n._OrtFree(_)),d.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&xe("Can't release IO binding."),a!==0&&n._OrtReleaseSession(a)!==0&&xe("Can't release session."),h}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&xe("Can't release session options."),l.forEach(h=>n._free(h)),n.unmountExternalData?.()}},bi=e=>{let t=Pe(),r=mr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&xe("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&xe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),n.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(s)!==0&&xe("Can't release session."),mr.delete(e)},Eo=async(e,t,r,s,n,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 y=e[2].gpuBuffer;w=es(Ir(c),d);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=k(y,s)}}else if(h==="ml-tensor"){let y=e[2].mlTensor;w=es(Ir(c),d);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=k(s,y,Ir(c),d)}else{let y=e[2];if(Array.isArray(y)){w=l*y.length,p=i._malloc(w),r.push(p);for(let k=0;k<y.length;k++){if(typeof y[k]!="string")throw new TypeError(`tensor data at index ${k} is not a string`);i.setValue(p+k*l,gt(y[k],r),"*")}}else{let k=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(c!=="string"&&k&&A){let E=i.UTF8ToString(n);if(k(s,E)||A(s,E)){let C=Ir(c);w=es(C,d),_="ml-tensor";let L=i.webnnCreateTemporaryTensor,x=i.webnnUploadTensor;if(!L||!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await L(s,C,d);x(G,new Uint8Array(y.buffer,y.byteOffset,y.byteLength)),p=G}else w=y.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,w),p)}else w=y.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(y.buffer,y.byteOffset,w),p)}}let v=i.stackSave(),M=i.stackAlloc(4*d.length);try{d.forEach((k,A)=>i.setValue(M+A*l,k,l===4?"i32":"i64"));let y=i._OrtCreateTensor(Ir(c),p,w,M,d.length,jo(_));y===0&&xe(`Can't create tensor for input/output. session=${s}, index=${a}.`),t.push(y)}finally{i.stackRestore(v)}},Mi=async(e,t,r,s,n,a)=>{let o=Pe(),i=o.PTR_SIZE,l=mr.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,M=s.length,y=0,k=[],A=[],E=[],C=[],L=[],x=o.stackSave(),G=o.stackAlloc(v*i),B=o.stackAlloc(v*i),j=o.stackAlloc(M*i),X=o.stackAlloc(M*i);try{[y,k]=i_(a),br("wasm prepareInputOutputTensor");for(let U=0;U<v;U++)await Eo(r[U],A,C,e,d[t[U]],t[U],p);for(let U=0;U<M;U++)await Eo(n[U],E,C,e,h[s[U]],v+s[U],p);Mr("wasm prepareInputOutputTensor");for(let U=0;U<v;U++)o.setValue(G+U*i,A[U],"*"),o.setValue(B+U*i,d[t[U]],"*");for(let U=0;U<M;U++)o.setValue(j+U*i,E[U],"*"),o.setValue(X+U*i,h[s[U]],"*");if(_&&!w){let{handle:U,outputPreferredLocations:Q,outputPreferredLocationsEncoded:ee}=_;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}).`);br("wasm bindInputsOutputs");for(let I=0;I<v;I++){let D=t[I];await o._OrtBindInput(U,d[D],A[I])!==0&&xe(`Can't bind input[${I}] for session=${e}.`)}for(let I=0;I<M;I++){let D=s[I];n[I]?.[3]?(L.push(E[I]),o._OrtBindOutput(U,h[D],E[I],0)!==0&&xe(`Can't bind pre-allocated output[${I}] for session=${e}.`)):o._OrtBindOutput(U,h[D],0,ee[D])!==0&&xe(`Can't bind output[${I}] to ${Q[I]} for session=${e}.`)}Mr("wasm bindInputsOutputs"),mr.set(e,[c,d,h,_,p,!0])}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let W;_?W=await o._OrtRunWithBinding(c,_.handle,M,j,y):W=await o._OrtRun(c,B,G,v,X,M,j,y),W!==0&&xe("failed to call OrtRun().");let N=[],O=[];br("wasm ProcessOutputTensor");for(let U=0;U<M;U++){let Q=Number(o.getValue(j+U*i,"*"));if(Q===E[U]||L.includes(E[U])){N.push(n[U]),Q!==E[U]&&o._OrtReleaseTensor(Q)!==0&&xe("Can't release tensor.");continue}let ee=o.stackSave(),I=o.stackAlloc(4*i),D=!1,R,H=0;try{o._OrtGetTensorData(Q,I,I+i,I+2*i,I+3*i)!==0&&xe(`Can't access output tensor data on index ${U}.`);let he=i===4?"i32":"i64",ke=Number(o.getValue(I,he));H=o.getValue(I+i,"*");let oe=o.getValue(I+i*2,"*"),ut=Number(o.getValue(I+i*3,he)),Le=[];for(let Se=0;Se<ut;Se++)Le.push(Number(o.getValue(oe+Se*i,he)));o._OrtFree(oe)!==0&&xe("Can't free memory for tensor dims.");let Qe=Le.reduce((Se,ve)=>Se*ve,1);R=Rn(ke);let dt=_?.outputPreferredLocations[s[U]];if(R==="string"){if(dt==="gpu-buffer"||dt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Se=[];for(let ve=0;ve<Qe;ve++){let nt=o.getValue(H+ve*i,"*"),be=o.getValue(H+(ve+1)*i,"*"),Me=ve===Qe-1?void 0:be-nt;Se.push(o.UTF8ToString(nt,Me))}N.push([R,Le,Se,"cpu"])}else if(dt==="gpu-buffer"&&Qe>0){let Se=o.webgpuGetBuffer;if(!Se)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Se(H),nt=es(ke,Qe);if(nt===void 0||!pi(R))throw new Error(`Unsupported data type: ${R}`);D=!0;{o.webgpuRegisterBuffer(ve,e,H);let be=o.webgpuCreateDownloader(ve,nt,e);N.push([R,Le,{gpuBuffer:ve,download:async()=>{let Me=await be();return new(Xs(R))(Me)},dispose:()=>{o._OrtReleaseTensor(Q)!==0&&xe("Can't release tensor.")}},"gpu-buffer"])}}else if(dt==="ml-tensor"&&Qe>0){let Se=o.webnnEnsureTensor,ve=o.webnnIsGraphInputOutputTypeSupported;if(!Se||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(es(ke,Qe)===void 0||!mi(R))throw new Error(`Unsupported data type: ${R}`);if(!ve(e,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let nt=await Se(e,H,ke,Le,!1);D=!0,N.push([R,Le,{mlTensor:nt,download:o.webnnCreateMLTensorDownloader(H,R),dispose:()=>{o.webnnReleaseTensorId(H),o._OrtReleaseTensor(Q)}},"ml-tensor"])}else if(dt==="ml-tensor-cpu-output"&&Qe>0){let Se=o.webnnCreateMLTensorDownloader(H,R)(),ve=N.length;D=!0,O.push((async()=>{let nt=[ve,await Se];return o.webnnReleaseTensorId(H),o._OrtReleaseTensor(Q),nt})()),N.push([R,Le,[],"cpu"])}else{let Se=Xs(R),ve=new Se(Qe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(o.HEAPU8.subarray(H,H+ve.byteLength)),N.push([R,Le,ve,"cpu"])}}finally{o.stackRestore(ee),R==="string"&&H&&o._free(H),D||o._OrtReleaseTensor(Q)}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&xe("Can't clear bound outputs."),mr.set(e,[c,d,h,_,p,!1]));for(let[U,Q]of await Promise.all(O))N[U][2]=Q;return Mr("wasm ProcessOutputTensor"),N}finally{o.webnnOnRunEnd?.(c),o.stackRestore(x),r.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),n.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),A.forEach(W=>o._OrtReleaseTensor(W)),E.forEach(W=>o._OrtReleaseTensor(W)),C.forEach(W=>o._free(W)),y!==0&&o._OrtReleaseRunOptions(y),k.forEach(W=>o._free(W))}},xi=e=>{let t=Pe(),r=mr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&xe("Can't get an profile file name."),t._OrtFree(n)},ki=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),gr,Mt,Xr,Rs,Gs,Sn,Ao,Pn,Ar,Cr,Sh,g_,w_,v_,y_,b_,M_,x_,k_=pe(()=>{Br(),m_(),Rr(),hi(),gr=()=>!!De.wasm.proxy&&typeof document<"u",Xr=!1,Rs=!1,Gs=!1,Pn=new Map,Ar=(e,t)=>{let r=Pn.get(e);r?r.push(t):Pn.set(e,[t])},Cr=()=>{if(Xr||!Rs||Gs||!Mt)throw new Error("worker not ready")},Sh=e=>{switch(e.data.type){case"init-wasm":Xr=!1,e.data.err?(Gs=!0,Ao[1](e.data.err)):(Rs=!0,Ao[0]()),Sn&&(URL.revokeObjectURL(Sn),Sn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Pn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},g_=async()=>{if(!Rs){if(Xr)throw new Error("multiple calls to 'initWasm()' detected.");if(Gs)throw new Error("previous call to 'initWasm()' failed.");if(Xr=!0,gr())return new Promise((e,t)=>{Mt?.terminate(),a_().then(([r,s])=>{try{Mt=s,Mt.onerror=a=>t(a),Mt.onmessage=Sh,Ao=[e,t];let n={type:"init-wasm",in:De};!n.in.wasm.wasmPaths&&(r||Uo)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",import.meta.url).href,import.meta.url).href}),Mt.postMessage(n),Sn=r}catch(n){t(n)}},t)});try{await fi(De.wasm),await wi(De),Rs=!0}catch(e){throw Gs=!0,e}finally{Xr=!1}}},w_=async e=>{if(gr())return Cr(),new Promise((t,r)=>{Ar("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:De}};Mt.postMessage(s)});await vi(De,e)},v_=async e=>gr()?(Cr(),new Promise((t,r)=>{Ar("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};Mt.postMessage(s,[e.buffer])})):Qn(e),y_=async(e,t)=>{if(gr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Cr(),new Promise((r,s)=>{Ar("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Mt.postMessage(n,a)})}else return yi(e,t)},b_=async e=>{if(gr())return Cr(),new Promise((t,r)=>{Ar("release",[t,r]);let s={type:"release",in:e};Mt.postMessage(s)});bi(e)},M_=async(e,t,r,s,n,a)=>{if(gr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Cr(),new Promise((o,i)=>{Ar("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:s,options:a}};Mt.postMessage(c,ki(l))})}else return Mi(e,t,r,s,n,a)},x_=async e=>{if(gr())return Cr(),new Promise((t,r)=>{Ar("end-profiling",[t,r]);let s={type:"end-profiling",in:e};Mt.postMessage(s)});xi(e)}}),Co,Ph,T_,Pb=pe(()=>{Br(),k_(),us(),di(),c_(),Co=(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()}`)}},Ph=e=>{switch(e[3]){case"cpu":return new St(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!pi(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return St.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let t=e[0];if(!mi(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=e[2];return St.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},T_=class{async fetchModelAndCopyToWasmMemory(e){return v_(await gi(e))}async loadModel(e,t){Dr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await y_(r,t),zr()}async dispose(){return b_(this.sessionId)}async run(e,t,r){Dr();let s=[],n=[];Object.entries(e).forEach(h=>{let _=h[0],p=h[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(p),n.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=s.map((h,_)=>Co(h,()=>`input "${this.inputNames[n[_]]}"`)),l=a.map((h,_)=>h?Co(h,()=>`output "${this.outputNames[o[_]]}"`):null),c=await M_(this.sessionId,n,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??Ph(c[h]);return zr(),d}startProfiling(){}endProfiling(){x_(this.sessionId)}}}),E_={};en(E_,{OnnxruntimeWebAssemblyBackend:()=>Ho,initializeFlags:()=>Wo,wasmBackend:()=>A_});var Wo,Ho,A_,Fb=pe(()=>{Br(),k_(),Pb(),Wo=()=>{(typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0);let e=De.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),De.wasm.simd=!1),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=!1),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=!1),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)De.wasm.numThreads=1;else{let t=typeof navigator>"u"?lb("node:os").cpus().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ho=class{async init(e){Wo(),await g_(),await w_(e)}async createInferenceSessionHandler(e,t){let r=new T_;return await r.loadModel(e,t),r}},A_=new Ho});Br();Br();Br();var Lb="1.26.0-dev.20260416-b7804b056c",Ib=Zf;{let e=(Fb(),jn(E_)).wasmBackend;Or("webgpu",e,5),Or("webnn",e,5),Or("cpu",e,10),Or("wasm",e,10)}Object.defineProperty(De.versions,"web",{value:Lb,enumerable:!0});var Ob=Object.freeze({__proto__:null,get InferenceSession(){return ui},get TRACE(){return qn},get TRACE_EVENT_BEGIN(){return br},get TRACE_EVENT_END(){return Mr},get TRACE_FUNC_BEGIN(){return Dr},get TRACE_FUNC_END(){return zr},get Tensor(){return St},default:Ib,get env(){return De},get registerBackend(){return Or}});const Nb=(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 s=r.getContext("2d");if(s!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);const o=t?.format!==void 0?t.format:"RGB",i=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*n;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 M=0;M<n;M++){const y=(e.data[h++]-c[0])*l[0],k=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],E=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+y+","+k+","+A+","+E+")",s.fillRect(M,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")},Db=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(r!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm;let 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*n;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,M=3,y=0,k=h,A=h*2,E=-1;i==="RGBA"?(y=0,k=h,A=h*2,E=h*3):i==="RGB"?(y=0,k=h,A=h*2):i==="RBG"&&(y=0,A=h,k=h*2),s=r.createImageData(n,a);for(let C=0;C<a*n;p+=_,w+=_,v+=_,M+=_,C++)s.data[p]=(e.data[y++]-d[0])*c[0],s.data[w]=(e.data[k++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[M]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw new Error("Can not access image data");return s},So=(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:s}=t,n=t.norm??{mean:255,bias:0};let a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.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*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let h=4,_=0,p=1,w=2,v=3,M=0,y=c,k=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(M=0,k=c,y=c*2):l==="BGR"&&(k=0,y=c,M=c*2);for(let C=0;C<c;C++,_+=h,w+=h,p+=h,v+=h)d[M++]=(e[_]+o[0])/a[0],d[y++]=(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 Tt("float32",d,[1,4,r,s]):new Tt("float32",d,[1,3,r,s])},zb=async(e,t)=>{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=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(s){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(n){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,So(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(So(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return So(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Bb=(e,t)=>{const{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new Tt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Rb=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new Tt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},Gb=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new Tt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},$b=(e,t,r)=>new Tt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),rs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Gn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Fh=!1;const Vb=()=>{if(!Fh){Fh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(rs.set("int64",BigInt64Array),Gn.set(BigInt64Array,"int64")),t&&(rs.set("uint64",BigUint64Array),Gn.set(BigUint64Array,"uint64")),s?(rs.set("float16",r),Gn.set(r,"float16")):rs.set("float16",Uint16Array)}},Ub=e=>{let t=1;for(let r=0;r<e.length;r++){const s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},jb=(e,t)=>{switch(e.location){case"cpu":return new Tt(e.type,e.data,t);case"cpu-pinned":return new Tt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Tt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Tt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Tt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Tt=class{constructor(t,r,s){Vb();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=rs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" 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(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.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=t.gpuBuffer,this.downloader=t.download,this.disposer=t.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=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(n=t,l=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const c=rs.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 ${n} 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")n="string",i=t;else if(c==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(t);else{const c=Gn.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=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=Ub(a);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="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=n,this.dims=a,this.size=o}static async fromImage(t,r){return zb(t,r)}static fromTexture(t,r){return Bb(t,r)}static fromGpuBuffer(t,r){return Rb(t,r)}static fromMLTensor(t,r){return Gb(t,r)}static fromPinnedBuffer(t,r,s){return $b(t,r,s)}toDataURL(t){return Nb(this,t)}toImageData(t){return Db(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 jb(this,t)}};const qb=Tt;var Po={},Wb=Object.defineProperty,ds=(e,t)=>{for(var r in t)Wb(e,r,{get:t[r],enumerable:!0})},vt={},Wt={},Hb={},Qb="4.2.0",Ti=typeof self<"u",os=!F_(vt),C_=!F_(Wt),Xn=Ti&&"caches"in self,Xb=typeof globalThis.Deno<"u",na=Xb&&Xn&&!os,S_=typeof process<"u",P_=S_&&process?.release?.name==="node"&&!na,Ei=typeof window<"u"&&typeof window.document<"u",Ai=Ti&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),Yb=Ei||Ai||na,Jb=P_||typeof navigator<"u"&&"gpu"in navigator,Kb=typeof navigator<"u"&&"ml"in navigator,Zb=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",e0=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",t0=typeof ServiceWorkerGlobalScope<"u"&&Ti&&self instanceof ServiceWorkerGlobalScope,r0=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&s},s0=r0(),de=Object.freeze({IS_BROWSER_ENV:Ei,IS_WEBWORKER_ENV:Ai,IS_WEB_ENV:Yb,IS_SERVICE_WORKER_ENV:t0,IS_DENO_WEB_RUNTIME:na,IS_WEB_CACHE_AVAILABLE:Xn,IS_WEBGPU_AVAILABLE:Jb,IS_WEBNN_AVAILABLE:Kb,IS_SAFARI:s0,IS_PROCESS_AVAILABLE:S_,IS_NODE_ENV:P_,IS_FS_AVAILABLE:os,IS_PATH_AVAILABLE:C_,IS_CRYPTO_AVAILABLE:Zb,IS_CHROME_AVAILABLE:e0}),Ci=os&&C_,Yn="./";if(Ci){const e=Object(import.meta).url;e?Yn=Wt.dirname(Wt.dirname(Hb.fileURLToPath(e))):typeof __dirname<"u"&&(Yn=Wt.dirname(__dirname))}var n0=Ci?Wt.join(Yn,"/.cache/"):null,Lh="/models/",a0=Ci?Wt.join(Yn,Lh):Lh,o0=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Pt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Ih=Pt.WARNING,we={version:Qb,backends:{onnx:{}},get logLevel(){return Ih},set logLevel(e){Ih=e,we.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Ei||Ai||na),localModelPath:a0,useFS:os,useBrowserCache:Xn,useFSCache:os,cacheDir:n0,useCustomCache:!1,customCache:null,useWasmCache:Xn||os,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:o0};function F_(e){return Object.keys(e).length===0}var _t=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 yr(e,t){e&&e(t)}var Qo=class extends _t{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};const t=Object.values(this.files_loading).reduce((n,a)=>n+a.loaded,0),r=Object.values(this.files_loading).reduce((n,a)=>n+a.total,0),s=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:s,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function i0(e){return Number.isInteger(e)||typeof e=="bigint"}function Oh(e){return e==null||e===-1}function Nh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Ht(...e){return Array.prototype.concat.apply([],e)}function l0(...e){return e.reduce((t,r)=>t.flatMap(s=>r.map(n=>[s,n])))}function Jn(e,t){return Math.abs((e+t)%(2*t)-t)}function Ke(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function c0(e,t){let r=0;for(const s of e)s===t&&++r;return r}var ie={error(...e){we.logLevel<=Pt.ERROR&&console.error(...e)},warn(...e){we.logLevel<=Pt.WARNING&&console.warn(...e)},info(...e){we.logLevel<=Pt.INFO&&console.log(...e)},debug(...e){we.logLevel<=Pt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},u0=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let s=t;for(let n=0;n<r.length;++n){const a=r[n];s=s[a]??=Object.create(null)}s.end=r}return t}split(e){const t=[],r=e.length;let s=0,n=0;for(;n<r;){let a=this.trie,o=null,i=n;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(n>s&&t.push(e.slice(s,n)),t.push(o),n+=o.length,s=n):++n}return s<r&&t.push(e.slice(s)),t}},Dh=u0,d0=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}},h0=d0,L_=(()=>{const e=[...Array.from({length:94},(n,a)=>a+33),...Array.from({length:12},(n,a)=>a+161),...Array.from({length:82},(n,a)=>a+174)],t=e.slice();let r=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);const s=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,a)=>[n,s[a]]))})(),f0=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),_0=f0(L_),zh=".,!?…。,、।۔،",p0=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${zh}])]+`,` ?[^\\s${zh}]+`]]),Kn="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",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"),aa=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[s,n]of p0)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(a,"gu")}catch{throw s}}}else if(e.String!==void 0){const r=m0(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},m0=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),g0=(e,t,r)=>{const s=[];let n=0;for(;n<e.length;){if(s.push(e[n]),(t.get(e[n])??r)!==r){++n;continue}for(;++n<e.length&&(t.get(e[n])??r)===r;)t.get(s.at(-1))!==r&&(s[s.length-1]+=e[n])}return s},w0=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,v0=e=>Number.isInteger(e)||typeof e=="bigint",y0=e=>{let t=0;for(const r of e)++t;return t},b0=e=>I_(e.toLowerCase()),Ft=(...e)=>Array.prototype.concat.apply([],e),Pi=e=>new Map(Object.entries(e)),M0=(e,t)=>{const r=[];let s=0;for(const n of e.matchAll(t)){const a=n[0];s<n.index&&r.push(e.slice(s,n.index)),a.length>0&&r.push(a),s=n.index+a.length}return s<e.length&&r.push(e.slice(s)),r},I_=e=>e.replace(new RegExp("\\p{M}","gu"),""),Bh=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const s of r)if(!(s in e))return`${t} must contain a "${s}" property`;return null},x0=e=>e.match(/\S+/g)||[],k0=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},tn=k0,T0=class extends tn{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},cr=T0,E0=class extends cr{tokenize_chinese_chars(e){const t=[];for(let r=0;r<e.length;++r){const s=e[r],n=s.charCodeAt(0);w0(n)?(t.push(" "),t.push(s),t.push(" ")):t.push(s)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
|
|
5
|
+
`: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 s=r.charCodeAt(0);s===0||s===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}},A0=E0,C0=class extends cr{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}},S0=C0,P0=class extends cr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>O_(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},F0=P0,L0=class extends cr{normalize(e){const t=aa(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},I0=L0,O0=class extends cr{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},oa=O0,N0=class extends oa{constructor(){super(...arguments),this.form="NFC"}},D0=N0,z0=class extends oa{constructor(){super(...arguments),this.form="NFD"}},B0=z0,R0=class extends oa{constructor(){super(...arguments),this.form="NFKC"}},G0=R0,$0=class extends oa{constructor(){super(...arguments),this.form="NFKD"}},V0=$0,U0=class extends cr{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}},j0=U0,q0=class extends cr{normalize(e){return I_(e)}},W0=q0,H0=class extends cr{normalize(e){return e.toLowerCase()}},Q0=H0,X0=class extends cr{normalize(e){return e=this.config.prepend+e,e}},Y0=X0;function J0(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new A0(e);case"Precompiled":return new S0(e);case"Sequence":return new F0(e);case"Replace":return new I0(e);case"NFC":return new D0(e);case"NFD":return new B0(e);case"NFKC":return new G0(e);case"NFKD":return new V0(e);case"Strip":return new j0(e);case"StripAccents":return new W0(e);case"Lowercase":return new Q0(e);case"Prepend":return new Y0(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var O_=J0,K0=class extends tn{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)}},Nt=K0,Z0=class extends Nt{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=L_,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(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},eM=Z0,tM=class extends Nt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},rM=tM,sM=class extends Nt{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 s=e.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},nM=sM,aM=class extends Nt{constructor(e){super(),this.config=e,this.pattern=aa(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):M0(e,this.pattern)}},oM=aM,iM=class extends Nt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Kn}]+|[${Kn}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},lM=iM,cM=class extends Nt{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)||[]}},uM=cM,dM=class extends Nt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Kn}]+|[${Kn}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},hM=dM,fM=class extends Nt{constructor(e){super(),this.config=e,this.pattern=aa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},_M=fM,pM=class extends Nt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>N_(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,t):r,[e])}},mM=pM,gM=class extends Nt{pre_tokenize_text(e){return x0(e)}},wM=gM,vM=class extends Nt{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}},yM=vM;function bM(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new hM;case"Sequence":return new mM(e);case"Whitespace":return new rM;case"WhitespaceSplit":return new wM;case"Metaspace":return new nM(e);case"ByteLevel":return new eM(e);case"Split":return new oM(e);case"Punctuation":return new lM(e);case"Digits":return new uM(e);case"Replace":return new _M(e);case"FixedLength":return new yM(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var N_=bM,MM=class extends tn{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=g0(t,this.tokens_to_ids,this.unk_token_id)),t}},ia=MM,xM=class extends ia{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Pi(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 s=[...r];if(s.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,a=0;const o=[];for(;a<s.length;){let i=s.length,l=null;for(;a<i;){let c=s.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){n=!0;break}o.push(l),a=i}n?t.push(this.unk_token):t.push(...o)}return t}},Rh=xM,Gh=class D_{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new D_(!1,new Map)}},kM=class{constructor(){this.root=Gh.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let s=t.children.get(r);s===void 0&&(s=Gh.default(),t.children.set(r,s)),t=s}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const s of e){if(r+=s,t=t.children.get(s),t===void 0)return;t.is_leaf&&(yield r)}}},TM=kM,Fo=class z_{constructor(t,r,s,n,a){this.token_id=t,this.node_id=r,this.pos=s,this.length=n,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new z_(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},EM=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 s=new Fo(this.bos_token_id??0,0,0,0,0),n=new Fo(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(e,t,r,s){const n=this.nodes.length,a=new Fo(s,n,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=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let a=n.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)}},AM=EM;function CM(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}var SM=class extends ia{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=e.vocab[s];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),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=CM(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new TM,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let s=0;for(;s<t.length;){let n=!1;const a=t.slice(s).join(""),o=this.trie.common_prefix_search(a);for(const i of o){const l=this.tokens_to_ids.get(i),c=this.scores[l],d=y0(i);e.insert(s,d,c,l),!n&&d===r&&(n=!0)}n||e.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(e){const t=new AM(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 s=this.tokenize(r);t.push(...s)}return t}},$h=SM,PM=class{constructor(e=(r,s)=>r>s,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}},FM=PM,LM=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()}},IM=LM,OM=class extends ia{constructor(e){super(e),this.tokens_to_ids=Pi(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,s]of this.tokens_to_ids)this.vocab[s]=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,s)=>[JSON.stringify(r),s])),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 IM(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 s=[];if(r.length>1){const n=new FM((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(n,o),o=l}for(;!n.is_empty();){const i=n.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(n,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=a;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,s),s}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 s=this.bpe(r);for(const n of s)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(n)).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}},Vh=OM,NM=class extends ia{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=Pi(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[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(e){return e}},DM=NM;function zM(e,t){switch(e.type){case"WordPiece":return new Rh(e);case"Unigram":return new $h(e,t.eos_token);case"BPE":return new Vh(e);default:if(e.vocab)return Array.isArray(e.vocab)?new $h(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Vh(e):new Rh(e):new DM(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var BM=zM,RM=class extends tn{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},rn=RM,GM=class extends rn{post_process(e,t=null,r=!0){const s=t===null?this.config.single:this.config.pair;let n=[],a=[];for(const o of s)"SpecialToken"in o?r&&(n.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(n=Ft(n,e),a=Ft(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(n=Ft(n,t),a=Ft(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:n,token_type_ids:a}}},$M=GM,VM=class extends rn{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},UM=VM,jM=class extends rn{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Ft([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=[],a=r?[this.sep[0]]:[];e=Ft(e,n,t,a),s=Ft(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},qM=jM,WM=class extends rn{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Ft([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Ft(e,n,t,a),s=Ft(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},HM=WM,QM=class extends rn{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>B_(t))}post_process(e,t=null,r=!0){let s={tokens:e,tokens_pair:t};for(const n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},XM=QM;function YM(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new $M(e);case"ByteLevel":return new UM(e);case"BertProcessing":return new qM(e);case"RobertaProcessing":return new HM(e);case"Sequence":return new XM(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var B_=YM,JM=class extends tn{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("")}},Dt=JM,KM=class extends Dt{constructor(e){super(e),this.byte_decoder=_0,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(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const s of e)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},ZM=KM,ex=class extends Dt{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const s=this.config.prefix;s&&t.startsWith(s)?t=t.replace(s,""):t=" "+t}return this.cleanup&&(t=Si(t)),t})}},tx=ex,rx=class extends Dt{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;r<e.length;++r){let s=e[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),t.push(s)}return t}},sx=rx,nx=class extends Dt{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},ax=nx,ox=class extends Dt{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 n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let s=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=Si(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},ix=ox,lx=class extends Dt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>R_(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},cx=lx,ux=class extends Dt{decode_chain(e){const t=aa(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(s=>s.replaceAll(t,r))}},dx=ux,hx=class extends Dt{decode_chain(e){return[e.join("")]}},fx=hx,_x=class extends Dt{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 n=0;n<this.start&&t[n]===this.content;++n){r=n+1;continue}let s=t.length;for(let n=0;n<this.stop;++n){const a=t.length-n-1;if(t[a]===this.content){s=a;continue}else break}return t.slice(r,s)})}},px=_x,mx=class extends Dt{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const s of e){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){const a=parseInt(s.slice(3,5),16);isNaN(a)||(n=a)}if(n!==null)r.push(n);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}return t}},gx=mx;function wx(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new ZM(e);case"WordPiece":return new tx(e);case"Metaspace":return new sx(e);case"BPEDecoder":return new ax(e);case"CTC":return new ix(e);case"Sequence":return new cx(e);case"Replace":return new dx(e);case"Fuse":return new fx(e);case"Strip":return new px(e);case"ByteFallback":return new gx(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var R_=wx,vx=class{constructor(e,t){const r=Bh(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const s=Bh(t,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=t,this.normalizer=O_(this.tokenizer.normalizer),this.pre_tokenizer=N_(this.tokenizer.pre_tokenizer),this.model=BM(this.tokenizer.model,this.config),this.post_processor=B_(this.tokenizer.post_processor),this.decoder=R_(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const n=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new h0(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 n.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 Dh(n),this.splitter_normalized=new Dh(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:s=null}={}){const{tokens:n,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:n,attention_mask:new Array(o.length).fill(1)};return s&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!v0(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(s=s.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Si(s)),s}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,s)=>{const n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(t[s-1]=t[s-1].trimEnd()),n.rstrip&&s<t.length-1&&(t[s+1]=t[s+1].trimStart()))}),t.flatMap((r,s)=>{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=b0(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const n=this.splitter_normalized.split(r);return n.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(n[o-1]=n[o-1].trimEnd()),i.rstrip&&o<n.length-1&&(n[o+1]=n[o+1].trimStart()))}),n.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:s}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const s=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Ft(s??[],n??[])}}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 s=this.model.vocab[r];(e||!this.added_tokens_map.has(s))&&t.set(s,r)}return t}},yx=vx,z=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",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),xt=class{constructor(e,t){this.value=e,this.type=t}};function Uh(e){return/\w/.test(e)}function $s(e){return/[0-9]/.test(e)}function jh(e){return/\s/.test(e)}var bx=[["{%",z.OpenStatement],["%}",z.CloseStatement],["{{",z.OpenExpression],["}}",z.CloseExpression],["(",z.OpenParen],[")",z.CloseParen],["{",z.OpenCurlyBracket],["}",z.CloseCurlyBracket],["[",z.OpenSquareBracket],["]",z.CloseSquareBracket],[",",z.Comma],[".",z.Dot],[":",z.Colon],["|",z.Pipe],["<=",z.ComparisonBinaryOperator],[">=",z.ComparisonBinaryOperator],["==",z.ComparisonBinaryOperator],["!=",z.ComparisonBinaryOperator],["<",z.ComparisonBinaryOperator],[">",z.ComparisonBinaryOperator],["+",z.AdditiveBinaryOperator],["-",z.AdditiveBinaryOperator],["~",z.AdditiveBinaryOperator],["*",z.MultiplicativeBinaryOperator],["/",z.MultiplicativeBinaryOperator],["%",z.MultiplicativeBinaryOperator],["=",z.Equals]],Mx=new Map([["n",`
|
|
6
|
+
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function xx(e,t={}){return e.endsWith(`
|
|
7
|
+
`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function kx(e,t={}){const r=[],s=xx(e,t);let n=0,a=0;const o=c=>{let d="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");const h=s[n++],_=Mx.get(h);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${h}`);d+=_;continue}if(d+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{const c=r.at(-1);c&&c.type===z.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&jh(s[n]);)++n};e:for(;n<s.length;){const c=r.at(-1)?.type;if(c===void 0||c===z.CloseStatement||c===z.CloseExpression||c===z.Comment){let h="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)h+=s[n++];if(h.length>0){r.push(new xt(h,z.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;const h=s[n]==="-";h&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++]}const p=_.endsWith("-");p&&(_=_.slice(0,-1)),h&&i(),r.push(new xt(_,z.Comment)),n+=2,p&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new xt("{%",z.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new xt("{{",z.OpenExpression)),a=0,n+=3;continue}if(o(jh),s.slice(n,n+3)==="-%}"){r.push(new xt("%}",z.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new xt("}}",z.CloseExpression)),n+=3,l();continue}const d=s[n];if(d==="-"||d==="+"){const h=r.at(-1)?.type;if(h===z.Text||h===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(h){case z.Identifier:case z.NumericLiteral:case z.StringLiteral:case z.CloseParen:case z.CloseSquareBracket:break;default:{++n;const _=o($s);r.push(new xt(`${d}${_}`,_.length>0?z.NumericLiteral:z.UnaryOperator));continue}}}for(const[h,_]of bx){if(h==="}}"&&a>0)continue;if(s.slice(n,n+h.length)===h){r.push(new xt(h,_)),_===z.OpenExpression?a=0:_===z.OpenCurlyBracket?++a:_===z.CloseCurlyBracket&&--a,n+=h.length;continue e}}if(d==="'"||d==='"'){++n;const h=o(_=>_!==d);r.push(new xt(h,z.StringLiteral)),++n;continue}if($s(d)){let h=o($s);if(s[n]==="."&&$s(s[n+1])){++n;const _=o($s);h=`${h}.${_}`}r.push(new xt(h,z.NumericLiteral));continue}if(Uh(d)){const h=o(Uh);r.push(new xt(h,z.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var zt=class{type="Statement"},Tx=class extends zt{constructor(e){super(),this.body=e}type="Program"},Ex=class extends zt{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},Ax=class extends zt{constructor(e,t,r,s){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=s}type="For"},Cx=class extends zt{type="Break"},Sx=class extends zt{type="Continue"},Px=class extends zt{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},Fx=class extends zt{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},Lx=class extends zt{constructor(e){super(),this.value=e}type="Comment"},yt=class extends zt{type="Expression"},Ix=class extends yt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},qh=class extends yt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},Yr=class extends yt{constructor(e){super(),this.value=e}type="Identifier"},hs=class extends yt{constructor(e){super(),this.value=e}type="Literal"},Ox=class extends hs{type="IntegerLiteral"},Nx=class extends hs{type="FloatLiteral"},Wh=class extends hs{type="StringLiteral"},Dx=class extends hs{type="ArrayLiteral"},Hh=class extends hs{type="TupleLiteral"},zx=class extends hs{type="ObjectLiteral"},Vs=class extends yt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},Bx=class extends yt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},Rx=class extends zt{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},Gx=class extends yt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},$x=class extends yt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},Vx=class extends yt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},Ux=class extends yt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},jx=class extends yt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},qx=class extends yt{constructor(e){super(),this.argument=e}type="SpreadExpression"},Wx=class extends zt{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},Hx=class extends yt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function Qx(e){const t=new Tx([]);let r=0;function s(I,D){const R=e[r++];if(!R||R.type!==I)throw new Error(`Parser Error: ${D}. ${R.type} !== ${I}.`);return R}function n(I){if(!l(I))throw new SyntaxError(`Expected ${I}`);++r}function a(){switch(e[r].type){case z.Comment:return new Lx(e[r++].value);case z.Text:return c();case z.OpenStatement:return d();case z.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...I){return r+I.length<=e.length&&I.every((D,R)=>D===e[r+R].type)}function i(...I){return e[r]?.type===z.OpenStatement&&e[r+1]?.type===z.Identifier&&I.includes(e[r+1]?.value)}function l(...I){return r+I.length<=e.length&&I.every((D,R)=>e[r+R].type==="Identifier"&&D===e[r+R].value)}function c(){return new Wh(s(z.Text,"Expected text token").value)}function d(){if(s(z.OpenStatement,"Expected opening statement token"),e[r].type!==z.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const I=e[r].value;let D;switch(I){case"set":++r,D=_();break;case"if":++r,D=p(),s(z.OpenStatement,"Expected {% token"),n("endif"),s(z.CloseStatement,"Expected %} token");break;case"macro":++r,D=w(),s(z.OpenStatement,"Expected {% token"),n("endmacro"),s(z.CloseStatement,"Expected %} token");break;case"for":++r,D=M(),s(z.OpenStatement,"Expected {% token"),n("endfor"),s(z.CloseStatement,"Expected %} token");break;case"call":{++r;let R=null;o(z.OpenParen)&&(R=j());const H=ee();if(H.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const he=j();s(z.CloseStatement,"Expected closing statement token");const ke=[];for(;!i("endcall");)ke.push(a());s(z.OpenStatement,"Expected '{%'"),n("endcall"),s(z.CloseStatement,"Expected closing statement token");const oe=new qh(H,he);D=new Wx(oe,R,ke);break}case"break":++r,s(z.CloseStatement,"Expected closing statement token"),D=new Cx;break;case"continue":++r,s(z.CloseStatement,"Expected closing statement token"),D=new Sx;break;case"filter":{++r;let R=ee();R instanceof Yr&&o(z.OpenParen)&&(R=B(R)),s(z.CloseStatement,"Expected closing statement token");const H=[];for(;!i("endfilter");)H.push(a());s(z.OpenStatement,"Expected '{%'"),n("endfilter"),s(z.CloseStatement,"Expected '%}'"),D=new Rx(R,H);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return D}function h(){s(z.OpenExpression,"Expected opening expression token");const I=y();return s(z.CloseExpression,"Expected closing expression token"),I}function _(){const I=v();let D=null;const R=[];if(o(z.Equals))++r,D=v();else{for(s(z.CloseStatement,"Expected %} token");!i("endset");)R.push(a());s(z.OpenStatement,"Expected {% token"),n("endset")}return s(z.CloseStatement,"Expected closing statement token"),new Px(I,D,R)}function p(){const I=y();s(z.CloseStatement,"Expected closing statement token");const D=[],R=[];for(;!i("elif","else","endif");)D.push(a());if(i("elif")){++r,++r;const H=p();R.push(H)}else if(i("else"))for(++r,++r,s(z.CloseStatement,"Expected closing statement token");!i("endif");)R.push(a());return new Ex(I,D,R)}function w(){const I=ee();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const D=j();s(z.CloseStatement,"Expected closing statement token");const R=[];for(;!i("endmacro");)R.push(a());return new Fx(I,D,R)}function v(I=!1){const D=I?ee:y,R=[D()],H=o(z.Comma);for(;H&&(++r,R.push(D()),!!o(z.Comma)););return H?new Hh(R):R[0]}function M(){const I=v(!0);if(!(I instanceof Yr||I instanceof Hh))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const D=y();s(z.CloseStatement,"Expected closing statement token");const R=[];for(;!i("endfor","else");)R.push(a());const H=[];if(i("else"))for(++r,++r,s(z.CloseStatement,"Expected closing statement token");!i("endfor");)H.push(a());return new Ax(I,D,R,H)}function y(){return k()}function k(){const I=A();if(l("if")){++r;const D=A();if(l("else")){++r;const R=k();return new Hx(D,I,R)}else return new Gx(I,D)}return I}function A(){let I=E();for(;l("or");){const D=e[r];++r;const R=E();I=new Vs(D,I,R)}return I}function E(){let I=C();for(;l("and");){const D=e[r];++r;const R=C();I=new Vs(D,I,R)}return I}function C(){let I;for(;l("not");){const D=e[r];++r;const R=C();I=new Vx(D,R)}return I??L()}function L(){let I=x();for(;;){let D;if(l("not","in"))D=new xt("not in",z.Identifier),r+=2;else if(l("in"))D=e[r++];else if(o(z.ComparisonBinaryOperator))D=e[r++];else break;const R=x();I=new Vs(D,I,R)}return I}function x(){let I=O();for(;o(z.AdditiveBinaryOperator);){const D=e[r];++r;const R=O();I=new Vs(D,I,R)}return I}function G(){const I=N(ee());return o(z.OpenParen)?B(I):I}function B(I){let D=new qh(I,j());return D=N(D),o(z.OpenParen)&&(D=B(D)),D}function j(){s(z.OpenParen,"Expected opening parenthesis for arguments list");const I=X();return s(z.CloseParen,"Expected closing parenthesis for arguments list"),I}function X(){const I=[];for(;!o(z.CloseParen);){let D;if(e[r].type===z.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const R=y();D=new qx(R)}else if(D=y(),o(z.Equals)){if(++r,!(D instanceof Yr))throw new SyntaxError("Expected identifier for keyword argument");const R=y();D=new jx(D,R)}I.push(D),o(z.Comma)&&++r}return I}function W(){const I=[];let D=!1;for(;!o(z.CloseSquareBracket);)o(z.Colon)?(I.push(void 0),++r,D=!0):(I.push(y()),o(z.Colon)&&(++r,D=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(D){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Ux(...I)}return I[0]}function N(I){for(;o(z.Dot)||o(z.OpenSquareBracket);){const D=e[r];++r;let R;const H=D.type===z.OpenSquareBracket;if(H)R=W(),s(z.CloseSquareBracket,"Expected closing square bracket");else if(R=ee(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new Ix(I,R,H)}return I}function O(){let I=U();for(;o(z.MultiplicativeBinaryOperator);){const D=e[r++],R=U();I=new Vs(D,I,R)}return I}function U(){let I=Q();for(;l("is");){++r;const D=l("not");D&&++r;const R=ee();if(!(R instanceof Yr))throw new SyntaxError("Expected identifier for the test");I=new $x(I,D,R)}return I}function Q(){let I=G();for(;o(z.Pipe);){++r;let D=ee();if(!(D instanceof Yr))throw new SyntaxError("Expected identifier for the filter");o(z.OpenParen)&&(D=B(D)),I=new Bx(I,D)}return I}function ee(){const I=e[r++];switch(I.type){case z.NumericLiteral:{const D=I.value;return D.includes(".")?new Nx(Number(D)):new Ox(Number(D))}case z.StringLiteral:{let D=I.value;for(;o(z.StringLiteral);)D+=e[r++].value;return new Wh(D)}case z.Identifier:return new Yr(I.value);case z.OpenParen:{const D=v();return s(z.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),D}case z.OpenSquareBracket:{const D=[];for(;!o(z.CloseSquareBracket);)D.push(y()),o(z.Comma)&&++r;return++r,new Dx(D)}case z.OpenCurlyBracket:{const D=new Map;for(;!o(z.CloseCurlyBracket);){const R=y();s(z.Colon,"Expected colon between key and value in object literal");const H=y();D.set(R,H),o(z.Comma)&&++r}return++r,new zx(D)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r<e.length;)t.body.push(a());return t}function Xx(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const s=[];if(r>0)for(let n=e;n<t;n+=r)s.push(n);else for(let n=e;n>t;n+=r)s.push(n);return s}function Qh(e,t,r,s=1){const n=Math.sign(s);n>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;n*o<n*r;o+=s)a.push(e[o]);return a}function Yx(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function Jx(e){return Kx(new Date,e)}function Kx(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return n(e.getMonth()+1);case"%d":return n(e.getDate());case"%b":return s.format(e);case"%B":return r.format(e);case"%H":return n(e.getHours());case"%M":return n(e.getMinutes());case"%%":return"%";default:return a}})}function Zx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function e1(e,t,r,s){if(s===0)return e;let n=s==null||s<0?1/0:s;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(Zx(t),"gu");return e.replaceAll(a,o=>n>0?(--n,r):o)}var Xh=class extends Error{},Yh=class extends Error{},Xt=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new ne(!!this.value)}toString(){return String(this.value)}},ce=class extends Xt{type="IntegerValue"},Re=class extends Xt{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},K=class extends Xt{type="StringValue";builtins=new Map([["upper",new Oe(()=>new K(this.value.toUpperCase()))],["lower",new Oe(()=>new K(this.value.toLowerCase()))],["strip",new Oe(()=>new K(this.value.trim()))],["title",new Oe(()=>new K(Yx(this.value)))],["capitalize",new Oe(()=>new K(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ce(this.value.length)],["rstrip",new Oe(()=>new K(this.value.trimEnd()))],["lstrip",new Oe(()=>new K(this.value.trimStart()))],["startswith",new Oe(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof K)return new ne(this.value.startsWith(t.value));if(t instanceof _e){for(const r of t.value){if(!(r instanceof K))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new ne(!0)}return new ne(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Oe(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof K)return new ne(this.value.endsWith(t.value));if(t instanceof _e){for(const r of t.value){if(!(r instanceof K))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new ne(!0)}return new ne(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Oe(e=>{const t=e[0]??new ze;if(!(t instanceof K||t instanceof ze))throw new Error("sep argument must be a string or null");const r=e[1]??new ce(-1);if(!(r instanceof ce))throw new Error("maxsplit argument must be a number");let s=[];if(t instanceof ze){const n=this.value.trimStart();for(const{0:a,index:o}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&o!==void 0){s.push(a+n.slice(o+a.length));break}s.push(a)}}else{if(t.value==="")throw new Error("empty separator");s=this.value.split(t.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(t.value))}return new _e(s.map(n=>new K(n)))})],["replace",new Oe(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],r=e[1];if(!(t instanceof K&&r instanceof K))throw new Error("replace() arguments must be strings");let s;if(e.length>2?e[2].type==="KeywordArgumentsValue"?s=e[2].value.get("count")??new ze:s=e[2]:s=new ze,!(s instanceof ce||s instanceof ze))throw new Error("replace() count argument must be a number or null");return new K(e1(this.value,t.value,r.value,s.value))})]])},ne=class extends Xt{type="BooleanValue"},t1=/[\x7f-\uffff]/g;function Jh(e){return e.replace(t1,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Nr(e,t={},r=0,s=!0){const{indent:n=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,c;switch(o?[l,c]=o:n?(l=",",c=": "):(l=", ",c=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let d=JSON.stringify(e.value);return a&&(d=Jh(d)),d}case"ArrayValue":case"ObjectValue":{const d=n?" ".repeat(n):"",h=`
|
|
8
|
+
`+d.repeat(r),_=h+d;if(e.type==="ArrayValue"){const p=e.value.map(w=>Nr(w,t,r+1,s));return n?`[${_}${p.join(`${l}${_}`)}${h}]`:`[${p.join(l)}]`}else{let p=Array.from(e.value.entries());i&&(p=p.sort(([v],[M])=>v.localeCompare(M)));const w=p.map(([v,M])=>{let y=JSON.stringify(v);a&&(y=Jh(y));const k=`${y}${c}${Nr(M,t,r+1,s)}`;return n?`${_}${k}`:k});return n?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var Je=class extends Xt{type="ObjectValue";__bool__(){return new ne(this.value.size>0)}builtins=new Map([["get",new Oe(([e,t])=>{if(!(e instanceof K))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new ze})],["items",new Oe(()=>this.items())],["keys",new Oe(()=>this.keys())],["values",new Oe(()=>this.values())],["dictsort",new Oe(e=>{let t=new Map;const r=e.filter(i=>i instanceof js?(t=i.value,!1):!0),s=r.at(0)??t.get("case_sensitive")??new ne(!1);if(!(s instanceof ne))throw new Error("case_sensitive must be a boolean");const n=r.at(1)??t.get("by")??new K("key");if(!(n instanceof K))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");const a=r.at(2)??t.get("reverse")??new ne(!1);if(!(a instanceof ne))throw new Error("reverse must be a boolean");const o=Array.from(this.value.entries()).map(([i,l])=>new _e([new K(i),l])).sort((i,l)=>{const c=n.value==="key"?0:1,d=i.value[c],h=l.value[c],_=Xo(d,h,s.value);return a.value?-_:_});return new _e(o)})]]);items(){return new _e(Array.from(this.value.entries()).map(([e,t])=>new _e([new K(e),t])))}keys(){return new _e(Array.from(this.value.keys()).map(e=>new K(e)))}values(){return new _e(Array.from(this.value.values()))}toString(){return Nr(this,{},0,!1)}},js=class extends Je{type="KeywordArgumentsValue"},_e=class extends Xt{type="ArrayValue";builtins=new Map([["length",new ce(this.value.length)]]);__bool__(){return new ne(this.value.length>0)}toString(){return Nr(this,{},0,!1)}},Kh=class extends _e{type="TupleValue"},Oe=class extends Xt{type="FunctionValue"},ze=class extends Xt{type="NullValue"},Ie=class extends Xt{type="UndefinedValue"},Pr=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Oe(e=>{if(e.length===0)return new Je(new Map);if(e.length!==1||!(e[0]instanceof Je))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Oe],["odd",e=>{if(!(e instanceof 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 Re],["integer",e=>e instanceof ce],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof Je],["sequence",e=>e instanceof _e||e instanceof Je||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]]);set(e,t){return this.declareVariable(e,$n(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Ie}catch{return new Ie}}};function r1(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",Xx),e.set("strftime_now",Jx),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Zh(e,t){const r=t.split(".");let s=e;for(const n of r)if(s instanceof Je)s=s.value.get(n)??new Ie;else if(s instanceof _e){const a=parseInt(n,10);if(!isNaN(a)&&a>=0&&a<s.value.length)s=s.value[a];else return new Ie}else return new Ie;return s}function Xo(e,t,r=!1){if(e instanceof ze&&t instanceof ze)return 0;if(e instanceof ze||t instanceof ze)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Ie&&t instanceof Ie)return 0;if(e instanceof Ie||t instanceof Ie)throw new Error(`Cannot compare ${e.type} with ${t.type}`);const s=a=>a instanceof ce||a instanceof Re||a instanceof ne,n=a=>a instanceof ne?a.value?1:0:a.value;if(s(e)&&s(t)){const a=n(e),o=n(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type==="StringValue"){let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}else throw new Error(`Cannot compare type: ${e.type}`)}var s1=class{global;constructor(e){this.global=e??new Pr}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 s=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ne(r.value==s.value);case"!=":return new ne(r.value!=s.value)}if(r instanceof Ie||s instanceof Ie){if(s instanceof Ie&&["in","not in"].includes(e.operator.value))return new ne(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof ze||s instanceof ze)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new K(r.value.toString()+s.value.toString());if((r instanceof ce||r instanceof Re)&&(s instanceof ce||s instanceof Re)){const n=r.value,a=s.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?n+a:e.operator.value==="-"?n-a:n*a;return r instanceof Re||s instanceof Re?new Re(o):new ce(o)}case"/":return new Re(n/a);case"%":{const o=n%a;return r instanceof Re||s instanceof Re?new Re(o):new ce(o)}case"<":return new ne(n<a);case">":return new ne(n>a);case">=":return new ne(n>=a);case"<=":return new ne(n<=a)}}else if(r instanceof _e&&s instanceof _e){if(e.operator.value==="+")return new _e(r.value.concat(s.value))}else if(s instanceof _e){const n=s.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ne(n);case"not in":return new ne(!n)}}}if((r instanceof K||s instanceof K)&&e.operator.value==="+")return new K(r.value.toString()+s.value.toString());if(r instanceof K&&s instanceof K)switch(e.operator.value){case"in":return new ne(s.value.includes(r.value));case"not in":return new ne(!s.value.includes(r.value))}if(r instanceof K&&s instanceof Je)switch(e.operator.value){case"in":return new ne(s.value.has(r.value));case"not in":return new ne(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,t){const r=[],s=new Map;for(const n of e)if(n.type==="SpreadExpression"){const a=n,o=this.evaluate(a.argument,t);if(!(o instanceof _e))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){const a=n;s.set(a.key.value,this.evaluate(a.value,t))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,t))}return[r,s]}applyFilter(e,t,r){if(t.type==="Identifier"){const s=t;if(s.value==="safe")return e;if(s.value==="tojson")return new K(Nr(e,{}));if(e instanceof _e)switch(s.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 _e(e.value.slice().reverse());case"sort":return new _e(e.value.slice().sort((n,a)=>Xo(n,a,!1)));case"join":return new K(e.value.map(n=>n.value).join(""));case"string":return new K(Nr(e,{},0,!1));case"unique":{const n=new Set,a=[];for(const o of e.value)n.has(o.value)||(n.add(o.value),a.push(o));return new _e(a)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof K)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const n=e.builtins.get(s.value);if(n instanceof Oe)return n.value([],r);if(n instanceof ce)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new K(e.value.trim());case"indent":return new K(e.value.split(`
|
|
9
|
+
`).map((n,a)=>a===0||n.length===0?n:" "+n).join(`
|
|
10
|
+
`));case"join":case"string":return e;case"int":{const n=parseInt(e.value,10);return new ce(isNaN(n)?0:n)}case"float":{const n=parseFloat(e.value);return new Re(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof ce||e instanceof Re)switch(s.value){case"abs":return e instanceof ce?new ce(Math.abs(e.value)):new Re(Math.abs(e.value));case"int":return new ce(Math.floor(e.value));case"float":return new Re(e.value);case"string":return new K(e.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof Je)switch(s.value){case"items":return new _e(Array.from(e.value.entries()).map(([n,a])=>new _e([new K(n),a])));case"length":return new ce(e.value.size);default:{const n=e.builtins.get(s.value);if(n)return n instanceof Oe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(e instanceof ne)switch(s.value){case"bool":return new ne(e.value);case"int":return new ce(e.value?1:0);case"float":return new Re(e.value?1:0);case"string":return new K(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const s=t;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);const n=s.callee.value;if(n==="tojson"){const[,a]=this.evaluateArguments(s.args,r),o=a.get("indent")??new ze;if(!(o instanceof ce||o instanceof ze))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new ne(!1);if(!(i instanceof ne))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new ne(!1);if(!(l instanceof ne))throw new Error("If set, sort_keys must be a boolean");const c=a.get("separators")??new ze;let d=null;if(c instanceof _e||c instanceof Kh){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 ze))throw new Error("If set, separators must be a tuple of two strings");return new K(Nr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let a;if(e instanceof K)a=Array.from(e.value);else if(e instanceof _e)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(s.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(n==="int"||n==="float"){const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("default")??(n==="int"?new ce(0):new Re(0));if(e instanceof K){const l=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:n==="int"?new ce(l):new Re(l)}else{if(e instanceof ce||e instanceof Re)return e;if(e instanceof ne)return n==="int"?new ce(e.value?1:0):new Re(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){const[a,o]=this.evaluateArguments(s.args,r),i=a[0]??new K(""),l=a[1]??o.get("boolean")??new ne(!1);if(!(l instanceof ne))throw new Error("`default` filter flag must be a boolean");return e instanceof Ie||l.value&&!e.__bool__().value?i:e}if(e instanceof _e){switch(n){case"sort":{const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("reverse")??new ne(!1);if(!(i instanceof ne))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new ne(!1);if(!(l instanceof ne))throw new Error("case_sensitive must be a boolean");const c=a.at(2)??o.get("attribute")??new ze;if(!(c instanceof K||c instanceof ce||c instanceof ze))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(c instanceof ze)return h;const _=c instanceof ce?String(c.value):c.value;return Zh(h,_)};return new _e(e.value.slice().sort((h,_)=>{const p=d(h),w=d(_),v=Xo(p,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=n==="selectattr";if(e.value.some(h=>!(h instanceof Je)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,l]=s.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 _e(d)}case"map":{const[,a]=this.evaluateArguments(s.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(!(c instanceof Je))throw new Error("items in map must be an object");const d=Zh(c,o.value);return d instanceof Ie?i??new Ie:d});return new _e(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof K){switch(n){case"indent":{const[a,o]=this.evaluateArguments(s.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 ne(!1),c=a.at(2)??o.get("blank")??new ne(!1),d=e.value.split(`
|
|
11
|
+
`),h=" ".repeat(i.value),_=d.map((p,w)=>!l.value&&w===0||!c.value&&p.length===0?p:h+p);return new K(_.join(`
|
|
12
|
+
`))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Oe))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(s.args,r);return a.value([...o,new js(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof Je){const a=e.builtins.get(n);if(a&&a instanceof Oe){const[o,i]=this.evaluateArguments(s.args,r);return i.size>0&&o.push(new js(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" 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),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const n=s(r);return new ne(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ie}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);if(e.operator.value==="not")return new ne(!r.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const s of e){const n=this.evaluate(s,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new K(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,s]=this.evaluateArguments(e.args,t);s.size>0&&r.push(new js(s));const n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof _e||e instanceof K))throw new Error("Slice object must be an array or string");const s=this.evaluate(t.start,r),n=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(s instanceof ce||s instanceof Ie))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof ce||n instanceof Ie))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof ce||a instanceof Ie))throw new Error("Slice step must be numeric or undefined");return e instanceof _e?new _e(Qh(e.value,s.value,n.value,a.value)):new K(Qh(Array.from(e.value),s.value,n.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);s=this.evaluate(e.property,t)}else s=new K(e.property.value);let n;if(r instanceof Je){if(!(s instanceof K))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof _e||r instanceof K)if(s instanceof ce)n=r.value.at(s.value),r instanceof K&&(n=new K(r.value.at(s.value)));else if(s instanceof K)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof K))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof Xt?n:new Ie}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const s=e.assignee.value;t.setVariable(s,r)}else if(e.assignee.type==="TupleLiteral"){const s=e.assignee;if(!(r instanceof _e))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let a=0;a<s.value.length;++a){const o=s.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,n[a])}}else if(e.assignee.type==="MemberExpression"){const s=e.assignee,n=this.evaluate(s.object,t);if(!(n instanceof Je))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new ze}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 Pr(t);let s,n;if(e.iterable.type==="SelectExpression"){const c=e.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(e.iterable,r);if(!(n instanceof _e||n instanceof Je))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof Je&&(n=n.keys());const a=[],o=[];for(let c=0;c<n.value.length;++c){const d=new Pr(r),h=n.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 M=0;M<p.value.length;++M){if(p.value[M].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${p.value[M].type}`);v.setVariable(p.value[M].value,w.value[M])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);s&&(_(d),!this.evaluate(s,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 ne(c===0)],["last",new ne(c===a.length-1)],["length",new ce(a.length)],["previtem",c>0?a[c-1]:new Ie],["nextitem",c<a.length-1?a[c+1]:new Ie]]);r.setVariable("loop",new Je(d)),o[c](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof Yh)continue;if(h instanceof Xh)break;throw h}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new K(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Oe((r,s)=>{const n=new Pr(s);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let o=0;o<e.args.length;++o){const i=e.args[o],l=r[o];if(i.type==="Identifier"){const c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);n.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){const c=i,d=l??a?.value.get(c.key.value)??this.evaluate(c.value,n);n.setVariable(c.key.value,d)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(e.body,n)})),new ze}evaluateCallStatement(e,t){const r=new Oe((i,l)=>{const c=new Pr(l);if(e.callerArgs)for(let d=0;d<e.callerArgs.length;++d){const h=e.callerArgs[d];if(h.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${h.type}`);c.setVariable(h.value,i[d]??new Ie)}return this.evaluateBlock(e.body,c)}),[s,n]=this.evaluateArguments(e.call.args,t);s.push(new js(n));const a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);const o=new Pr(t);return o.setVariable("caller",r),a.value(s,o)}evaluateFilterStatement(e,t){const r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new Ie;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 Xh;case"Continue":throw new Yh;case"IntegerLiteral":return new ce(e.value);case"FloatLiteral":return new Re(e.value);case"StringLiteral":return new K(e.value);case"ArrayLiteral":return new _e(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new Kh(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[s,n]of e.value){const a=this.evaluate(s,t);if(!(a instanceof K))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(n,t))}return new Je(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new ze;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function $n(e){switch(typeof e){case"number":return Number.isInteger(e)?new ce(e):new Re(e);case"string":return new K(e);case"boolean":return new ne(e);case"undefined":return new Ie;case"object":return e===null?new ze:Array.isArray(e)?new _e(e.map($n)):new Je(new Map(Object.entries(e).map(([t,r])=>[t,$n(r)])));case"function":return new Oe((t,r)=>{const s=e(...t.map(n=>n.value))??null;return $n(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var qe=`
|
|
13
|
+
`,n1="{%- ",a1=" -%}";function o1(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function i1(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Lt(e.body,0,r).replace(/\n$/,"")}function tt(...e){return n1+e.join(" ")+a1}function Lt(e,t,r){return e.map(s=>l1(s,t,r)).join(qe)}function l1(e,t,r){const s=r.repeat(t);switch(e.type){case"Program":return Lt(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 s+tt("break");case"Continue":return s+tt("continue");case"CallStatement":return f1(e,t,r);case"FilterStatement":return _1(e,t,r);case"Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+ge(e)+" -}}"}}function c1(e,t,r){const s=r.repeat(t),n=[];let a=e;for(;a&&(n.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=s+tt("if",ge(n[0].test))+qe+Lt(n[0].body,t+1,r);for(let i=1;i<n.length;++i)o+=qe+s+tt("elif",ge(n[i].test))+qe+Lt(n[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=qe+s+tt("else")+qe+Lt(a.alternate,t+1,r)),o+=qe+s+tt("endif"),o}function u1(e,t,r){const s=r.repeat(t);let n="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;n=`${ge(o.lhs)} if ${ge(o.test)}`}else n=ge(e.iterable);let a=s+tt("for",ge(e.loopvar),"in",n)+qe+Lt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=qe+s+tt("else")+qe+Lt(e.defaultBlock,t+1,r)),a+=qe+s+tt("endfor"),a}function d1(e,t,r){const s=r.repeat(t),n=ge(e.assignee),a=e.value?ge(e.value):"",o=s+tt("set",`${n}${e.value?" = "+a:""}`);return e.body.length===0?o:o+qe+Lt(e.body,t+1,r)+qe+s+tt("endset")}function h1(e,t,r){const s=r.repeat(t),n=e.args.map(ge).join(", ");return s+tt("macro",`${e.name.value}(${n})`)+qe+Lt(e.body,t+1,r)+qe+s+tt("endmacro")}function f1(e,t,r){const s=r.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ge).join(", ")})`:"",a=ge(e.call);let o=s+tt(`call${n}`,a)+qe;return o+=Lt(e.body,t+1,r)+qe,o+=s+tt("endcall"),o}function _1(e,t,r){const s=r.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:ge(e.filter);let a=s+tt("filter",n)+qe;return a+=Lt(e.body,t+1,r)+qe,a+=s+tt("endfilter"),a}function ge(e,t=-1){switch(e.type){case"SpreadExpression":return`*${ge(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const r=e,s=o1(r),n=ge(r.left,s),a=ge(r.right,s+1),o=`${n} ${r.operator.value} ${a}`;return s<t?`(${o})`:o}case"UnaryExpression":{const r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+ge(r.argument,1/0)}case"CallExpression":{const r=e,s=r.args.map(ge).join(", ");return`${ge(r.callee)}(${s})`}case"MemberExpression":{const r=e;let s=ge(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ge(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{const r=e,s=ge(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ge(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{const r=e;return`${ge(r.lhs)} if ${ge(r.test)}`}case"TestExpression":{const r=e;return`${ge(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const r=e.value.map(ge),s=e.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([s,n])=>`${ge(s)}: ${ge(n)}`).join(", ")}}`;case"SliceExpression":{const r=e,s=r.start?ge(r.start):"",n=r.stop?ge(r.stop):"",a=r.step?`:${ge(r.step)}`:"";return`${s}:${n}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${ge(r.value)}`}case"Ternary":{const r=e,s=`${ge(r.trueExpr)} if ${ge(r.condition,0)} else ${ge(r.falseExpr)}`;return t>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var p1=class{parsed;constructor(e){const t=kx(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Qx(t)}render(e){const t=new Pr;if(r1(t),e)for(const[n,a]of Object.entries(e))t.set(n,a);return new s1(t).run(this.parsed).value}format(e){return i1(this.parsed,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"},Zn=class G_{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=vt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=vt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const s=vt.createReadStream(t);this.body=new ReadableStream({start(n){s.on("data",a=>n.enqueue(a)),s.on("end",()=>n.close()),s.on("error",a=>n.error(a))},cancel(){s.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 G_(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 vt.promises.readFile(this.filePath)).buffer}async blob(){const t=await vt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await vt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},la=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(de.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,s=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))s.push(o&4294967295);s.length||s.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 n=1,a=0;for(let o=Math.max(624,s.length);o>0;--o,++n,++a)n>=624&&(t[0]=t[623],n=1),a>=s.length&&(a=0),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1664525))+s[a]+a>>>0;for(let o=623;o>0;--o,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1566083941))-n>>>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 s=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^s>>>1^(s&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 s=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(s)*n,this._gauss_next=Math.sin(s)*n}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let s=this._int32()>>>32-r;for(;s>t;)s=this._int32()>>>32-r;const n=e[t];e[t]=e[s],e[s]=n}}choices(e,t){return e[$_(this._random_fn,t)]}};function $_(e,t){let r=0;for(let n=0;n<t.length;++n)r+=t[n];let s=e()*r;for(let n=0;n<t.length;++n)if(s-=t[n],s<0)return n;return t.length-1}var Ut=new la,Fi=Object.freeze({Random:la,seed:Ut.seed.bind(Ut),random:Ut.random.bind(Ut),gauss:Ut.gauss.bind(Ut),shuffle:Ut.shuffle.bind(Ut),choices:Ut.choices.bind(Ut)}),g1=e=>$_(Fi.random,e),w1=new la,V_=class{constructor(e){this.path=e}async match(e){let t=Wt.join(this.path,e),r=new Zn(t);if(r.exists)return r}async put(e,t,r=void 0){const s=Wt.join(this.path,e),n=de.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=w1._int32().toString(36),o=s+`.tmp.${n}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let c=0;await vt.promises.mkdir(Wt.dirname(s),{recursive:!0});const d=vt.createWriteStream(o),h=t.body.getReader();for(;;){const{done:_,value:p}=await h.read();if(_)break;await new Promise((v,M)=>{d.write(p,y=>{if(y){M(y);return}v()})}),c+=p.length;const w=l?c/l*100:0;r?.({progress:w,loaded:c,total:l})}await new Promise((_,p)=>{d.close(w=>w?p(w):_())}),await vt.promises.rename(o,s)}catch(i){try{await vt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=Wt.join(this.path,e);try{return await vt.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"},ef=100,y1=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Fn(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function fs(e,t=null,r=null){let s;try{s=new URL(e)}catch{return!1}return!(t&&!t.includes(s.protocol)||r&&!r.includes(s.hostname))}function b1(e){return!(!y1.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function M1(e,t,r){if(!r)return null;const s=v1[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}async function x1(e,t,r){const s=e.headers.get("Content-Length");let n=s?parseInt(s,10):r??0;s===null&&!r&&ie.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(n),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>n){n=h;const p=new Uint8Array(n);p.set(a),a=p}a.set(d,o),o=h;const _=o/n*100;return t({progress:_,loaded:o,total:n}),l()}return await l(),a}function tf(e){return fs(e,["blob:"])}function rf(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var U_="SHA-256",k1="experimental_transformers-hash-cache",sf=e=>({algorithm:U_,value:e}),nf=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(k1),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{const t=await this._getFileHash(e);if(t)try{const[r]=await navigator.crossOriginStorage.requestFileHandles([sf(t)]),s=await r.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}};put=async(e,t)=>{const r=await this._getFileHash(e);if(r){const s=await t.blob();await this._storeBlobInCOS(s,r)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{const[r]=await navigator.crossOriginStorage.requestFileHandles([sf(t)],{create:!0}),s=await r.createWritable();await s.write(e),await s.close()};_processAndStore=async(e,t)=>{try{const r=[];for await(const a of t)r.push(a);const s=new Blob(r),n=await this._getBlobHash(s);await this._storeBlobInCOS(s,n);try{await(await this._getHashCache()).put(e,new Response(n))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{const t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();const s=await this._getLfsFileHash(e);return s?(await t.put(e,new Response(s)),s):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const s=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return s?s[1]:null}catch{return null}};_getBlobHash=async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(U_,t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}};async function Li(e=null){let t=null;if(we.useCustomCache){if(!we.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!we.customCache.match||!we.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=we.customCache}if(!t&&we.experimental_useCrossOriginStorage&&nf.isAvailable()&&(t=new nf),!t&&we.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(we.cacheKey)}catch(r){ie.warn("An error occurred while opening the browser cache:",r)}}if(!t&&we.useFSCache){if(!de.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new V_(e??we.cacheDir)}return t}async function T1(e,...t){for(let r of t)try{let s=await e.match(r);if(s)return s}catch{continue}}var E1=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;const t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,t),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}},A1=100,Lo=new E1(A1);function j_(e,t){const r=Lo.get(e);if(r!==void 0)return r;const s=t().then(n=>n,n=>(Lo.delete(e),Promise.reject(n)));return Lo.put(e,s),s}async function C1(e){if(!fs(e,["http:","https:"]))return null;const t=q_(e);return t.set("Range","bytes=0-0"),we.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function sn(e,t,r={}){const s=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return j_(s,()=>S1(e,t,r))}async function S1(e,t,r){const s=await Li(r?.cache_dir),{localPath:n,remoteURL:a,proposedCacheKey:o,validModelId:i}=W_(e,t,r,s),l=await H_(s,n,o);if(l!==void 0&&typeof l!="string"){const c=l.headers.get("content-length"),d=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:d||void 0,fromCache:!0}}if(we.allowLocalModels&&!fs(n,["http:","https:"]))try{const d=await Ys(n);if(typeof d!="string"&&d.status!==404){const h=d.headers.get("content-length"),_=d.headers.get("content-type");return{exists:!0,size:h?parseInt(h,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(we.allowRemoteModels&&!r.local_files_only&&i)try{const c=await C1(a);if(c&&c.status>=200&&c.status<300){let d;const h=c.headers.get("content-type");if(c.status===206){const _=c.headers.get("content-range");if(_){const p=_.match(/bytes \d+-\d+\/(\d+)/);p&&(d=parseInt(p[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(d===void 0){const _=c.headers.get("content-length");d=_?parseInt(_,10):void 0}return{exists:!0,size:d,contentType:h||void 0,fromCache:!1}}}catch(c){ie.warn(`Unable to fetch file metadata for "${a}": ${c}`)}return{exists:!1,fromCache:!1}}async function Ys(e){return we.useFS&&!fs(e,["http:","https:","blob:"])?new Zn(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):we.fetch(e,{headers:q_(e)})}function q_(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const s=!!Po?.TESTING_REMOTELY,n=we.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),fs(e,["http:","https:"],["huggingface.co","hf.co"])){const o=Po?.HF_TOKEN??Po?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function W_(e,t,r={},s=null){const n=r.revision??"main",a=Fn(e,t),o=b1(e),i=o?Fn(we.localModelPath,a):a,l=Fn(we.remoteHost,we.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),c=s instanceof V_?n==="main"?a:Fn(e,n,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function H_(e,t,r){if(e)return await T1(e,t,r)}async function P1(e,t,r,s,n,a,o={}){if(await r.match(s)===void 0)if(a){if(typeof n!="string"){const i=new Headers(n.headers);i.set("content-length",a.byteLength.toString()),await r.put(s,new Response(a,{headers:i})).catch(l=>{ie.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>yr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(s,n,i)}}async function F1(e,t,r=!0,s={},n=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=W_(e,t,s,a);let h,_=!1,p;p=await H_(a,i,c);const w=p!==void 0;if(w)h=c;else{if(we.allowLocalModels)if(fs(o,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!we.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{p=await Ys(i),h=i}catch(k){ie.warn(`Unable to load from local path "${i}": "${k}"`)}if(p===void 0||typeof p!="string"&&p.status===404){if(s.local_files_only||!we.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await Ys(l),p.status!==200)return M1(p.status,l,r);h=c}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200}yr(s.progress_callback,{status:"download",name:e,file:t});let v;if(!(de.IS_NODE_ENV&&n)){let y;if(typeof p!="string")if(!s.progress_callback)y=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))y=new Uint8Array(await p.arrayBuffer()),yr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:y.length,total:y.length});else{let k;const A=p.headers.get("content-length");if(A)k=parseInt(A,10);else try{const E=await sn(e,t,s);E.size&&(k=E.size)}catch{}y=await x1(p,E=>{yr(s.progress_callback,{status:"progress",name:e,file:t,...E})},k)}v=y}if(_&&h&&typeof p!="string"&&await P1(e,t,a,h,p,v,s),de.IS_NODE_ENV&&n&&s.progress_callback&&typeof p!="string"){const y=parseInt(p.headers.get("content-length"),10)||0;yr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:y,total:y})}if(yr(s.progress_callback,{status:"done",name:e,file:t}),v){if(!de.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return v}if(p instanceof Zn)return p.filePath;const M=await a?.match(h);if(M instanceof Zn)return M.filePath;if(M instanceof Response)return new Uint8Array(await M.arrayBuffer());if(typeof M=="string")return M;throw new Error("Unable to get model file path or buffer.")}var Ln=new Map;async function ea(e,t,r=!0,s={},n=!1){if(!we.allowLocalModels){if(s.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(!we.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}yr(s.progress_callback,{status:"initiate",name:e,file:t});const a=`${e}::${t}`;let o=Ln.get(a);if(!o){const i=await Li(s?.cache_dir);o=F1(e,t,r,s,n,i).then(l=>(Ln.delete(a),l),l=>{throw Ln.delete(a),l}),Ln.set(a,o)}return await o}async function Ii(e,t,r=!0,s={}){const n=await ea(e,t,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function Yt(e,t,r=!0,s={}){const n=await Ii(e,t,r,s);return n===null?{}:JSON.parse(n)}function L1(e,[t,r,s],[n,a],o="bilinear",i=!1){const l=a/s,c=n/r,d=new e.constructor(n*a*t),h=r*s,_=n*a;for(let p=0;p<n;++p)for(let w=0;w<a;++w){const v=p*a+w,M=(w+.5)/l-.5,y=(p+.5)/c-.5;let k=Math.floor(M),A=Math.floor(y);const E=Math.min(k+1,s-1),C=Math.min(A+1,r-1);k=Math.max(k,0),A=Math.max(A,0);const L=M-k,x=y-A,G=(1-L)*(1-x),B=L*(1-x),j=(1-L)*x,X=L*x,W=A*s,N=C*s,O=W+k,U=W+E,Q=N+k,ee=N+E;for(let I=0;I<t;++I){const D=I*h;d[I*_+v]=G*e[D+O]+B*e[D+U]+j*e[D+Q]+X*e[D+ee]}}return d}function I1(e,t,r){const s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=t[r[i]],l*=s[i];const a=r.map((i,l)=>n[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,s]}function rt(e){const t=$e(e)[0],r=e.map(a=>Math.exp(a-t)),s=r.reduce((a,o)=>a+o,0);return r.map(a=>a/s)}function O1(e){const t=$e(e)[0];let r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);const s=Math.log(r);return e.map(a=>a-t-s)}function Yo(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}function $e(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]>t&&(t=e[s],r=s);return[t,r]}function Q_(e){return e>0&&(e&e-1)===0}var X_=class{constructor(e){if(this.size=e|0,this.size<=1||!Q_(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 s=Math.PI*r/this.size;this.table[r]=Math.cos(s),this.table[r+1]=-Math.sin(s)}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 s=0;s<this._width;s+=2){const n=this._width-s-2;this._bitrev[r]|=(r>>>s&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const r=t||new Array(e.length>>>1);for(let s=0;s<e.length;s+=2)r[s>>>1]=e[s];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let s=0;s<r.length;s+=2)r[s]=e[s>>>1],r[s+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 s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const h=c[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<s;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=s/a<<1;const h=o>>>2;for(i=0;i<s;i+=o){const _=i+h-1;for(let p=i,w=0;p<_;p+=2,w+=a){const v=p,M=v+h,y=M+h,k=y+h,A=e[v],E=e[v+1],C=e[M],L=e[M+1],x=e[y],G=e[y+1],B=e[k],j=e[k+1],X=d[w],W=r*d[w+1],N=C*X-L*W,O=C*W+L*X,U=d[2*w],Q=r*d[2*w+1],ee=x*U-G*Q,I=x*Q+G*U,D=d[3*w],R=r*d[3*w+1],H=B*D-j*R,he=B*R+j*D,ke=A+ee,oe=E+I,ut=A-ee,Le=E-I,Qe=N+H,dt=O+he,Se=r*(N-H),ve=r*(O-he);e[v]=ke+Qe,e[v+1]=oe+dt,e[M]=ut+ve,e[M+1]=Le-Se,e[y]=ke-Qe,e[y+1]=oe-dt,e[k]=ut-ve,e[k+1]=Le+Se}}}}_singleTransform2(e,t,r,s,n){const a=e[s],o=e[s+1],i=e[s+n],l=e[s+n+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+1],d=e[s+n],h=e[s+n+1],_=e[s+o],p=e[s+o+1],w=e[s+i],v=e[s+i+1],M=l+_,y=c+p,k=l-_,A=c-p,E=d+w,C=h+v,L=a*(d-w),x=a*(h-v);t[r]=M+E,t[r+1]=y+C,t[r+2]=k+x,t[r+3]=A-L,t[r+4]=M-E,t[r+5]=y-C,t[r+6]=k-x,t[r+7]=A+L}_realTransform4(e,t,r){const s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<s;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=s/a<<1;const _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<s;i+=o)for(let v=0,M=0;v<=w;v+=2,M+=a){const y=i+v,k=y+p,A=k+p,E=A+p,C=e[y],L=e[y+1],x=e[k],G=e[k+1],B=e[A],j=e[A+1],X=e[E],W=e[E+1],N=C,O=L,U=d[M],Q=r*d[M+1],ee=x*U-G*Q,I=x*Q+G*U,D=d[2*M],R=r*d[2*M+1],H=B*D-j*R,he=B*R+j*D,ke=d[3*M],oe=r*d[3*M+1],ut=X*ke-W*oe,Le=X*oe+W*ke,Qe=N+H,dt=O+he,Se=N-H,ve=O-he,nt=ee+ut,be=I+Le,Me=r*(ee-ut),Vr=r*(I-Le);if(e[y]=Qe+nt,e[y+1]=dt+be,e[k]=Se+Vr,e[k+1]=ve-Me,v===0){e[A]=Qe-nt,e[A+1]=dt-be;continue}if(v===w)continue;const Ss=i+p-v,Ur=i+_-v;e[Ss]=Se-r*Vr,e[Ss+1]=-ve-r*Me,e[Ur]=Qe-r*nt,e[Ur+1]=-dt+r*be}}const h=s>>>1;for(let _=2;_<h;_+=2)e[s-_]=e[_],e[s-_+1]=-e[_+1]}_singleRealTransform2(e,t,r,s,n){const a=e[s],o=e[s+n];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+n],d=e[s+o],h=e[s+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),s=2**Math.ceil(Math.log2(r));this.bufferSize=s,this._a=t;const n=new Float64Array(r),a=new Float64Array(s);this._chirpBuffer=new Float64Array(s),this._buffer1=new Float64Array(s),this._buffer2=new Float64Array(s),this._outBuffer1=new Float64Array(s),this._outBuffer2=new Float64Array(s);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;n[p]=h*Math.cos(_),n[p+1]=h*Math.sin(_),a[p]=n[p],a[p+1]=-n[p+1]}this._slicedChirpBuffer=n.subarray(t,r),this._f=new X_(s>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const s=this._buffer1,n=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[_];s[d]=p*l[d],s[h]=p*l[h]}else for(let d=0;d<l.length;d+=2){const h=d+1;s[d]=t[d]*l[d]-t[h]*l[h],s[h]=t[d]*l[h]+t[h]*l[d]}this._f.transform(a,s);for(let d=0;d<i.length;d+=2){const h=d+1;n[d]=a[d]*i[d]-a[h]*i[h],n[h]=a[d]*i[h]+a[h]*i[d]}this._f.inverseTransform(o,n);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=Q_(e),this.isPowerOfTwo?(this.fft=new X_(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),s=new e.constructor(t),n=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-n;i<=n;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),s[o++]=e[l]}s.sort(),r[a]=s[n]}return r}function qs(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,s=[t+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;const a=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let d=1;d<s[1];++d)for(let h=1;h<s[0];++h){const _=n[h-1][d-1],p=n[h-1][d],w=n[h][d-1];let v,M;_<p&&_<w?(v=_,M=0):p<_&&p<w?(v=p,M=1):(v=w,M=2),n[h][d]=e[h-1][d-1]+v,a[h][d]=M}for(let d=0;d<s[1];++d)a[0][d]=2;for(let d=0;d<s[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 G1=(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,s=e,n=new Float32Array(r);for(let a=0;a<r;++a)n[a]=s[t[a]];return n}})(),Y_={};ds(Y_,{default:()=>$1});var $1={};async function J_(e){const t=e.split("/").pop();let r;try{if(r=await Li(),r){const n=await r.match(e);if(n)return n}}catch(n){ie.warn(`Failed to load ${t} from cache:`,n)}const s=await we.fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone())}catch(n){ie.warn(`Failed to cache ${t}:`,n)}return s}async function V1(e){const t=await J_(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ie.warn("Failed to read WASM binary:",r),null}}async function U1(e){if(de.IS_SERVICE_WORKER_ENV||de.IS_CHROME_AVAILABLE)return e;const t=await J_(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ie.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 K_(e){return e<=Pt.DEBUG?0:e<=Pt.INFO?2:e<=Pt.WARNING||e<=Pt.ERROR?3:4}var q1={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},kt=[],Jo,is,af=Symbol.for("onnxruntime");if(af in globalThis)is=globalThis[af];else if(de.IS_NODE_ENV){switch(is=Y_,process.platform){case"win32":kt.push("dml");break;case"linux":process.arch==="x64"&&kt.push("cuda");break;case"darwin":kt.push("coreml");break}kt.push("webgpu"),kt.push("cpu"),Jo=["cpu"]}else is=Ob,de.IS_WEBNN_AVAILABLE&&kt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),de.IS_WEBGPU_AVAILABLE&&kt.push("webgpu"),kt.push("wasm"),Jo=["wasm"];var W1=is.InferenceSession;function H1(e=null){if(!e)return Jo;switch(e){case"auto":return kt;case"gpu":return kt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(kt.includes(e))return[j1[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${kt.join(", ")}.`)}var of=Promise.resolve(),Jr=null;async function Q1(){if(Jr)return Jr;if(!(we.useWasmCache&&typeof je?.wasm?.wasmPaths=="object"&&je?.wasm?.wasmPaths?.wasm&&je?.wasm?.wasmPaths?.mjs)){if(de.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Jr=Promise.resolve(),Jr}return Jr=(async()=>{const t=je.wasm.wasmPaths;let r=!1;await Promise.all([t.wasm&&!tf(t.wasm)?(async()=>{try{const s=await V1(rf(t.wasm));s&&(je.wasm.wasmBinary=s,r=!0)}catch(s){ie.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),t.mjs&&!tf(t.mjs)?(async()=>{try{const s=await U1(rf(t.mjs));s&&(je.wasm.wasmPaths.mjs=s)}catch(s){ie.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(je.wasm.wasmPaths.mjs=t.mjs)})(),Jr}async function Z_(e,t,r){await Q1();const s=K_(we.logLevel??Pt.WARNING),n=()=>W1.create(e,{logSeverityLevel:s,...t}),a=await(de.IS_WEB_ENV?of=of.then(n):n());return a.config=r,a}var lf=Promise.resolve();async function ep(e,t){const r=()=>e.run(t);return de.IS_WEB_ENV?lf=lf.then(r):r()}function tp(e){return e instanceof is.Tensor}var je=is?.env;function Oi(){return je?.wasm?.proxy}if(je){let e=function(t){const r=K_(t);je.logLevel=q1[r]};if(je.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&je.versions?.web&&!je.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${je.versions.web}/dist/`;je.wasm.wasmPaths=de.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}je.wasm.proxy=!1}je.webgpu&&(je.webgpu.powerPreference="high-performance"),e(we.logLevel??Pt.WARNING),we.backends.onnx={...je,setLogLevel:e}}var wr=async(e,t,r)=>{const s=await Z_(new Uint8Array(e),t);return(async n=>{const a=Oi(),o=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await ep(s,o);return Array.isArray(r)?r.map(l=>new V(i[l])):new V(i[r])})},ls=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=wr([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=wr([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=wr([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=wr([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=wr([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=wr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=wr([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=wr([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}},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"}),Io=de.IS_NODE_ENV?"cpu":"wasm";function rp(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 (${Io}).`),Io):Io}var Y1=(function(){let e;return async function(){if(e===void 0)if(!de.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),Ve=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"}),cf=Ve.fp32,uf=Object.freeze({[X1.wasm]:Ve.q8}),Ko=Object.freeze({[Ve.fp32]:"",[Ve.fp16]:"_fp16",[Ve.int8]:"_int8",[Ve.uint8]:"_uint8",[Ve.q8]:"_quantized",[Ve.q4]:"_q4",[Ve.q2]:"_q2",[Ve.q1]:"_q1",[Ve.q4f16]:"_q4f16",[Ve.q2f16]:"_q2f16",[Ve.q1f16]:"_q1f16",[Ve.bnb4]:"_bnb4"});function sp(e,t,r,{configDtype:s=null,warn:n}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===Ve.auto){if(s){const l=typeof s=="string"?s:s?.[t];if(l&&l!==Ve.auto&&Ve.hasOwnProperty(l))return l}i=uf[r]??cf}else a&&Ve.hasOwnProperty(a)?i=a:i=uf[r]??cf;return o&&n&&n(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var Js=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}),V=class Be{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...t){return tp(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new qb(t[0],t[1],t[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const s=r.reduce((n,a)=>n*a);for(let n=0;n<t;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(t){const[r,...s]=this.dims;if(t=qt(t,r),s.length>0){const n=s.reduce((a,o)=>a*o);return this._subarray(t,n,s)}else return new Be(this.type,[this.data[t]],s)}indexOf(t){const r=this.data;for(let s=0;s<r.length;++s)if(r[s]==t)return s;return-1}_subarray(t,r,s){const n=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new Be(this.type,o,s)}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 s=0;s<r.length;++s)r[s]=t(r[s],s,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]-=t;return this}clone(){return new Be(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],s=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=qt(h,this.dims[d],d),s.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[_,p]=h;if(_=_===null?0:qt(_,this.dims[d],d,!1),p=p===null?this.dims[d]:qt(p,this.dims[d],d,!1),_>p)throw new Error(`Invalid slice: ${h}`);const w=[Math.max(_,0),Math.min(p,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${h}`)}const n=s.map(([d,h])=>h-d),a=n.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride();let c=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){c=!1;break}if(c){const d=s[0][0]*l[0],h=s[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 _=n.length-1,p=d;_>=0;--_){const w=n[_];h+=(p%w+s[_][0])*l[_],p=Math.floor(p/w)}i[d]=o[h]}return new Be(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,s=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const n=this.data,a=n instanceof BigInt64Array||n 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=n.reduce(o,i);return t!==1&&(h=h**(1/t)),new Be(this.type,[h],[])}const[l,c,d]=Hs(o,this,r,s);if(t!==1)for(let h=0;h<c.length;++h)c[h]=c[h]**(1/t);return new Be(l,c,d)}normalize_(t=2,r=1){r=qt(r,this.dims.length);const s=this.norm(t,r,!0),n=this.data,a=s.data;for(let o=0;o<n.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)}n[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Oo(this.dims)}squeeze(t=null){return new Be(this.type,this.data,df(this.dims,t))}squeeze_(t=null){return this.dims=df(this.dims,t),this}unsqueeze(t){return new Be(this.type,this.data,hf(this.dims,t))}unsqueeze_(t){return this.dims=hf(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,t),n=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...s,n.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 n=0;n<t.length;++n)if(t[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}const s=this.data;if(r!==-1){const n=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=s.length/n}return new Be(this.type,s,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),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>t?1:0;return new Be("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<t?1:0;return new Be("bool",r,this.dims)}clamp_(t,r){const s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],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 Ni(this,t,r)}min(t=null,r=!1){if(t===null){const o=Yo(this.data)[0];return new Be(this.type,[o],[])}const[s,n,a]=Hs((o,i)=>Math.min(o,i),this,t,r,1/0);return new Be(s,n,a)}max(t=null,r=!1){if(t===null){const o=$e(this.data)[0];return new Be(this.type,[o],[])}const[s,n,a]=Hs((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Be(s,n,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=Yo(this.data)[1];return new Be("int64",[BigInt(s)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=$e(this.data)[1];return new Be("int64",[BigInt(s)],[])}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 Be(this.type,this.data.slice(),h)}const r=t.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((d,h)=>d*t[h]),a=n.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=Oo(s),c=Oo(n);for(let d=0;d<a;++d){let h=d,_=0;for(let p=0;p<n.length;++p){const w=Math.floor(h/c[p]);h=h%c[p];const v=w%s[p];_+=v*l[p]}i[d]=o[_]}return new Be(this.type,i,n)}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(!Js.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r;const s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(s&&!n)r=Number;else if(!s&&n)["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 Be(t,G1(this.data),this.dims);return new Be(t,Js[t].from(this.data,r),this.dims)}};function J1(e,t){const r=e.length,s=t.reduce((a,o)=>a*o);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let a=t.length-1;a>=0;a--)n=n.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return n[0]}function K1(e,t){const[r,s]=I1(e.data,e.dims,t);return new V(e.type,r,s)}function np(e,[t,r],s="bilinear",n=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=L1(e.data,[a,o,i],[t,r],s,n);return new V(e.type,l,[a,t,r])}async function It(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 s;if(t.length===2)s=[...e.dims.slice(0,2),...t];else if(t.length===3)s=[e.dims[0],...t];else if(t.length===4)s=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await ls.nearest_interpolate_4d;else if(r==="bilinear")n=await ls.bilinear_interpolate_4d;else if(r==="bicubic")n=await ls.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new V("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:e,s:a})}async function Z1(e,t){return await(await ls.matmul)({a:e,b:t})}async function _s(e,t){const r=await ls.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new V("int64",[BigInt(t)],[1])})}var In=e=>new V("int64",e,[e.length]);async function ap(e,t,r,s,n){return await(await ls.slice)({x:e,s:In(t),e:In(r),a:In(s),t:In(new Array(s.length).fill(1))})}function ek(e,t){const r=e.data,s=t.data,n=[e.dims[0],e.dims[2]],a=new r.constructor(n[0]*n[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,M=h+_;for(let k=0;k<i;++k){const A=Number(s[v+k]);w+=A,p+=r[M+k*l]*A}const y=p/w;a[c++]=y}}return new V(e.type,a,n)}function df(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,s)=>r!==1||!t.includes(s))),e}function hf(e,t){return t=qt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function qt(e,t,r=null,s=!0){if(e<-t||e>=t){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Ne(e,t=0){t=qt(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const s=r.reduce((o,i)=>o*i,1),n=new e[0].data.constructor(s),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;n.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 M=p%v;_===t&&(M+=o),h+=M*w,w*=r[_],p=Math.floor(p/v)}n[h]=l[d]}o+=c[t]}}return new V(a,n,r)}function or(e,t=0){return Ne(e.map(r=>r.unsqueeze(t)),t)}function Hs(e,t,r,s=!1,n=null){const a=t.data,o=t.dims;r=qt(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);n!==null&&l.fill(n);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 s||i.splice(r,1),[t.type,l,i]}function tk(e,t=null,r=1,s=!1){const n=e.data,a=e.dims;if(t===null){const p=n.reduce((y,k)=>y+k,0)/n.length,w=Math.sqrt(n.reduce((y,k)=>y+(k-p)**2,0)/(n.length-r)),v=new V(e.type,[p],[]);return[new V(e.type,[w],[]),v]}t=qt(t,a.length);const o=Ni(e,t,s),i=o.data,[l,c,d]=Hs((_,p,w,v)=>_+(p-i[v])**2,e,t,s);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return[new V(l,c,d),o]}function Ni(e,t=null,r=!1){const s=e.dims,n=e.data;if(t===null){const l=n.reduce((c,d)=>c+d,0);return new V(e.type,[l/n.length],[])}t=qt(t,s.length);const[a,o,i]=Hs((l,c)=>l+c,e,t,r);if(s[t]!==1)for(let l=0;l<o.length;++l)o[l]/=s[t];return new V(a,o,i)}function Oo(e){const t=new Array(e.length);for(let r=e.length-1,s=1;r>=0;--r)t[r]=s,s*=e[r];return t}function Di(e,t,r,s){const n=e.reduce((a,o)=>a*o,1);return new V(r,new s(n).fill(t),e)}function ot(e,t){let r,s;if(typeof t=="number")r="float32",s=Float32Array;else if(typeof t=="bigint")r="int64",s=BigInt64Array;else if(typeof t=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Di(e,t,r,s)}function Zo(e,t){return ot(e.dims,t)}function ft(e){return Di(e,1n,"int64",BigInt64Array)}function op(e){return ft(e.dims)}function ip(e){return Di(e,0n,"int64",BigInt64Array)}function lp(e){return ip(e.dims)}function rk(e){const t=e.reduce((r,s)=>r*s,1);return new V("float32",Float32Array.from({length:t},()=>Fi.gauss()),e)}function sk(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",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,a=e.data,o=new n(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 V(s,o,[e.dims[0],e.dims[1]/8])}async function cp(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await sn(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function up(e,t){const r=await cp(e);return await Promise.all(r.map(s=>Yt(e,s,!0,t)))}function zi(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 nk=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ak(e,t,r,s){for(const n of Object.keys(e)){const a=t-e[n].length,o=r(n),i=new Array(a).fill(o);e[n]=s==="right"?Ht(e[n],i):Ht(i,e[n])}}function ok(e,t){for(const r of Object.keys(e))e[r].length=t}function Sr(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const s=e[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}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 ae=class extends _t{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new yx(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Sr(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Sr(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Sr(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Sr(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Sr(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Sr(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const s=Object.create(null);for(const{name:n,template:a}of this.chat_template){if(typeof n!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[n]=a}this.chat_template=s}this._compiled_template_cache=new Map;const r=ik(this._tokenizer);this.all_special_ids=r.map(s=>s.id),this.all_special_tokens=r.map(s=>s.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:a="main"}={}){const o=await up(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(t=>this._tokenizer.token_to_id(t))}_call(e,t={}){const{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,return_token_type_ids:a=null}=t;let{truncation:o=null,max_length:i=null}=t;const l=t.return_tensor??!0,c=Array.isArray(e);let d;if(c){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((_,p)=>this._encode_plus(_,{text_pair:r[p],add_special_tokens:s,return_token_type_ids:a}))}else d=e.map(_=>this._encode_plus(_,{add_special_tokens:s,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:a})]}if(i===null?i=this.model_max_length:o===null&&(n===!0?(ie.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),i=this.model_max_length):n===!1&&(ie.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(i=Math.min($e(d.map(_=>_.input_ids.length))[0],i??1/0)),i=Math.min(i,this.model_max_length??1/0),n||o)for(let _=0;_<d.length;++_)d[_].input_ids.length!==i&&(d[_].input_ids.length>i?o&&ok(d[_],i):n&&ak(d[_],i,p=>p==="input_ids"?this.pad_token_id:0,this.padding_side));const h={};if(l){if(!(n&&o)&&d.some(p=>{for(const w of Object.keys(p))if(p[w].length!==d[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const _=[d.length,d[0].input_ids.length];for(const p of Object.keys(d[0]))h[p]=new V("int64",BigInt64Array.from(d.flatMap(w=>w[p]).map(BigInt)),_)}else{for(const _ of Object.keys(d[0]))h[_]=d.map(p=>p[_]);if(!c)for(const _ of Object.keys(h))h[_]=h[_][0]}return h}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{ids:n,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:s??this.return_token_type_ids});return{input_ids:n,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:s}).ids}batch_decode(e,t={}){return e instanceof V&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof V&&(e=zi(e)),!Array.isArray(e)||e.length===0||!i0(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,t={}){let{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:d=!0,return_dict:h=!0,tokenizer_kwargs:_={},...p}=t;if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new p1(n),this._compiled_template_cache.set(n,w));const v=Object.create(null);for(const y of nk){const k=Sr(this.config,y);k&&(v[y]=k)}const M=w.render({messages:e,add_generation_prompt:a,tools:r,documents:s,...v,...p});if(o){const y=this._call(M,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:d,..._});return h?y:y.input_ids}return M}};function Bi(e,t,r,s){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 n=s.src_lang,a=s.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(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(n);break}}return s.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var dp={};ds(dp,{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:()=>Lk,MBart50Tokenizer:()=>Ok,MBartTokenizer:()=>hp,MPNetTokenizer:()=>zk,MarianTokenizer:()=>Ik,MgpstrTokenizer:()=>Nk,MobileBertTokenizer:()=>Dk,NllbTokenizer:()=>Bk,NougatTokenizer:()=>Rk,PreTrainedTokenizer:()=>ae,Qwen2Tokenizer:()=>Gk,RoFormerTokenizer:()=>Vk,RobertaTokenizer:()=>$k,SiglipTokenizer:()=>Uk,SpeechT5Tokenizer:()=>jk,SqueezeBertTokenizer:()=>qk,T5Tokenizer:()=>Wk,TokenizersBackend:()=>ae,VitsTokenizer:()=>Qk,Wav2Vec2CTCTokenizer:()=>Xk,WhisperTokenizer:()=>eT,XLMRobertaTokenizer:()=>tT,XLMTokenizer:()=>rT});var lk=class extends ae{return_token_type_ids=!0},ck=class extends ae{},uk=class extends ae{return_token_type_ids=!0},dk=class extends ae{},hk=class extends ae{},fk=class extends ae{},_k=class extends ae{},pk=class extends ae{},mk=class extends ae{},gk=class extends ae{},wk=class extends ae{},vk=class extends ae{},yk=class extends ae{return_token_type_ids=!0},bk=class extends ae{return_token_type_ids=!0},Mk=class extends ae{return_token_type_ids=!0},xk=class extends ae{},kk=class extends ae{return_token_type_ids=!0},Tk=class extends ae{},Ek=class extends ae{},Ak=class extends ae{},Ck=class extends ae{},Sk=class extends ae{},Pk=class extends ae{return_token_type_ids=!0},Fk=class extends ae{padding_side="left"},Lk=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Bi(this,e,t,r)}},Ik=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),ie.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[s,n]=r;return this.supported_language_codes.includes(s)||ie.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Ht([s],super._encode_text(n))}}},hp=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Bi(this,e,t,r)}},Ok=class extends hp{},Nk=class extends ae{},Dk=class extends ae{return_token_type_ids=!0},zk=class extends ae{},Bk=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Bi(this,e,t,r)}},Rk=class extends ae{},Gk=class extends ae{},$k=class extends ae{},Vk=class extends ae{return_token_type_ids=!0},Uk=class extends ae{},jk=class extends ae{},qk=class extends ae{return_token_type_ids=!0},Wk=class extends ae{},Hk=class extends Dt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},Qk=class extends ae{constructor(e,t){super(e,t),this._tokenizer.decoder=new Hk({type:"VitsDecoder"})}},Xk=class extends ae{},fp=[["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"]],Vn=new Map(fp),Yk=new Map([...fp.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]),Vn.has(e))t=e;else{const n=e.length===2?Vn.keys():Vn.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}var Kk="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",ff=new RegExp(`^[${Kk}]+$`,"gu"),Zk=.1,eT=class extends ae{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:n=!0}={}){if(s===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=[],M=!1,y=null;const k=new Set(this.all_special_ids);for(const C of e){const L=C.tokens,x=o?C.token_timestamps:null;let G=null,B=h;if("stride"in C){const[W,N,O]=C.stride;if(d-=N,y=W-O,N&&(B=N/s+h),O)for(let U=L.length-1;U>=0;--U){const Q=Number(L[U]);if(Q>=h){if(G!==null&&(Q-h)*s<y)break;G=Q}}}let j=[],X=[];for(let W=0;W<L.length;++W){const N=Number(L[W]);if(k.has(N)){const O=this.decode([N]),U=Vn.get(O.slice(2,-2));if(U!==void 0){if(a!==null&&U!==a&&!t){w.push(j);const Q=this.findLongestCommonSequence(w)[0],ee=this.decode(Q);c.text=ee,l.push(c),w=[],j=[],c=i()}a=c.language=U}}else if(N>=h&&N<=p){const O=(N-h)*s+d,U=qs(O,2);if(G!==null&&N>=G)M=!0;else if(M||w.length>0&&N<B)M=!1;else if(c.timestamp[0]===null)c.timestamp[0]=U;else if(U!==c.timestamp[0]){c.timestamp[1]=U,w.push(j),o&&v.push(X);const[Q,ee]=this.findLongestCommonSequence(w,v),I=this.decode(Q);if(c.text=I,o&&(c.words=this.collateWordTimestamps(Q,ee,a),c.words.length>0&&c.timestamp[1]!==null))for(const D of c.words)D.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=D.timestamp[0]&&(D.timestamp[1]=c.timestamp[1]);l.push(c),w=[],j=[],v=[],X=[],c=i()}}else if(j.push(N),o){let O=qs(x[W]+d,2),U;if(W+1<x.length){U=qs(x[W+1]+d,2);const Q=this.decode([N]);ff.test(Q)&&(U=qs(Math.min(O+s,U),2))}else U=null;X.push([O,U])}}if("stride"in C){const[W,N,O]=C.stride;d+=W-O}j.length>0?(w.push(j),o&&v.push(X)):w.every(W=>W.length===0)&&(c=i(),w=[],j=[],v=[],X=[])}if(w.length>0){if(n&&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,L]=this.findLongestCommonSequence(w,v),x=this.decode(C);c.text=x,o&&(c.words=this.collateWordTimestamps(C,L,a)),l.push(c)}let A=Object.create(null);const E=l.map(C=>C.text).join("");if(t||r){for(let C=0;C<l.length;++C){const L=l[C];t||delete L.timestamp,r||delete L.language}if(o){const C=[];for(const L of l)for(const x of L.words)C.push(x);A={chunks:C}}else A={chunks:l}}return[E,A]}findLongestCommonSequence(e,t=null){let r=e[0],s=r.length,n=[];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=[s,s,0,0];const _=c.length;for(let A=1;A<s+_;++A){const E=Math.max(0,s-A),C=Math.min(s,s+_-A),L=r.slice(E,C),x=Math.max(0,A-s),G=Math.min(_,A),B=c.slice(x,G);if(L.length!==B.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let j;a?j=L.filter((N,O)=>N===B[O]&&i[E+O][0]-Zk<=t[l][x+O][0]).length:j=L.filter((N,O)=>N===B[O]).length;const X=A/1e4,W=j/A+X;j>1&&W>d&&(d=W,h=[E,C,x,G])}const[p,w,v,M]=h,y=Math.floor((w+p)/2);let k=Math.floor((M+v)/2);if(a&&d===0&&s>0){const A=i[s-1][0],E=t[l].findIndex(C=>C[0]>=A);k=E===-1?c.length:E}n.push(...r.slice(0,y)),r=c.slice(k),s=r.length,a&&(o.push(...i.slice(0,y)),i=t[l].slice(k))}return n.push(...r),a?(o.push(...i),[n,o]):[n,[]]}collateWordTimestamps(e,t,r){const[s,n,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<s.length;++i){const l=a[i];o.push({text:s[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,s=`"'.。,,!!??::”)]}、`){t=t??"english";let n,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,a,o]=this.splitTokensOnUnicode(e):[n,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,a,o,r,s)}decode(e,t){let r;return t?.decode_with_timestamps?(e instanceof V&&(e=zi(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){const r=t?.time_precision??.02,s=this.all_special_ids.at(-1)+1;let n=[[]];for(let a of e)if(a=Number(a),a>=s){const o=((a-s)*r).toFixed(2);n.push(`<|${o}|>`),n.push([])}else n[n.length-1].push(a);return n=n.map(a=>typeof a=="string"?a:super.decode(a,t)),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],n=[],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)&&(s.push(h),n.push(o),a.push(i),o=[],i=[],l+=h.length)}return[s,n,a]}splitTokensOnSpaces(e){const[t,r,s]=this.splitTokensOnUnicode(e),n=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],c=r[i],d=s[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=ff.test(p);if(h||_||w||n.length===0)n.push(l),a.push(c),o.push(d);else{const v=n.length-1;n[v]+=l,a[v].push(...c),o[v].push(...d)}}return[n,a,o]}mergePunctuations(e,t,r,s,n){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(" ")&&s.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=Ht(o[l],o[c]),i[c]=Ht(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&n.includes(a[c])?(a[l]+=a[c],o[l]=Ht(o[l],o[c]),i[l]=Ht(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 ae{},rT=class extends ae{return_token_type_ids=!0;constructor(e,t){super(e,t),ie.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:s=null,local_files_only:n=!1,revision:a="main"}={}){const[o,i]=await up(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let c=dp[l];return c||(ie.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=ae),new c(o,i)}},ca="https://github.com/huggingface/transformers.js/issues/new/choose",Ri="preprocessor_config.json",Ks=Ri,_p="processor_config.json",pp="chat_template.jinja",Ee=class extends _t{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([this.uses_processor_config?Yt(e,_p,!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?Ii(e,pp,!0,t):null]);return new this(r,s,n)}},ei={};ds(ei,{ChatterboxProcessor:()=>FT,CohereAsrProcessor:()=>IT,Florence2Processor:()=>OE,Gemma3Processor:()=>NE,Gemma3nProcessor:()=>DE,Gemma4Processor:()=>zE,Glm46VProcessor:()=>BE,GraniteSpeechProcessor:()=>RE,GroundingDinoProcessor:()=>$E,Idefics3Processor:()=>yf,JinaCLIPProcessor:()=>WE,Lfm2VlProcessor:()=>HE,LlavaProcessor:()=>QE,MgpstrProcessor:()=>XE,MoonshineProcessor:()=>YE,OwlViTProcessor:()=>JE,PaliGemmaProcessor:()=>ZE,Phi3VProcessor:()=>t2,PixtralProcessor:()=>r2,Processor:()=>Ee,PyAnnoteProcessor:()=>s2,Qwen2VLProcessor:()=>qi,Qwen2_5_VLProcessor:()=>Wp,Qwen3VLProcessor:()=>n2,Sam2Processor:()=>Qp,Sam2VideoProcessor:()=>a2,SamProcessor:()=>Hp,SmolVLMProcessor:()=>yf,SpeechT5Processor:()=>o2,UltravoxProcessor:()=>i2,VLChatProcessor:()=>qE,VoxtralProcessor:()=>d2,VoxtralRealtimeProcessor:()=>_2,Wav2Vec2Processor:()=>p2,Wav2Vec2ProcessorWithLM:()=>m2,WhisperProcessor:()=>g2});var it=class extends _t{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await Yt(e,Ri,!0,t);return new this(r)}};function st(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Gi={};ds(Gi,{ASTFeatureExtractor:()=>gT,ChatterboxFeatureExtractor:()=>wT,ClapFeatureExtractor:()=>vT,CohereAsrFeatureExtractor:()=>bT,DacFeatureExtractor:()=>bp,EncodecFeatureExtractor:()=>vp,FeatureExtractor:()=>it,Gemma3nAudioFeatureExtractor:()=>Mp,Gemma4AudioFeatureExtractor:()=>xp,GraniteSpeechFeatureExtractor:()=>MT,MoonshineFeatureExtractor:()=>xT,ParakeetFeatureExtractor:()=>yp,PyAnnoteFeatureExtractor:()=>kp,SeamlessM4TFeatureExtractor:()=>kT,SnacFeatureExtractor:()=>TT,SpeechT5FeatureExtractor:()=>ET,VoxtralRealtimeFeatureExtractor:()=>ST,Wav2Vec2FeatureExtractor:()=>AT,WeSpeakerFeatureExtractor:()=>CT,WhisperFeatureExtractor:()=>PT});var sT=()=>{},nT=sT;async function mp(e,t){if(de.IS_BROWSER_ENV){if(de.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(de.IS_FS_AVAILABLE)t.stream(),vt.createWriteStream(e),await nT();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 Ys(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});typeof t>"u"&&ie.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);const n=await s.decodeAudioData(r);let a;if(n.numberOfChannels===2){const o=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<n.length;++c)a[c]=o*(i[c]+l[c])/2}else a=n.getChannelData(0);return a}var oT=aT;function gp(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,s=2*Math.PI/(e-1),n=new Float64Array(e);for(let a=0;a<e;++a)n[a]=t-r*Math.cos(a*s);return n}function _f(e){return gp(e,.5)}function iT(e){return gp(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,s=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*s:3*e/200};function No(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(s=>r(s))}var cT={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?t*Math.exp(s*(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(s=>r(s))}function dT(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),s=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const n=t.length-2,a=Array.from({length:n},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<n;++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 pf(e,t,r){const s=(t-e)/(r-1);return Float64Array.from({length:r},(n,a)=>e+s*a)}function Qt(e,t,r,s,n,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>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);const l=No(r,o),c=No(s,o),d=pf(l,c,t+2);let h=uT(d,o),_;if(i){const w=n/((e-1)*2);_=No(Float64Array.from({length:e},(v,M)=>M*w),o),h=d}else _=pf(0,Math.floor(n/2),e);const p=dT(_,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){const v=p[w],M=2/(h[w+2]-h[w]);for(let y=0;y<e;++y)v[y]*=M}return p}function hT(e,t,r){const s=new e.constructor(e.length+t+r),n=e.length-1;for(let a=0;a<e.length;++a)s[t+a]=e[a];for(let a=1;a<=t;++a)s[t-a]=e[Jn(a,n)];for(let a=1;a<=r;++a)s[n+t+a]=e[Jn(n-a,n)];return s}function wp(e,t,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);const a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(s,e[o])-a);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");const o=$e(e)[0]-n;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,s=null){return wp(e,20,t,r,s)}function _T(e,t=1,r=1e-10,s=null){return wp(e,10,t,r,s)}async function Jt(e,t,r,s,{fft_length:n=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:M=1e-10,db_range:y=null,remove_dc_offset:k=null,min_num_frames:A=null,max_num_frames:E=null,do_pad:C=!0,transpose:L=!1,mel_offset:x=0,mel_floor_mode:G="clamp"}={}){const B=t.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(B!==r)throw new Error(`Length of the window (${B}) must equal frame_length (${r})`);if(s<=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 H=Math.floor(r/2);switch(i){case"reflect":{e=hT(e,H,H);break}case"constant":{const he=new e.constructor(e.length+2*H);he.set(e,H),e=he;break}case"semicausal":{const he=new e.constructor(e.length+H);he.set(e,H),e=he;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let j=Math.floor(1+Math.floor((e.length-r)/s));A!==null&&j<A&&(j=A);const X=l?Math.floor(n/2)+1:n;let W=j,N=j;E!==null&&(E>j?C&&(N=E):N=W=E);const O=new D1(n),U=new Float64Array(n),Q=new Float64Array(O.outputBufferSize),ee=new Float32Array(X*N);for(let H=0;H<W;++H){const he=H*s,ke=Math.min(e.length-he,r);ke!==r&&U.fill(0,0,r);for(let oe=0;oe<ke;++oe)U[oe]=e[he+oe];if(k){let oe=0;for(let Le=0;Le<ke;++Le)oe+=U[Le];const ut=oe/ke;for(let Le=0;Le<ke;++Le)U[Le]-=ut}if(c!==null){for(let oe=ke-1;oe>=1;--oe)U[oe]-=c*U[oe-1];U[0]*=1-c}for(let oe=0;oe<t.length;++oe)U[oe]*=t[oe];O.realTransform(Q,U);for(let oe=0;oe<X;++oe){const ut=oe<<1;ee[oe*N+H]=Q[ut]**2+Q[ut+1]**2}}if(a!==null&&a!==2){const H=a/2;for(let he=0;he<ee.length;++he)ee[he]**=H}const I=h.length;let D=await Z1(new V("float32",h.flat(),[I,X]),new V("float32",ee,[X,N]));L&&(D=D.transpose(1,0));const R=D.data;if(G==="add")for(let H=0;H<R.length;++H)R[H]=x+R[H]+_;else for(let H=0;H<R.length;++H)R[H]=x+Math.max(_,R[H]);if(a!==null&&p!==null){const H=Math.min(R.length,W*I);switch(p){case"log":for(let he=0;he<H;++he)R[he]=Math.log(R[he]);break;case"log10":for(let he=0;he<H;++he)R[he]=Math.log10(R[he]);break;case"log10_max_norm":{for(let oe=0;oe<H;++oe)R[oe]=Math.log10(R[oe]);const ke=(w??$e(R)[0])-8;for(let oe=0;oe<H;++oe)R[oe]=(Math.max(R[oe],ke)+4)/4;break}case"dB":if(a===1)fT(R,v,M,y);else if(a===2)_T(R,v,M,y);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 D}function ur(e,t,{periodic:r=!0,frame_length:s=null,center:n=!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=_f(a);break;case"hamming":o=iT(a);break;case"povey":o=_f(a).map(c=>Math.pow(c,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),s===null||e===s)return o;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);const i=new Float64Array(s),l=n?Math.floor((s-e)/2):0;return i.set(o,l),i}function pT(e,t){const r=e.reduce((a,o)=>a+o.length,0),s=new ArrayBuffer(44),n=new DataView(s);return On(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),On(n,8,"WAVE"),On(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,t*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),On(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...e.map(a=>a.buffer)],{type:"audio/wav"})}function On(e,t,r){for(let s=0;s<r.length;++s)e.setUint8(t+s,r.charCodeAt(s))}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((s,n)=>s+n.length,0),t=new Float32Array(e);let r=0;for(const s of this.audio)t.set(s,r),r+=s.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 mp(e,this.toBlob())}},gT=class extends it{constructor(e){super(e);const t=this.config.sampling_rate,r=Qt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ur(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Jt(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){st(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,s=t.data;for(let n=0;n<s.length;++n)s[n]=(s[n]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},vp=class extends it{async _call(e){st(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 V("float32",e,r)}}},wT=class extends it{async _call(e){st(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new V("float32",e,t)}}},vT=class extends it{constructor(e){super(e),this.mel_filters=Qt(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=Qt(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=ur(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,s){let n;const a=e.length-t;if(a>0)if(r==="rand_trunc"){const o=Math.floor(Fi.random()*(a+1));e=e.subarray(o,o+t),n=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),s==="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(s==="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`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return Jt(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 st(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,yp=class extends it{constructor(e){super(e),this.config.mel_filters??=Qt(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=ur(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 s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await Jt(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){st(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),s=t.data;s.fill(0,r*t.dims[1]);const[n,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=s[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 M=v*a+d;s[M]=(s[M]-h)*w}}const c=new BigInt64Array(n);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new V("int64",c,[1,n])}}},bT=class extends yp{_apply_dither(e){const t=this.config.dither??0;if(t<=0)return e;const r=new la(e.length);for(let s=0;s<e.length;++s)e[s]+=t*r.gauss();return e}split_audio(e){const t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,s=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,a=Math.max(1,Math.round(t*n)),o=Math.max(1,Math.round(r*n));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,s),_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_}return i}_find_split_point_energy(e,t,r,s){const n=r-t;if(n<=s)return Math.floor((t+r)/2);let a=1/0,o=t;const i=n-s;for(let l=0;l<=i;l+=s){let c=0;for(let d=0;d<s;++d){const h=e[t+l+d];c+=h*h}c=Math.sqrt(c/s),c<a&&(a=c,o=t+l)}return o}async _call(e){st(e,"CohereAsrFeatureExtractor");const t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},bp=class extends vp{},Mp=class extends it{constructor(e){super(e);const{fft_length:t,feature_size:r,min_frequency:s,max_frequency:n,sampling_rate:a,frame_length:o}=this.config,i=Qt(Math.floor(1+t/2),r,s,n,a,null,"htk",!1);this.mel_filters=i,this.window=ur(o,"hann")}async _extract_fbank_features(e,t){return Jt(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:s=!0,pad_to_multiple_of:n=128}={}){if(st(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),s&&e.length%n!==0){const i=n-e.length%n,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=ot([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},xp=class extends Mp{async _extract_fbank_features(e,t){const{frame_length:r,hop_length:s,fft_length:n}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/s)+1;return Jt(e,this.window,r,s,{fft_length:n,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={}){st(e,"Gemma4AudioFeatureExtractor");const r=e.length,s=await super._call(e,t),{input_features:n}=s,[,a,o]=n.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=n.data;for(let w=0;w<a;++w)_[w]||p.fill(0,w*o,(w+1)*o);return s.input_features_mask=new V("bool",_,[1,a]),s}},MT=class extends it{constructor(e){super(e);const{n_fft:t,win_length:r,n_mels:s,sample_rate:n}=e.melspec_kwargs;this.mel_filters=Qt(Math.floor(1+t/2),s,0,n/2,n,null,"htk");const a=ur(r,"hann");this.window=new Float64Array(t);const o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){st(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:r,n_mels:s}=this.config.melspec_kwargs,n=1+Math.floor((e.length-1)/r),a=n-n%2;return{input_features:(await Jt(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*s).unsqueeze_(0)}}},xT=class extends it{async _call(e){st(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new V("float32",e,t)}}},kp=class extends it{async _call(e){st(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new V("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,s=[];for(const n of e.tolist()){const a=[];let o=-1;for(let i=0;i<n.length;++i){const l=rt(n[i]),[c,d]=$e(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)}s.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return s}},kT=class extends it{constructor(e){super(e);const t=this.config.sampling_rate,r=Qt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ur(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Jt(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:s=!0,return_attention_mask:n=!0}={}){st(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(s){const[p,w]=a.dims,v=a.data;for(let M=0;M<w;++M){let y=0;for(let C=0;C<p;++C)y+=v[C*w+M];const k=y/p;let A=0;for(let C=0;C<p;++C)A+=(v[C*w+M]-k)**2;A/=p-1;const E=Math.sqrt(A+1e-7);for(let C=0;C<p;++C){const L=C*w+M;v[L]=(v[L]-k)/E}}}let o;if(t){const[p,w]=a.dims,v=a.data,M=p%r;if(M>0){const y=new Float32Array(w*(p+M));y.set(v),y.fill(this.config.padding_value,v.length);const k=p+M;a=new V(a.type,y,[k,w]),n&&(o=new V("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(n){const p=h.dims[1],w=new BigInt64Array(p);if(o){const v=o.data;for(let M=1,y=0;M<i;M+=c,++y)w[y]=v[M]}else w.fill(1n);_.attention_mask=new V("int64",w,[1,p])}return _}},TT=class extends bp{},ET=class extends it{},AT=class extends it{_zero_mean_unit_var_norm(e){const r=e.reduce((n,a)=>n+a,0)/e.length,s=e.reduce((n,a)=>n+(a-r)**2,0)/e.length;return e.map(n=>(n-r)/Math.sqrt(s+1e-7))}async _call(e){st(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 V("float32",t,r),attention_mask:new V("int64",new BigInt64Array(t.length).fill(1n),r)}}},CT=class extends it{constructor(e){super(e);const t=this.config.sampling_rate,r=Qt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=ur(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),Jt(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){st(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,s=t.data,[n,a,o]=t.dims;for(let i=0;i<n;++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;++_)s[h+_]-=r[c+_]}}}return{input_features:t}}},ST=class extends it{constructor(e){super(e),this.config.mel_filters??=Qt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=ur(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){const{n_fft:r,hop_length:s,mel_filters:n,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/s:(e.length-r)/s);return await Jt(e,this.window,r,s,{power:2,mel_filters:n,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 st(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},PT=class extends it{constructor(e){super(e),this.config.mel_filters??=Qt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=ur(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await Jt(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}={}){st(e,"WhisperFeatureExtractor");let r;const s=t??this.config.n_samples;return e.length>s?(e.length>this.config.n_samples&&ie.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,s)):(r=new Float32Array(s),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Et=class{static async from_pretrained(e,t={}){const r=await Yt(e,Ri,!0,t),s=r.feature_extractor_type,n=Gi[s];if(!n)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${ca}.`);return new n(r)}},FT=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e,t=null){const r=this.tokenizer(e),s=t?await this.feature_extractor(t):{};return{...r,...s}}},LT=new Set(["ja","zh"]),IT=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){const t=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){const r=e.filter(a=>a&&a.trim());if(r.length===0)return"";const s=LT.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(s)}async _call(e){return await this.feature_extractor(e)}},ti={},Fr,Tp,vr;if(de.IS_WEB_ENV)Fr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},vr=self.createImageBitmap,Tp=self.ImageData;else if(ti)vr=async e=>{const r=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new Ot(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.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"]]),Ot=class jt{constructor(t,r,s,n){this.data=t,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof jt)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(!de.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const s=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new jt(s,t.width,t.height,4)}static async fromURL(t){const r=await Ys(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const s=await r.blob();return this.fromBlob(s)}static async fromBlob(t){if(de.IS_WEB_ENV){const r=await vr(t),s=Fr(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=ti(await t.arrayBuffer());return await vr(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new jt(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,s=0;r<this.data.length;r+=this.channels){const n=this.data[r],a=this.data[r+1],o=this.data[r+2];t[s++]=Math.round(.2989*n+.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,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=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,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2],t[s++]=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,s=t.data,n=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(n*4);for(let o=0,i=0,l=0;o<n;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=s[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<n;++a)r[4*a+3]=s[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:s=2}={}){if(this.width===t&&this.height===r)return this;let n=OT[s]??s;const a=Oh(t),o=Oh(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),de.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Fr(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new jt(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(ie.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await vr(i)}}async pad([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),t===0&&r===0&&s===0&&n===0)return this;if(de.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+s+n,c=Fr(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,s,this.width,this.height),new jt(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:r,top:s,bottom:n});return await vr(a)}}async crop([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),t===0&&r===0&&s===this.width-1&&n===this.height-1)return this;const a=s-t+1,o=n-r+1;if(de.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Fr(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new jt(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 vr(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;const s=(this.width-t)/2,n=(this.height-r)/2;if(de.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=Fr(t,r).getContext("2d");let l=0,c=0,d=0,h=0;return s>=0?l=s:d=-s,n>=0?c=n:h=-n,i.drawImage(o,l,c,t,r,d,h,t,r),new jt(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(s>=0&&n>=0)a=a.extract({left:Math.floor(s),top:Math.floor(n),width:t,height:r});else if(s<=0&&n<=0){const o=Math.floor(-n),i=Math.floor(-s);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;n<0?(o[0]=Math.floor(-n),o[1]=r-this.height-o[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=t-this.width-l[0]):c=Math.floor(s),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 vr(a)}}async toBlob(t="image/png",r=1){if(!de.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 V("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(!de.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Fr(t.width,t.height),s=new Tp(t.data,t.width,t.height);return r.getContext("2d").putImageData(s,0,0),r}split(){const{data:t,width:r,height:s,channels:n}=this,a=t.constructor,o=t.length/n,i=Array.from({length:n},()=>new a(o));for(let l=0;l<o;++l){const c=n*l;for(let d=0;d<n;++d)i[d][l]=t[c+d]}return i.map(l=>new jt(l,r,s,1))}_update(t,r,s,n=null){return this.data=t,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new jt(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(de.IS_WEB_ENV){if(de.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),s=NT.get(r)??"image/png",n=await this.toBlob(s);return mp(t,n)}else if(de.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(de.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return ti(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Ot.read.bind(Ot);function mf(e,t,r=0,s=null){const n=e/t;let a=B1(n)*t;return s!==null&&a>s&&(a=Math.floor(n)*t),a<r&&(a=Math.ceil(n)*t),a}function gf([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function Ep([e,t,r,s]){return[e-r/2,t-s/2,e+r/2,t+s/2]}function ua(e,t=.5,r=null,s=!1){const n=e.logits,a=e.pred_boxes,[o,i,l]=n.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=n[d],w=a[d];for(let v=0;v<i;++v){let M=p[v],y=[],k;if(s){k=M.sigmoid().data;for(let A=0;A<k.length;++A)k[A]>t&&y.push(A)}else{let A=$e(M.data)[1];if(A===l-1||(k=rt(M.data),k[A]<t))continue;y.push(A)}for(const A of y){let E=w[v].data;E=Ep(E),h!==null&&(E=E.map((C,L)=>C*h[(L+1)%2])),_.boxes.push(E),_.classes.push(A),_.scores.push(k[A])}}c.push(_)}return c}function Ap(e,t=null){const r=e.logits,s=r.dims[0];if(t!==null&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const n=[];for(let a=0;a<s;++a){const o=t!==null?t[a]:null;let i=r[a];o!==null&&(i=np(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new V("int32",new Int32Array(l*c),[l,c]),h=i[0].data,_=d.data;for(let v=1;v<i.dims[0];++v){const M=i[v].data;for(let y=0;y<M.length;++y)M[y]>h[y]&&(h[y]=M[y],_[y]=v)}const p=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const M=_[v];p[M]=M}const w=p.filter(v=>v!==void 0);n.push({segmentation:d,labels:w})}return n}function DT(e,t,r,s){const n=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=$e(l.data)[1];if(d===s)continue;const _=rt(l.data)[d];_>r&&(n.push(c),a.push(_),o.push(d))}return[n,a,o]}function zT(e,t,r,s=.5,n=.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]>=s&&++i;let c=o>0&&i>0;return c&&(c=o/i>n),[c,a]}function BT(e,t,r,s,n,a=null,o=null){const[i,l]=o??e[0].dims,c=new V("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=np(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 M=t[v];const y=e[v].data;for(let k=0;k<y.length;++k)y[k]*=M,y[k]>_[k]&&(h[k]=v,_[k]=y[k])}let p=0;const w=c.data;for(let v=0;v<r.length;++v){const M=r[v],[y,k]=zT(h,e,v,s,n);if(y){++p;for(const A of k)w[A]=p;d.push({id:p,label_id:M,score:t[v]})}}return[c,d]}function $i(e,t,r=28,s=3136,n=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>n){const l=Math.sqrt(a*e*t/n);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<s){const l=Math.sqrt(s/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function Cp(e,t=.5,r=.5,s=.8,n=null,a=null){n===null&&(ie.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=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],M=l[p],[y,k,A]=DT(v,M,t,h);if(A.length===0){let[L,x]=w??M.dims.slice(-2),G=new V("int32",new Int32Array(L*x).fill(-1),[L,x]);_.push({segmentation:G,segments_info:[]});continue}let[E,C]=BT(y,k,A,r,s,n,w);_.push({segmentation:E,segments_info:C})}return _}function Sp(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var le=class extends _t{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 s=e.height,n=e.width,a=t.height,o=t.width;let i=Math.min(s,a),l=Math.min(n,o);return i===s&&l===n?e:(s>n?l=Math.floor(n*i/s):n>s&&(i=Math.floor(s*l/n)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),s=Yo(r.data)[0],a=$e(r.data)[0]-s;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]-s)/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:s="constant",center:n=!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]=n?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+p)*c,M=w*i;for(let y=0;y<i;++y){const k=(v+y+_)*l,A=(M+y)*l;for(let E=0;E<l;++E)h[k+E]=e[A+E]}}if(s==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const w=o-1,v=i-1;for(let M=0;M<d;++M){const y=M*c,k=Jn(M,w)*i;for(let A=0;A<c;++A){if(M<o&&A<i)continue;const E=(y+A)*l,C=(k+Jn(A,v))*l;for(let L=0;L<l;++L)h[E+L]=e[C+L]}}}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,s]=e.size;let n,a;if(this.do_thumbnail){const{height:o,width:i}=t;n=Math.min(o,i)}else Number.isInteger(t)?(n=t,a=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,a=t.longest_edge);if(n!==void 0||a!==void 0){const o=n===void 0?1:Math.max(n/r,n/s),i=r*o,l=s*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]=gf([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/s,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=mf(l*s,this.config.ensure_multiple_of),o=mf(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return gf([r,s],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:s=null,do_convert_grayscale:n=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(s??this.do_convert_rgb?e=e.rgb():n&&(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 V("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(n=>this.preprocess(n)));return{pixel_values:or(r.map(n=>n.pixel_values),0),original_sizes:r.map(n=>n.original_size),reshaped_input_sizes:r.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await Yt(e,Ks,!0,t);return new this(r)}},ta={};ds(ta,{BeitFeatureExtractor:()=>RT,BitImageProcessor:()=>GT,CHMv2ImageProcessor:()=>VT,CLIPFeatureExtractor:()=>UT,CLIPImageProcessor:()=>Pp,ChineseCLIPFeatureExtractor:()=>$T,ConvNextFeatureExtractor:()=>jT,ConvNextImageProcessor:()=>Fp,DINOv3ViTImageProcessor:()=>HT,DPTFeatureExtractor:()=>XT,DPTImageProcessor:()=>Op,DeiTFeatureExtractor:()=>qT,DeiTImageProcessor:()=>Lp,DetrFeatureExtractor:()=>WT,DetrImageProcessor:()=>Ip,DonutFeatureExtractor:()=>QT,DonutImageProcessor:()=>Vi,EfficientNetImageProcessor:()=>YT,GLPNFeatureExtractor:()=>tE,Gemma3ImageProcessor:()=>JT,Gemma4ImageProcessor:()=>Np,Glm46VImageProcessor:()=>eE,GroundingDinoImageProcessor:()=>rE,Idefics3ImageProcessor:()=>wf,ImageFeatureExtractor:()=>le,ImageProcessor:()=>le,JinaCLIPImageProcessor:()=>nE,Lfm2VlImageProcessor:()=>cE,LlavaOnevisionImageProcessor:()=>uE,Mask2FormerImageProcessor:()=>hE,MaskFormerFeatureExtractor:()=>dE,MaskFormerImageProcessor:()=>Ui,MobileNetV1FeatureExtractor:()=>fE,MobileNetV1ImageProcessor:()=>zp,MobileNetV2FeatureExtractor:()=>_E,MobileNetV2ImageProcessor:()=>Bp,MobileNetV3FeatureExtractor:()=>pE,MobileNetV3ImageProcessor:()=>Rp,MobileNetV4FeatureExtractor:()=>mE,MobileNetV4ImageProcessor:()=>Gp,MobileViTFeatureExtractor:()=>gE,MobileViTImageProcessor:()=>$p,NougatImageProcessor:()=>wE,OwlViTFeatureExtractor:()=>vE,OwlViTImageProcessor:()=>ji,Owlv2ImageProcessor:()=>yE,Phi3VImageProcessor:()=>ME,PixtralImageProcessor:()=>xE,PvtImageProcessor:()=>kE,Qwen2VLImageProcessor:()=>Dp,RTDetrImageProcessor:()=>TE,Sam2ImageProcessor:()=>Bo,Sam3ImageProcessor:()=>Bo,SamImageProcessor:()=>Bo,SapiensFeatureExtractor:()=>EE,SapiensImageProcessor:()=>Vp,SegformerFeatureExtractor:()=>AE,SegformerImageProcessor:()=>Up,SiglipImageProcessor:()=>CE,SmolVLMImageProcessor:()=>wf,Swin2SRImageProcessor:()=>SE,VLMImageProcessor:()=>sE,ViTFeatureExtractor:()=>PE,ViTImageProcessor:()=>jp,VitMatteImageProcessor:()=>FE,VitPoseImageProcessor:()=>LE,YolosFeatureExtractor:()=>IE,YolosImageProcessor:()=>qp});var RT=class extends le{},GT=class extends le{},$T=class extends le{},VT=class extends le{},Pp=class extends le{},UT=class extends Pp{},Fp=class extends le{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const r=Math.floor(t/this.crop_pct),[s,n]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(s,n,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},jT=class extends Fp{},Lp=class extends le{},qT=class extends Lp{},Ip=class extends le{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],s=ot(r,1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return ua(...e)}post_process_panoptic_segmentation(...e){return Cp(...e)}post_process_instance_segmentation(...e){return Sp(...e)}},WT=class extends Ip{},HT=class extends le{},Vi=class extends le{pad_image(e,t,r,s={}){const[n,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,...s})}},QT=class extends Vi{},Op=class extends le{},XT=class extends Op{},YT=class extends le{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))}},JT=class extends le{};function KT(e,t,r,s,n){const a=s*r**2,o=Math.sqrt(a/(e*t)),i=n*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(s/n**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,s,n,a,o){const i=Math.floor(t/n),l=Math.floor(r/n),c=i*l,d=n*n*s,h=new Float32Array(a*d);let _=0;for(let v=0;v<i;++v)for(let M=0;M<l;++M)for(let y=0;y<n;++y){const k=(v*n+y)*r*s+M*n*s;for(let A=0;A<n;++A){const E=k+A*s;for(let C=0;C<s;++C)h[_++]=e[E+C]}}const p=new BigInt64Array(a*2).fill(-1n);let w=0;for(let v=0;v<i;++v)for(let M=0;M<l;++M)p[w++]=BigInt(M),p[w++]=BigInt(v);return{patches:new V("float32",h,[a,d]),positions:new V("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var Np=class extends _t{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,s=this.max_soft_tokens*r**2,n=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){const[_,p]=KT(i.height,i.width,t,s,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,s,r);n.push(c),a.push(d),o.push(h)}return{pixel_values:or(n,0),image_position_ids:or(a,0),num_soft_tokens_per_image:o}}},Dp=class extends le{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.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 $i(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:s,reshaped_input_sizes:n}=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=Ne(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 V("int64",[c,h,_],[1,3]);return{pixel_values:p,image_grid_thw:w,original_sizes:s,reshaped_input_sizes:n}}},eE=class extends Dp{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,s=this.config.temporal_patch_size??2;return $i(e.height,e.width,r,this.min_pixels,this.max_pixels,s)}},tE=class extends le{},rE=class extends le{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,s=ft([r[0],r[2],r[3]]);return{...t,pixel_mask:s}}},wf=class extends le{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,s]=e.dims.slice(-2);const n=s/r;return s>=r?(s=Math.ceil(s/t)*t,r=Math.floor(s/n),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,s=Math.floor(r*n),s=Math.ceil(s/t)*t),{height:r,width:s}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let s;if(!Array.isArray(e))s=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?s=e:s=[e]}let n=[],a=[],o=[];const i=[],l=[];for(const M of s){let y=await Promise.all(M.map(E=>this.preprocess(E)));i.push(...y.map(E=>E.original_size)),l.push(...y.map(E=>E.reshaped_input_size)),y.forEach(E=>E.pixel_values.unsqueeze_(0));const{longest_edge:k}=this.max_image_size;let A;if(t??this.do_image_splitting){let E=new Array(y.length),C=new Array(y.length);A=await Promise.all(y.map(async(L,x)=>{const G=this.get_resize_for_vision_encoder(L.pixel_values,k),B=await It(L.pixel_values,{size:[G.height,G.width]}),{frames:j,num_splits_h:X,num_splits_w:W}=await this.split_image(B,this.max_image_size);return E[x]=X,C[x]=W,Ne(j,0)})),a.push(E),o.push(C)}else{const E=[k,k];A=await Promise.all(y.map(C=>It(C.pixel_values,{size:E}))),a.push(new Array(y.length).fill(0)),o.push(new Array(y.length).fill(0))}n.push(Ne(A,0))}const c=n.length,[d,h,_,p]=n[0].dims;let w,v;if(c===1)w=n[0].unsqueeze_(0),v=ot([c,d,_,p],!0);else{const M=Math.max(...n.map(A=>A.dims.at(0)));v=ot([c,M,_,p],!0);const y=v.data,k=M*_*p;for(let A=0;A<c;++A){const E=n[A].dims[0];if(E<M){n[A]=Ne([n[A],ot([M-E,h,_,p],0)],0);const C=A*k+E*_*p,L=(A+1)*k;y.fill(!1,C,L)}}w=or(n,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,s=t,n=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>r||o>s){i=Math.ceil(a/r),l=Math.ceil(o/s);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,M,y,k;p===i-1?(M=a-c,k=a):(M=p*c,k=(p+1)*c),w===l-1?(v=o-d,y=o):(v=w*d,y=(w+1)*d);const C=await ap(e,[M,v],[k,y],[2,3]);n.push(C)}const h=r,_=s;(a!==h||o!==_)&&(e=await It(e,{size:[h,_]}))}return n.push(e),{frames:n,num_splits_h:i,num_splits_w:l}}},sE=class extends le{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,s){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...s})}},nE=class extends le{constructor(e){const{resize_mode:t,fill_color:r,interpolation:s,size:n,...a}=e,o=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},i=s==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:n,do_normalize:!0})}};function vf(e,t){return Math.round(e/t)*t}function aE(e,t,r,s,n){let a=1/0,o=[1,1];const i=r*s;for(const l of t){const c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*n*n*l[0]*l[1]&&(o=l)}return o}function oE(e,t){const r=[],s=new Set;for(let n=e;n<=t;++n)for(let a=1;a<=n;++a)for(let o=1;o<=n;++o){const i=a*o;if(i>=e&&i<=t){const l=a<<16|o;s.has(l)||(s.add(l),r.push([a,o]))}}return r.sort((n,a)=>n[0]*n[1]-a[0]*a[1])}function iE(e,t){const[r,s,n,a]=e.dims,o=Math.floor(n/t),i=Math.floor(a/t),l=t*t*s,c=e.data,d=new Float32Array(r*o*i*l),h=n*a;for(let _=0;_<r;++_){const p=_*s*h,w=_*o*i*l;for(let v=0;v<o;++v)for(let M=0;M<i;++M){let y=w+(v*i+M)*l;for(let k=0;k<t;++k){const A=(v*t+k)*a+M*t;for(let E=0;E<t;++E){const C=A+E;for(let L=0;L<s;++L)d[y++]=c[p+L*h+C]}}}}return new V("float32",d,[r,o*i,l])}function lE(e,t){const[,r,s]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,r);let a=e;if(r<t){const o=new Float32Array(t*s);o.set(e.data),a=new V("float32",o,[1,t,s])}return{padded:a,mask:new V("int64",n,[t])}}var cE=class extends le{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,s=Math.max(this.encoder_patch_size,vf(e,r)),n=Math.max(this.encoder_patch_size,vf(t,r));return s*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=oE(this.min_tiles,this.max_tiles),[s,n]=aE(t/e,r,t,e,this.tile_size);return{grid_width:s,grid_height:n,target_width:this.tile_size*s,target_height:this.tile_size*n}}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 s=[],n=[],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),M=this.encoder_patch_size*this.downsample_factor,y=M**2,[k,A]=$i(Math.max(M,p),Math.max(M,w),M,this.min_image_tokens*y,this.max_image_tokens*y).map(B=>Math.max(M,B));let E,C=1,L=1;const x=this._is_image_too_large(p,w),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(x&&G){const{grid_width:B,grid_height:j,target_width:X,target_height:W}=this._get_grid_layout(p,w);C=j,L=B;const N=await It(v,{size:[W,X]});E=[];for(let O=0;O<j;++O)for(let U=0;U<B;++U){const Q=O*this.tile_size,ee=U*this.tile_size;E.push(N.slice(null,null,[Q,Q+this.tile_size],[ee,ee+this.tile_size]))}this.use_thumbnail&&B*j!==1&&E.push(await It(v,{size:[A,k]}))}else E=[await It(v,{size:[A,k]})];for(const B of E){const[,,j,X]=B.dims,W=iE(B,this.encoder_patch_size),{padded:N,mask:O}=lE(W,this.max_num_patches);s.push(N),n.push(O),a.push([Math.floor(j/this.encoder_patch_size),Math.floor(X/this.encoder_patch_size)])}o.push(C),i.push(L),l.push([A,k])}}const c={pixel_values:Ne(s,0),pixel_attention_mask:or(n,0),spatial_shapes:new V("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}},uE=class extends le{},Ui=class extends le{post_process_panoptic_segmentation(...e){return Cp(...e)}post_process_instance_segmentation(...e){return Sp(...e)}},dE=class extends Ui{},hE=class extends Ui{},zp=class extends le{},fE=class extends zp{},Bp=class extends le{},_E=class extends Bp{},Rp=class extends le{},pE=class extends Rp{},Gp=class extends le{},mE=class extends Gp{},$p=class extends le{},gE=class extends $p{},wE=class extends Vi{},ji=class extends le{post_process_object_detection(...e){return ua(...e)}},vE=class extends ji{},yE=class extends ji{},pt=336,bE=[2,3],{ceil:Do,floor:Kr,sqrt:zo}=Math,ME=class extends le{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 Kr((Kr(t/pt)*Kr(e/pt)+1)*r+1+(Kr(t/pt)+1)*zo(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[s,n]=e.size;let a=s/n,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,s={}){const[n,a]=t,o=pt*Do(n/pt),i=pt*Do(a/pt),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,...s})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||zo(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,s=await Promise.all(e.map(h=>this.preprocess(h))),n=s.map(h=>h.original_size),a=s.map(h=>h.reshaped_input_size),o=[];for(const{pixel_values:h}of s){h.unsqueeze_(0);const[_,p]=h.dims.slice(-2),w=await It(h,{size:[pt,pt],mode:"bicubic"});if(t>0){const v=[],M=zo(t),y=Kr(p/M),k=Kr(_/M);for(let E=0;E<M;++E)for(let C=0;C<M;++C){let L,x,G,B;E===M-1?(x=_-k,B=_):(x=E*k,B=(E+1)*k),C===M-1?(L=p-y,G=p):(L=C*y,G=(C+1)*y);const W=await ap(h,[x,L],[B,G],bE);v.push(W)}const A=await It(Ne(v,0),{size:[pt,pt],mode:"bicubic"});o.push(Ne([w,A],0))}else o.push(w)}const i=or(o,0),l=a.map(h=>h.map(_=>pt*Do(_/pt))),c=new V("int64",l.flat(),[r,2]),d=l.map(([h,_])=>this.calc_num_image_tokens_from_image_size(_,h));return{pixel_values:i,original_sizes:n,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},xE=class extends le{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[s,n]=e.size,a=Math.max(s,n)/r;let o=s,i=n;a>1&&(o=Math.floor(s/a),i=Math.floor(n/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]}},kE=class extends le{},TE=class extends le{post_process_object_detection(...e){return ua(...e)}},Bo=class extends le{reshape_input_points(e,t,r,s=!1){e=structuredClone(e);let n=Nh(e);if(n.length===3)s||(n=[1,...n]),e=[e];else if(n.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 V("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let r=Nh(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((s,n)=>s!==t.dims[n]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new V("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:s=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),r){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(r,n.input_points)}return s&&(n.input_boxes=this.reshape_input_points(s,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,r,{mask_threshold:s=0,binarize:n=!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 It(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await It(h,{mode:"bilinear",size:c}),n){const _=h.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)_[w]>s&&(p[w]=1);h=new V("bool",p,h.dims)}o.push(h)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:a=1}={}){}},Vp=class extends le{post_process_semantic_segmentation(...e){return Ap(...e)}},EE=class extends Vp{},Up=class extends le{post_process_semantic_segmentation(...e){return Ap(...e)}},AE=class extends Up{},CE=class extends le{},SE=class extends le{pad_image(e,t,r,s={}){const[n,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:n+(r-n%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}},jp=class extends le{},PE=class extends jp{},FE=class extends le{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))),s=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:or(r.map((a,o)=>Ne([a.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},LE=class extends le{post_process_pose_estimation(e,t,{threshold:r=null}={}){const s=e.tolist(),[n,a,o,i]=e.dims,l=[];for(let c=0;c<n;++c){const d=s[c],h=t[c],_=[];for(let p=0;p<h.length;++p){const w=h[p],v=[],M=[],y=[],k=w.at(-2)/i,A=w.at(-1)/o;for(let E=0;E<d.length;++E){let[C,L]=[0,0],x=0,G=-1/0;const B=d[E];for(let X=0;X<B.length;++X){const W=B[X];for(let N=0;N<W.length;++N){const O=W[N];x+=O,G=Math.max(G,O),C+=(N+.5)*O,L+=X*O}}if(r!=null&&G<r)continue;const j=[k*C/x,A*L/x];v.push(j),y.push(E),M.push(G)}_.push({bbox:w,scores:M,labels:y,keypoints:v})}l.push(_)}return l}},qp=class extends le{post_process_object_detection(...e){return ua(...e)}},IE=class extends qp{},lt=class{static async from_pretrained(e,t={}){const r=await Yt(e,Ks,!0,t),s=r.image_processor_type??r.feature_extractor_type;let n=ta[s?.replace(/Fast$/,"")];return n||(s!==void 0&&ie.warn(`Image processor type '${s}' not found, assuming base ImageProcessor. Please report this at ${ca}.`),n=le),new n(r)}},OE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;constructor(e,t,r){super(e,t,r);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),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[s,n]of this.task_prompts_with_input)if(r.includes(s)){t.push(n.replaceAll("{input}",r).replaceAll(s,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const s=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(s){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=s==="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]));n={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${s}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=await this.image_processor(e,r),n=t?this.tokenizer(this.construct_prompts(t),r):{};return{...s,...n}}},NE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;const{boi_token:s,image_token:n,eoi_token:a}=this.tokenizer.config;this.boi_token=s,this.image_token=n,this.eoi_token=a;const o=n.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
14
|
+
|
|
15
|
+
${s}${o}${a}
|
|
16
|
+
|
|
17
|
+
`}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let s;return t&&(s=await this.image_processor(t,r),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...s}}},DE=class extends Ee{static image_processor_class=lt;static feature_extractor_class=Et;static tokenizer_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:s,boa_token:n,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=s,this.boa_token=n,this.audio_token=a;const h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
18
|
+
|
|
19
|
+
${n}${h}${o}
|
|
20
|
+
|
|
21
|
+
`,this.image_token_id=i,this.boi_token=l,this.image_token=c;const _=c.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
22
|
+
|
|
23
|
+
${l}${_}${d}
|
|
24
|
+
|
|
25
|
+
`}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;r&&(n=await this.feature_extractor(r,s),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,s),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...a,...n}}},zE=class extends Ee{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;const{audio_token:s,boa_token:n,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=s,this.boa_token=n,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([Yt(e,_p,!0,t),Te.from_pretrained(e,t),Ii(e,pp,!1,t)]),a={tokenizer:s};return r.image_processor&&(a.image_processor=new Np(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new xp(r.feature_extractor)),new this(r,a,n)}_compute_audio_num_tokens(e,t){const r=Math.round(t*20/1e3),s=Math.round(t*10/1e3),n=Math.floor(r/2);let a=Math.floor((e+n-r-1)/s)+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,s={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,s);const o=n.num_soft_tokens_per_image;let i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>`
|
|
26
|
+
|
|
27
|
+
${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
|
|
28
|
+
|
|
29
|
+
`))}let a;if(r){const o=Array.isArray(r)?r:[r];a=await this.feature_extractor(o[0],s);const i=this.feature_extractor.config.sampling_rate??16e3;let l=0;e=e.map(c=>c.replaceAll(this.audio_token,()=>`
|
|
30
|
+
|
|
31
|
+
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
|
|
32
|
+
|
|
33
|
+
`))}return{...this.tokenizer(e,s),...n,...a}}},qi=class extends Ee{static image_processor_class=lt;static tokenizer_class=Te;static image_token="<|image_pad|>";async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let s,n;if(t&&(s=await this.image_processor(t),n=s.image_grid_thw),n){let o=this.image_processor.config.merge_size**2,i=0;const l=this.constructor.image_token,c=n.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),...s}}},BE=class extends qi{static image_token="<|image|>"},RE=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;static uses_processor_config=!0;_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:s}=this.feature_extractor.config,n=Math.floor(r/s),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*n}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const{input_features:a}=await this.feature_extractor(t);s.input_features=a;const o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);s.input_features_mask=new V("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}),...s}}};function GE(e,t){const s=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,s);const a=t.tolist();return n.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var $E=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;async _call(e,t,r={}){const s=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...s}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:n=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(n!==null&&n.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=>Ep(w))),_=[];for(let p=0;p<i;++p){const w=n!==null?n[p]:null;w!==null&&(h[p]=h[p].map(A=>A.map((E,C)=>E*w[(C+1)%2])));const v=d[p],M=[],y=[],k=[];for(let A=0;A<l;++A){const E=v[A];if(E<=r)continue;const C=h[p][A],L=c[p][A];M.push(E),k.push(C);const x=GE(L.gt(s),t[p]);y.push(x)}_.push({scores:M,boxes:k,labels:this.batch_decode(y)})}return _}};function VE(e,t,r,s,n,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(e);o+=`
|
|
34
|
+
`}return o+=`
|
|
35
|
+
${s}${a}`+n.repeat(e)+`${s}`,o}function UE(e,t,r,s){return`${t}${s}`+r.repeat(e)+`${t}`}function jE(e,t,r,s,n,a){return e===0&&t===0?UE(r,s,n,a):VE(r,e,t,s,n,a)}var yf=class extends Ee{static image_processor_class=lt;static tokenizer_class=Te;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,r={}){r.return_row_col_info??=!0;let s;t&&(s=await this.image_processor(t,r)),Array.isArray(e)||(e=[e]);const n=s.rows??[new Array(e.length).fill(0)],a=s.cols??[new Array(e.length).fill(0)],o=this.config.image_seq_len,i=[],l=[];for(let d=0;d<e.length;++d){const h=e[d],_=n[d],p=a[d];i.push(c0(h,this.image_token));const w=_.map((y,k)=>jE(y,p[k],o,this.fake_image_token,this.image_token,this.global_img_token)),v=h.split(this.image_token);if(v.length===0)throw new Error("The image token should be present in the text.");let M=v[0];for(let y=0;y<w.length;++y)M+=w[y]+v[y+1];l.push(M)}return{...this.tokenizer(l),...s}}},qE=class extends Ee{static image_processor_class=lt;static tokenizer_class=Te;static uses_processor_config=!0;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=>Ot.read(v)));const s=this.tokenizer,n=s.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>s.encode(v,{add_special_tokens:!1}),o=n.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]=s.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 M=new Array(this.num_image_tokens).fill(l),y=a(o[v]);h=Ht(h,[c],M,[d],y);const k=new Array(this.num_image_tokens).fill(!0);_=Ht(_,[!1],k,[!1],new Array(y.length).fill(!1))}const p=[1,h.length],w={input_ids:new V("int64",h,p),attention_mask:new V("int64",new Array(h.length).fill(1),p),images_seq_mask:new V("bool",_,p),images_emb_mask:new V("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}},WE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=e?this.tokenizer(e,r):{},n=t?await this.image_processor(t,r):{};return{...s,...n}}},HE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;async _call(e,t=null,r={}){const{image_rows:s,image_cols:n,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|>",M=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let y=0;t=t.map(k=>{const A=k.split(i);return A[0]+A.slice(1).map(E=>{const C=y++,[L,x]=a[C],G=s[C],B=n[C],j=_(L)*_(x);let X=w;if(G>1||B>1){const W=i.repeat(p);for(let N=0;N<G;++N)for(let O=0;O<B;++O)X+=`<|img_row_${N+1}_col_${O+1}|>`+W;h&&(X+=M+i.repeat(j))}else X+=i.repeat(j);return X+v+E}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},QE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;static uses_processor_config=!0;async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.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 n=t?this.tokenizer(t,r):{};return{...s,...n}}},bf={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},XE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;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(!bf.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,s]=bf[t],n=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 M=1;M<o;++M){const[y,k]=$e(rt(_[M]));if(w.push(y),k==s)break;p.push(k)}const v=w.length>0?w.reduce((M,y)=>M*y,1):0;l.push(p),i.push(v)}return[n(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[s,n]=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<s.length;++h){const[_,p]=$e([n[h],o[h],l[h]]);c.push([s[h],a[h],i[h]][p]),d.push(_)}return{generated_text:c,scores:d,char_preds:s,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"),s=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:s},t}async _call(e,t=null){const r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},YE=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e){return await this.feature_extractor(e)}},JE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt},Zr="<image>";function KE(e,t,r,s,n){return`${s.repeat(r*n)}${t}${e}
|
|
36
|
+
`}var ZE=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(ie.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 s=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(Zr))?a=t.map(l=>{const c=l.replaceAll(Zr,Zr.repeat(n)),d=c.lastIndexOf(Zr),h=d===-1?0:d+Zr.length;return c.slice(0,h)+s+c.slice(h)+`
|
|
37
|
+
`}):(ie.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=>KE(l,s,n,Zr,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},Mf="<|image|>",e2=/<\|image_\d+\|>/g,t2=class extends Ee{static image_processor_class=lt;static tokenizer_class=Te;async _call(e,t=null,{padding:r=!0,truncation:s=!0,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:n});const{num_img_tokens:i}=o,l=e.map((d,h)=>d.split(e2).join(Mf.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:s});const c=this.tokenizer._tokenizer.token_to_id(Mf);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},r2=class extends Ee{static tokenizer_class=Te;static image_processor_class=lt;static uses_processor_config=!0;async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.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 M=i.repeat(w),y=M+l,k=M+c,A=y.repeat(p-1)+k;t[v]=t[v].replace(i,A)}}const n=t?this.tokenizer(t,r):{};return{...s,...n}}},s2=class extends Ee{static feature_extractor_class=kp;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}},Wp=class extends qi{},n2=class extends Wp{},Hp=class extends Ee{static image_processor_class=lt;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)}},Qp=class extends Hp{},a2=class extends Qp{},o2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e){return await this.feature_extractor(e)}},i2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;static uses_processor_config=!0;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};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);s.audio_token_len=[l],s.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}),...s}}},Nn="[AUDIO]",l2="[BEGIN_AUDIO]",c2=375;function u2(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.subarray(s,Math.min(s+t,e.length)));return r}var d2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;static uses_processor_config=!1;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const s={};if(t){if(!e.includes(Nn))throw new Error(`The input text does not contain the audio token ${Nn}.`);Array.isArray(t)||(t=[t]);const a=e.split(Nn),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=>u2(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);s.audio_values=h.length>1?Ne(h,0):h[0];let _=a[0];for(let p=0;p<c.length;++p){_+=l2;for(let w=0;w<c[p];++w)_+=Nn.repeat(c2);_+=a[p+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},xf=32,Ro=6,Dn=8,h2=10,f2=32,_2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Ro+1)*Dn}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 Dn*e+t}get num_right_pad_tokens(){return Ro+1+h2}get audio_length_per_tok(){return Dn}get raw_audio_length_per_tok(){return Dn*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(st(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 s=xf*this.raw_audio_length_per_tok,n=new Float32Array(s+e.length);n.set(e,s);const a=await this.feature_extractor(n,{center:!0}),i=1+(xf+Ro),l=new BigInt64Array(i).fill(BigInt(f2));return l[0]=1n,{input_ids:new V("int64",l,[1,i]),...a}}else{const s=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+s);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},p2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e){return await this.feature_extractor(e)}},m2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e){return await this.feature_extractor(e)}},g2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Et;async _call(e){return await this.feature_extractor(e)}},w2=class{static async from_pretrained(e,t={}){const r=await Yt(e,Ks,!0,t),{image_processor_type:s,feature_extractor_type:n,processor_class:a}=r;if(a&&ei[a])return ei[a].from_pretrained(e,t);if(!s&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(s){const l=ta[s.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${s}'.`);o.image_processor=new l(r)}if(n){const l=ta[n];if(l)o.image_processor=new l(r);else{const c=Gi[n];if(!c)throw new Error(`Unknown feature_extractor_type: '${n}'.`);o.feature_extractor=new c(r)}}const i={};return new Ee(i,o,null)}};async function v2(e,t){return await Yt(e,"config.json",!0,t)}function ts(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=ts(e.text_config);break;case"moondream1":r=ts(e.phi_config);break;case"musicgen":r=ts(e.decoder);break;case"multi_modality":r=ts(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"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_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:n,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:n,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":const i=ts(e.decoder),l="num_decoder_layers"in i,c=Ke(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 s={...r,...Ke(e,["model_type","multi_query","is_encoder_decoder"])};for(const n in t)s[n]=e[t[n]];return s}function da(e,t){e instanceof ri||(e=new ri(e));const r=t?.prefix??"past_key_values",s=r==="present"?"present":"past",n=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")n.add(`${r}.${o}.key`),n.add(`${r}.${o}.value`);else if(a[o]==="conv")n.add(`${s}_conv.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}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?.length;for(let l=0;l<i;++l)(!o||o[l]==="mamba")&&(n.add(`${s}_conv.${l}`),n.add(`${s}_ssm.${l}`)),(!o||o[l]==="attention")&&(n.add(`${r}.${l}.key`),n.add(`${r}.${l}.value`));return n}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")n.add(`${r}.${o}.key`),n.add(`${r}.${o}.value`);else if(a[o]==="linear_attention")e.model_type==="olmo_hybrid"?(n.add(`${s}_conv.${o}.key`),n.add(`${s}_conv.${o}.value`),n.add(`${s}_conv.${o}.query`)):n.add(`${s}_conv.${o}`),n.add(`${s}_recurrent.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}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)n.add(`${r}.${c}.key`),n.add(`${r}.${c}.value`);return n}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let a;return e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder"?a=e.audio_config:a=e.text_config,da(a,t)}return y2(e,{prefix:r})}function y2(e,{prefix:t="past_key_values"}={}){const r=new Set,s=e.normalized_config;if(s.is_encoder_decoder&&"num_encoder_heads"in s&&"num_decoder_heads"in s)for(let n=0;n<s.num_decoder_layers;++n)r.add(`${t}.${n}.encoder.key`),r.add(`${t}.${n}.encoder.value`),r.add(`${t}.${n}.decoder.key`),r.add(`${t}.${n}.decoder.value`);else if(s.multi_query)for(let n=0;n<s.num_layers;++n)r.add(`${t}.${n}.key_value`);else for(let n=0;n<s.num_layers;++n)r.add(`${t}.${n}.key`),r.add(`${t}.${n}.value`);return r}var ri=class si{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=ts(this)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){s&&!(s instanceof si)&&(s=new si(s));const i=s??await v2(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(i)}},Zs=class{static async from_pretrained(...e){return ri.from_pretrained(...e)}};function Xp(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function Yp(e,t){const r=[];for(let s=0;s<t;++s)r.push(`${e}_data${s===0?"":"_"+s}`);return r}async function b2(e,t,r,s){const n=`${t}${s}.onnx`,a=`${r.subfolder??""}/${n}`;return await ea(e,a,!0,r,de.IS_NODE_ENV)}async function M2(e,t,r,s,n,a={}){const o=`${t}${r}.onnx`,i=de.IS_NODE_ENV;let l=[];const c=Xp(n,o,t);if(c>0){if(c>ef)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${ef}).`);const d=Yp(o,c);for(const h of d){const _=`${s.subfolder??""}/${h}`;l.push(new Promise(async(p,w)=>{const v=await ea(e,_,!0,s,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 ea(e,d.data,!0,s);return{...d,data:h}}return d}));return Promise.all(l)}async function x2(e,t,r,s=!1,n=void 0){let a=r.config?.["transformers.js_config"]??{};const o=rp(r.device??a.device,t,{warn:k=>ie.info(k)}),i=H1(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const c=sp(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:k=>ie.info(k)});if(Ko.hasOwnProperty(c)){if(o==="webgpu"&&!de.IS_NODE_ENV&&c===Ve.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(Ve).join(", ")}`);const d=Ko[c],h={...r.session_options};h.executionProviders??=i;const _=a.free_dimension_overrides;_?h.freeDimensionOverrides??=_:o.startsWith("webnn")&&!h.freeDimensionOverrides&&ie.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=b2(e,t,r,d),w=r.use_external_data_format??a.use_external_data_format,v=await M2(e,t,d,r,w,h);if(v.length>0&&(!de.IS_NODE_ENV||v.some(k=>typeof k!="string"))&&(h.externalData=v),s&&o==="webgpu"){const k=da(r.config,{prefix:"present",session_name:n});if(k.size>0&&!Oi()){const A={};for(const E of k)A[E]="gpu-buffer";h.preferredOutputLocation=A}}return{buffer_or_path:await p,session_options:h,session_config:{dtype:c,device:o}}}async function k2(e,t,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const a=s?.[n]??!1,{buffer_or_path:o,session_options:i,session_config:l}=await x2(e,t[n],r,a,n),c=await Z_(o,i,l);return[n,c]})))}function Jp(e){for(let t in e)tp(e[t])?e[t]=new V(e[t]):typeof e[t]=="object"&&Jp(e[t]);return e}async function ye(e,t){const r=T2(e,t);try{const s=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return de.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),n=await ep(e,s);return Jp(n)}catch(s){const n=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 ie.error(`An error occurred during model execution: "${s}".`),ie.error("Inputs given to model:",n),s}}function T2(e,t){const r=Object.create(null),s=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof V)){s.push(o);continue}r[o]=Oi()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);const n=Object.keys(t).length,a=e.inputNames.length;if(n>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ie.warn(`WARNING: Too many inputs were provided (${n} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var We=class{},se=class extends We{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},Ue=class extends We{constructor({logits:e}){super(),this.logits=e}},He=class extends We{constructor({logits:e}){super(),this.logits=e}},ct=class extends We{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Gr=class extends We{constructor({logits:e}){super(),this.logits=e}},E2=class extends We{constructor({alphas:e}){super(),this.alphas=e}},Bt=class extends _t{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},A2=class extends _t{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},ni=class extends _t{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},C2=class extends Bt{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 s=t[r].data;s.fill(-1/0),s[this.bos_token_id]=0}return t}},S2=class extends Bt{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 s=t[r].data;s.fill(-1/0);for(const n of this.eos_token_id)s[n]=0}return t}},P2=class extends Bt{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of this.suppress_tokens)s[n]=-1/0}return t}},Kp=class extends Bt{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 s=t[r].data;for(const n of this.begin_suppress_tokens)s[n]=-1/0}return t}},F2=class extends Bt{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 s=t[r].data;if(s[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){s.subarray(0,this.timestamp_begin).fill(-1/0);continue}const n=e[r].slice(this.begin_index),a=n.length>=1&&n[n.length-1]>=this.timestamp_begin,o=n.length<2||n[n.length-2]>=this.timestamp_begin;if(a&&(o?s.subarray(this.timestamp_begin).fill(-1/0):s.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;s.subarray(d+1).fill(-1/0)}const i=O1(s),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=$e(i.subarray(0,this.timestamp_begin))[0];l>c&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},L2=class extends Bt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[n+o]);r.push(a.map(Number))}const s=new Map;for(const n of r){const a=n.slice(0,n.length-1),o=JSON.stringify(a),i=s.get(o)??[];i.push(n[n.length-1]),s.set(o,i)}return s}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 s=t[r].data,n=this.calcBannedNgramTokens(e[r]);for(const a of n)s[a]=-1/0}return t}},I2=class extends Bt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of new Set(e[r])){const a=Number(n);s[a]<0?s[a]*=this.penalty:s[a]/=this.penalty}}return t}},O2=class extends Bt{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 s=t[r].data;for(const n of this.eos_token_id)s[n]=-1/0}return t}},N2=class extends Bt{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 n=t[r].data;for(const a of this.eos_token_id)n[a]=-1/0}return t}},D2=class extends Bt{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 s=t[r].data,n=e[r];for(const a of this.bad_words_ids){if(n.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=n.at(-i)){o=!1;break}o&&(s[a.at(-1)]=-1/0)}}return t}},z2=class extends Bt{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,s=t.slice([0,r],null),n=t.slice([r,t.dims[0]],null);for(let a=0;a<n.data.length;++a)n.data[a]+=(s.data[a]-n.data[a])*this.guidance_scale;return n}},B2=class extends A2{constructor(e){super(),this.temperature=e}_call(e,t){const r=t.data;for(let s=0;s<r.length;++s)r[s]/=this.temperature;return t}},Zp=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Ke(e,Object.getOwnPropertyNames(this)))}},ha=class extends _t{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},em=class tm extends _t{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof tm?t=t.criteria:t instanceof ha&&(t=[t]),this.criteria.push(...t)}_call(t,r){const s=new Array(t.length).fill(!1);for(const n of this.criteria){const a=n(t,r);for(let o=0;o<s.length;++o)s[o]||=a[o]}return s}[Symbol.iterator](){return this.criteria.values()}},R2=class extends ha{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)}},G2=class extends ha{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(n=>s==n)})}},fa=class extends _t{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),s=e.data;if(t===-1)s=s.slice(-r);else{let n=t*r;s=s.slice(n,n+r)}return s}randomSelect(e){return g1(e)}static getSampler(e){if(e.do_sample)return new V2(e);if(e.num_beams>1)return new U2(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 $2(e)}},$2=class extends fa{async sample(e){const t=$e(e.data)[1];return[[BigInt(t),0]]}},V2=class extends fa{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,s]=await _s(e,t),n=rt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(n);return[s.data[a],Math.log(n[a])]})}},U2=class extends fa{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,s]=await _s(e,t),n=rt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[s.data[o],Math.log(n[o])])}},j2=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 V))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],s=e[t];r&&r!==s&&r.location==="gpu-buffer"&&r.dispose(),this[t]=s}}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},Wi=j2,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},nr={[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 s={...nr[q.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(s.model="encoder_model"),s},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 s={...nr[q.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},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 s={...nr[q.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},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 s={...nr[q.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};function q2(e){return nr[e]?.text_only_sessions??null}function W2(e,t,r={}){const s=nr[e]??nr.default;return{sessions:s.sessions(t,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function rm(e,{warn:t=!0}={}){const r=e.architectures||[];for(const s of r){const n=ar.get(s);if(n!==void 0)return n}if(e.model_type){const s=ar.get(e.model_type);if(s!==void 0)return s;for(const n of Object.values(ss))if(n.has(e.model_type)){const a=ar.get(n.get(e.model_type));if(a!==void 0)return a}}if(t){const s=r.length>0?r.join(", "):"(none)";ie.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${ca}`)}return q.EncoderOnly}function sm(e,{config:t=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(t!==null)return Zs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n});const a=JSON.stringify([e,r,s,n]);return j_(a,()=>Zs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n}))}async function nm(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){t=await sm(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=s??o.device;let d=r??o.dtype;const h=rm(t),_=(v,M=null)=>{M=M??v;const y=rp(c,v),k=sp(d,v,y),A=Ko[k]??"",E=`${M}${A}.onnx`,C=`${l}/${E}`;a.push(C);const L=Xp(i,E,v);for(const x of Yp(E,L)){const G=`${l}/${x}`;a.push(G)}},{sessions:p,optional_configs:w}=W2(h,t,{model_file_name:n});for(const[v,M]of Object.entries(p))_(v,M);if(w)for(const v of Object.values(w))a.push(v);return a}var ss=null;function H2(e){ss=e}function ai(e){if(e instanceof V)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 V("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new V("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function am(e){return new V("bool",[e],[1])}var kf={[q.DecoderOnly]:{can_generate:!0,forward:ir,prepare_inputs:Qs},[q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:ir,prepare_inputs:Qs},[q.Seq2Seq]:{can_generate:!0,forward:zn,prepare_inputs:ra},[q.Vision2Seq]:{can_generate:!0,forward:zn,prepare_inputs:ra},[q.Musicgen]:{can_generate:!0,forward:zn},[q.EncoderDecoder]:{can_generate:!1,forward:zn},[q.ImageTextToText]:{can_generate:!0,forward:J2,prepare_inputs:Bn},[q.AudioTextToText]:{can_generate:!0,forward:Y2,prepare_inputs:Bn},[q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Bn},[q.Phi3V]:{can_generate:!0,prepare_inputs:Bn},[q.MultiModality]:{can_generate:!0},[q.AutoEncoder]:{can_generate:!1,forward:Q2},[q.Chatterbox]:{can_generate:!0,forward:xr},[q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Qs},default:{can_generate:!1,forward:xr}};function Tf(e,t){let r=ar.get(e),s=!1;const n=t?.architectures?.[0];if(n&&n!==e&&e?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){const i=ar.get(n);i!==void 0&&(r=i,s=!0)}const a=kf[r]??kf.default,o=nr[r]??nr.default;return{typeConfig:{...a,...o},textOnly:s,modelType:r}}var ar=new Map,Hi=new Map,cs=new Map,S=class extends _t{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,r){super(),this.config=e,this.sessions=t,this.configs=r;const s=cs.get(this.constructor),{typeConfig:n}=Tf(s,e);this.can_generate=n.can_generate,this._forward=n.forward,this._prepare_inputs_for_generation=n.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!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:s,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h},p=cs.get(this);r=_.config=await Zs.from_pretrained(e,_);const{typeConfig:w,textOnly:v,modelType:M}=Tf(p,r);if(M===void 0){const E=p??r?.model_type;E!=="custom"&&ie.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${ca}.`)}if(t&&!(t instanceof Qo)){const E={};try{const C=await nm(e,{config:r,dtype:c,device:l,model_file_name:o});(await Promise.all(C.map(x=>sn(e,x,_)))).forEach((x,G)=>{if(x.exists){const B=C[G]==="config.json";E[C[G]]={loaded:B?x.size??0:0,total:x.size??0}}})}catch(C){ie.warn(`Unable to fetch model file metadata for total progress tracking: ${C}`)}Object.keys(E).length>0&&(_.progress_callback=new Qo(t,E))}const y=w.sessions(r,_,v),k=[k2(e,y,_,w.cache_sessions)];w.optional_configs&&k.push(Z2(e,w.optional_configs,_));const A=await Promise.all(k);return new this(r,...A)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,r=null){const s=new ni;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&s.push(new I2(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&s.push(new L2(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&s.push(new D2(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&s.push(new O2(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&s.push(new N2(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&s.push(new C2(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&s.push(new S2(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&s.push(new P2(e.suppress_tokens)),e.begin_suppress_tokens!==null){const n=t>1||e.forced_bos_token_id===null?t:t+1;s.push(new Kp(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&s.push(new z2(e.guidance_scale)),e.temperature===0&&e.do_sample&&(ie.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&s.push(new B2(e.temperature)),r!==null&&s.extend(r),s}_prepare_generation_config(e,t,r=Zp){const s={...this.config};for(const a of["decoder","generator","text_config"])a in s&&Object.assign(s,s[a]);const n=new r(s);return Object.assign(n,this.generation_config??{}),e&&Object.assign(n,e),t&&Object.assign(n,Ke(t,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,t=null){const r=new em;return e.max_length!==null&&r.push(new R2(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new G2(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[ss.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,ss.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,ss.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,ss.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=cs.get(this.constructor),r=new Set,s=this.config.model_type;for(const a of e){const o=a?.get(s);o&&r.add(o)}let n=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(n+=` Please use the following class instead: ${[...r].join(", ")}`),Error(n)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:s}){return r.past_key_values=oi(t,r.past_key_values),r.input_ids=new V("int64",e.flat(),[e.length,1]),s?"decoder_attention_mask"in r&&(r.decoder_attention_mask=Ne([r.decoder_attention_mask,ft([r.decoder_attention_mask.dims[0],1])],1)):r.attention_mask=Ne([r.attention_mask,ft([r.attention_mask.dims[0],1])],1),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){const s=Ke(r,this.forward_params),n=this.main_input_name;if(n in s){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[n]=e;return{inputs_tensor:s[n],model_inputs:s,model_input_name:n}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:a,pixel_values:o,attention_mask:i,...l}=t,c=await this._prepare_inputs_embeds(t);t={...l,...Ke(c,["inputs_embeds","attention_mask"])}}let{last_hidden_state:n}=await xr(this,t);if(s.guidance_scale!==null&&s.guidance_scale>1)n=Ne([n,Zo(n,0)],0),"attention_mask"in t&&(t.attention_mask=Ne([t.attention_mask,lp(t.attention_mask)],0));else if(t.decoder_input_ids){const a=ai(t.decoder_input_ids).dims[0];if(a!==n.dims[0]){if(n.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${n.dims[0]}) than the decoder inputs (${a}).`);n=Ne(Array.from({length:a},()=>n),0)}}return t.encoder_outputs=n,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:s,bos_token_id:n,generation_config:a}){let{decoder_input_ids:o,...i}=r;if(!(o instanceof V)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(s??=n,this.config.model_type==="musicgen")o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${s.length}`);o=s}else o=Array.from({length:e},()=>[s]);o=ai(o)}return i.decoder_attention_mask=op(o),{input_ids:o,model_inputs:i}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,streamer:n=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const c=this.config.is_encoder_decoder;c&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:i,model_input_name:l,generation_config:t})));let d;c?{input_ids:d,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[l].dims.at(0),model_input_name:l,model_kwargs:i,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):d=i[l];let h=d.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=h+t.max_new_tokens);const _=this._get_logits_processor(t,h,r),p=this._get_stopping_criteria(t,s),w=i[l].dims.at(0),v=fa.getSampler(t),M=new Array(w).fill(0),y=d.tolist();n&&n.put(y);let k,A={},E={};for(;;){if(i=this.prepare_inputs_for_generation(y,i,t),k=await this.forward(i),t.return_dict_in_generate)if(t.output_attentions){const N=X2(k);for(const O in N)O in A||(A[O]=[]),A[O].push(N[O])}else this._return_dict_in_generate_keys&&Object.assign(E,Ke(k,this._return_dict_in_generate_keys));const B=k.logits.slice(null,-1,null).to("float32"),j=_(y,B),X=[];for(let N=0;N<j.dims.at(0);++N){const O=j[N],U=await v(O);for(const[Q,ee]of U){const I=BigInt(Q);M[N]+=ee,y[N].push(I),X.push([I]);break}}if(n&&n.put(X),p(y).every(N=>N))break;i=this._update_model_kwargs_for_generation({generated_input_ids:X,outputs:k,model_inputs:i,is_encoder_decoder:c})}n&&n.end();const C=new V("int64",y.flat(),[y.length,y[0].length]),L=oi(k,i.past_key_values),x=new Set(Object.values(L));for(const B of Object.values(k))B.location==="gpu-buffer"&&!x.has(B)&&B.dispose();return"past_key_values"in a||t.return_dict_in_generate||await L.dispose(),t.return_dict_in_generate?{sequences:C,past_key_values:L,...A,...E}:C}async _encode_input(e,t,r){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);const s=this.sessions[e];return(await ye(s,Ke(t,s.inputNames)))[r]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function zn(e,t){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:a,...o}=t;if(!r){const i=Ke(t,e.sessions.model.inputNames);r=(await xr(e,i)).last_hidden_state}return o.input_ids=n,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 ir(e,o,!0)}async function xr(e,t){const r=e.sessions.model,s=Ke(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=lp(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const n=s.pixel_values.dims;s.pixel_mask=ft([n[0],n[2],n[3]])}return await ye(r,s)}async function Q2(e,t){const r=await e.encode(t);return await e.decode(r)}function oi(e,t){const r=Object.create(null);for(const s in e)if(s.startsWith("present")){const n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");s.includes("encoder")&&t?r[n]=t[n]:r[n]=e[s]}return t?(t.update(r),t):new Wi(r)}function X2(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in e)s.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[s]));return t}function om(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function Qi(e,t,r){if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;const s=e.sessions.decoder_model_merged??e.sessions.model,n=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=da(e.config),o=e.config?.normalized_config?.num_heads,i={batch_size:n};typeof o=="number"&&(i["batch_size x num_heads"]=n*o);const l=Object.create(null);for(const c of s.inputMetadata){if(!a.has(c.name))continue;const d=om(c.shape,i),h=d.reduce((w,v)=>w*v,1),_=Js[c.type],p=new V(c.type,new _(h),d);t[c.name]=p,l[c.name]=p}return r?(r.update(l),r):new Wi(l)}async function ir(e,t,r=!1){const s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...a}=t;if(s.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=am(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=K2(a,n,i)}s.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new V("int64",[0n],[])),Qi(e,a,n);const o=Ke(a,s.inputNames);return await ye(s,o)}async function im(e,{encode_function:t,merge_function:r,modality_input_names:s,modality_output_name:n,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,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});const w=Ke(_,s);if(Object.keys(w).length>0){if(a.dims[1]!==1){const v=await t({...w,..._});({inputs_embeds:l,attention_mask:o}=r({[n]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){const v=a.dims[1],M=c.get_seq_length();o=Ne([ft([a.dims[0],M]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){const{image_grid_thw:w,video_grid_thw:v}=_;[i]=e.get_rope_index(a,w,v,o)}return await ir(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},!0)}async function Y2(e,t){return await im(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 J2(e,t){return await im(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 lm(e,t=0){const[r,s]=e.dims,n=e.data,a=new BigInt64Array(n.length);for(let o=0;o<r;++o){const i=o*s;let l=BigInt(t);for(let c=0;c<s;++c){const d=i+c;n[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=n[d])}}return{data:a,dims:e.dims}}function K2(e,t=null,r=0){const{input_ids:s,inputs_embeds:n,attention_mask:a}=e,{data:o,dims:i}=lm(a,r);let l=new V("int64",o,i);if(t){const c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Qs(e,t,r,s){const n=r.past_key_values?r.past_key_values.get_seq_length():0;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new V("int64",[1n],[])),!r.attention_mask){let o;for(const i of["input_ids","inputs_embeds","position_ids"])if(r[i]){o=r[i].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=ft([o[0],n+o[1]])}if(r.past_key_values){const{input_ids:o,attention_mask:i}=r;i&&i.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]))}return r}function ra(e,t,r,s){return r.past_key_values&&(t=t.map(n=>[n.at(-1)])),{...r,decoder_input_ids:ai(t)}}function Bn(e,...t){return e.config.is_encoder_decoder?ra(e,...t):Qs(e,...t)}function cm({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n}){const a=s.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:n}}function Xi({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:s,attention_mask:n}){return cm({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}function um({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:s,attention_mask:n}){return cm({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}async function Z2(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const n=await Yt(e,t[s],!1,r);return[s,n]})))}var Yi={};ds(Yi,{ASTForAudioClassification:()=>dA,ASTModel:()=>uA,ASTPreTrainedModel:()=>el,AfmoeForCausalLM:()=>iA,AfmoeModel:()=>oA,AfmoePreTrainedModel:()=>Ki,AlbertForMaskedLM:()=>sA,AlbertForQuestionAnswering:()=>rA,AlbertForSequenceClassification:()=>tA,AlbertModel:()=>eA,AlbertPreTrainedModel:()=>nn,ApertusForCausalLM:()=>aA,ApertusModel:()=>nA,ApertusPreTrainedModel:()=>Ji,ArceeForCausalLM:()=>cA,ArceeModel:()=>lA,ArceePreTrainedModel:()=>Zi,BartForConditionalGeneration:()=>fA,BartForSequenceClassification:()=>_A,BartModel:()=>hA,BartPretrainedModel:()=>_a,BeitForImageClassification:()=>mA,BeitModel:()=>pA,BeitPreTrainedModel:()=>tl,BertForMaskedLM:()=>wA,BertForQuestionAnswering:()=>bA,BertForSequenceClassification:()=>vA,BertForTokenClassification:()=>yA,BertModel:()=>gA,BertPreTrainedModel:()=>ps,BlenderbotForConditionalGeneration:()=>xA,BlenderbotModel:()=>MA,BlenderbotPreTrainedModel:()=>rl,BlenderbotSmallForConditionalGeneration:()=>TA,BlenderbotSmallModel:()=>kA,BlenderbotSmallPreTrainedModel:()=>sl,BloomForCausalLM:()=>AA,BloomModel:()=>EA,BloomPreTrainedModel:()=>nl,CHMv2ForDepthEstimation:()=>NA,CHMv2PreTrainedModel:()=>_m,CLIPModel:()=>zA,CLIPPreTrainedModel:()=>$r,CLIPSegForImageSegmentation:()=>VA,CLIPSegModel:()=>$A,CLIPSegPreTrainedModel:()=>al,CLIPTextModel:()=>BA,CLIPTextModelWithProjection:()=>gm,CLIPVisionModel:()=>RA,CLIPVisionModelWithProjection:()=>GA,CamembertForMaskedLM:()=>SA,CamembertForQuestionAnswering:()=>LA,CamembertForSequenceClassification:()=>PA,CamembertForTokenClassification:()=>FA,CamembertModel:()=>CA,CamembertPreTrainedModel:()=>ms,ChatterboxModel:()=>hm,ChatterboxPreTrainedModel:()=>dm,ChineseCLIPModel:()=>OA,ChineseCLIPPreTrainedModel:()=>fm,ClapAudioModelWithProjection:()=>mm,ClapModel:()=>DA,ClapPreTrainedModel:()=>pa,ClapTextModelWithProjection:()=>pm,CodeGenForCausalLM:()=>jA,CodeGenModel:()=>UA,CodeGenPreTrainedModel:()=>ol,Cohere2ForCausalLM:()=>QA,Cohere2Model:()=>HA,Cohere2PreTrainedModel:()=>ll,CohereAsrForConditionalGeneration:()=>YA,CohereAsrModel:()=>XA,CohereAsrPreTrainedModel:()=>cl,CohereForCausalLM:()=>WA,CohereModel:()=>qA,CoherePreTrainedModel:()=>il,ConvBertForMaskedLM:()=>KA,ConvBertForQuestionAnswering:()=>tC,ConvBertForSequenceClassification:()=>ZA,ConvBertForTokenClassification:()=>eC,ConvBertModel:()=>JA,ConvBertPreTrainedModel:()=>gs,ConvNextForImageClassification:()=>sC,ConvNextModel:()=>rC,ConvNextPreTrainedModel:()=>ul,ConvNextV2ForImageClassification:()=>aC,ConvNextV2Model:()=>nC,ConvNextV2PreTrainedModel:()=>dl,DFineForObjectDetection:()=>cC,DFineModel:()=>lC,DFinePreTrainedModel:()=>fl,DINOv3ConvNextModel:()=>NC,DINOv3ConvNextPreTrainedModel:()=>Em,DINOv3ViTModel:()=>DC,DINOv3ViTPreTrainedModel:()=>Am,DPTForDepthEstimation:()=>jC,DPTModel:()=>UC,DPTPreTrainedModel:()=>vl,DacDecoderModel:()=>bm,DacDecoderOutput:()=>vm,DacEncoderModel:()=>ym,DacEncoderOutput:()=>wm,DacModel:()=>uC,DacPreTrainedModel:()=>ma,DebertaForMaskedLM:()=>hC,DebertaForQuestionAnswering:()=>pC,DebertaForSequenceClassification:()=>fC,DebertaForTokenClassification:()=>_C,DebertaModel:()=>dC,DebertaPreTrainedModel:()=>ws,DebertaV2ForMaskedLM:()=>vC,DebertaV2ForQuestionAnswering:()=>MC,DebertaV2ForSequenceClassification:()=>yC,DebertaV2ForTokenClassification:()=>bC,DebertaV2Model:()=>wC,DebertaV2PreTrainedModel:()=>vs,DecisionTransformerModel:()=>xC,DecisionTransformerPreTrainedModel:()=>Mm,DeepseekV3ForCausalLM:()=>gC,DeepseekV3Model:()=>mC,DeepseekV3PreTrainedModel:()=>_l,DeiTForImageClassification:()=>TC,DeiTModel:()=>kC,DeiTPreTrainedModel:()=>pl,DepthAnythingForDepthEstimation:()=>EC,DepthAnythingPreTrainedModel:()=>xm,DepthProForDepthEstimation:()=>AC,DepthProPreTrainedModel:()=>km,DetrForObjectDetection:()=>SC,DetrForSegmentation:()=>PC,DetrModel:()=>CC,DetrObjectDetectionOutput:()=>ml,DetrPreTrainedModel:()=>ga,DetrSegmentationOutput:()=>Tm,Dinov2ForImageClassification:()=>LC,Dinov2Model:()=>FC,Dinov2PreTrainedModel:()=>gl,Dinov2WithRegistersForImageClassification:()=>OC,Dinov2WithRegistersModel:()=>IC,Dinov2WithRegistersPreTrainedModel:()=>wl,DistilBertForMaskedLM:()=>$C,DistilBertForQuestionAnswering:()=>GC,DistilBertForSequenceClassification:()=>BC,DistilBertForTokenClassification:()=>RC,DistilBertModel:()=>zC,DistilBertPreTrainedModel:()=>ys,DonutSwinModel:()=>VC,DonutSwinPreTrainedModel:()=>Cm,EdgeTamModel:()=>tI,EfficientNetForImageClassification:()=>WC,EfficientNetModel:()=>qC,EfficientNetPreTrainedModel:()=>yl,ElectraForMaskedLM:()=>QC,ElectraForQuestionAnswering:()=>JC,ElectraForSequenceClassification:()=>XC,ElectraForTokenClassification:()=>YC,ElectraModel:()=>HC,ElectraPreTrainedModel:()=>bs,Ernie4_5ForCausalLM:()=>ZC,Ernie4_5Model:()=>KC,Ernie4_5PretrainedModel:()=>bl,EsmForMaskedLM:()=>tS,EsmForSequenceClassification:()=>rS,EsmForTokenClassification:()=>sS,EsmModel:()=>eS,EsmPreTrainedModel:()=>on,EuroBertForMaskedLM:()=>aS,EuroBertForSequenceClassification:()=>oS,EuroBertForTokenClassification:()=>iS,EuroBertModel:()=>nS,EuroBertPreTrainedModel:()=>ln,ExaoneForCausalLM:()=>cS,ExaoneModel:()=>lS,ExaonePreTrainedModel:()=>Ml,FalconForCausalLM:()=>dS,FalconH1ForCausalLM:()=>fS,FalconH1Model:()=>hS,FalconH1PreTrainedModel:()=>kl,FalconModel:()=>uS,FalconPreTrainedModel:()=>xl,FastViTForImageClassification:()=>pS,FastViTModel:()=>_S,FastViTPreTrainedModel:()=>Tl,Florence2ForConditionalGeneration:()=>mS,Florence2PreTrainedModel:()=>Sm,GLPNForDepthEstimation:()=>IS,GLPNModel:()=>LS,GLPNPreTrainedModel:()=>Il,GPT2LMHeadModel:()=>US,GPT2Model:()=>VS,GPT2PreTrainedModel:()=>Bl,GPTBigCodeForCausalLM:()=>NS,GPTBigCodeModel:()=>OS,GPTBigCodePreTrainedModel:()=>Ol,GPTJForCausalLM:()=>qS,GPTJModel:()=>jS,GPTJPreTrainedModel:()=>Rl,GPTNeoForCausalLM:()=>zS,GPTNeoModel:()=>DS,GPTNeoPreTrainedModel:()=>Nl,GPTNeoXForCausalLM:()=>RS,GPTNeoXModel:()=>BS,GPTNeoXPreTrainedModel:()=>Dl,Gemma2ForCausalLM:()=>yS,Gemma2Model:()=>vS,Gemma2PreTrainedModel:()=>Al,Gemma3ForCausalLM:()=>kS,Gemma3ForConditionalGeneration:()=>Lm,Gemma3Model:()=>xS,Gemma3PreTrainedModel:()=>Fm,Gemma3nForCausalLM:()=>TS,Gemma3nForConditionalGeneration:()=>wa,Gemma3nPreTrainedModel:()=>Im,Gemma4ForCausalLM:()=>ES,Gemma4ForConditionalGeneration:()=>Cl,GemmaForCausalLM:()=>wS,GemmaModel:()=>gS,GemmaPreTrainedModel:()=>El,GlmForCausalLM:()=>CS,GlmModel:()=>AS,GlmMoeDsaForCausalLM:()=>PS,GlmMoeDsaModel:()=>SS,GlmMoeDsaPreTrainedModel:()=>Pl,GlmOcrForConditionalGeneration:()=>FS,GlmPreTrainedModel:()=>Sl,GptOssForCausalLM:()=>$S,GptOssModel:()=>GS,GptOssPreTrainedModel:()=>zl,GraniteForCausalLM:()=>HS,GraniteModel:()=>WS,GraniteMoeHybridForCausalLM:()=>XS,GraniteMoeHybridModel:()=>QS,GraniteMoeHybridPreTrainedModel:()=>$l,GranitePreTrainedModel:()=>Gl,GraniteSpeechForConditionalGeneration:()=>YS,GroundingDinoForObjectDetection:()=>JS,GroundingDinoPreTrainedModel:()=>Bm,GroupViTModel:()=>KS,GroupViTPreTrainedModel:()=>Rm,HeliumForCausalLM:()=>eP,HeliumModel:()=>ZS,HeliumPreTrainedModel:()=>Ul,HieraForImageClassification:()=>rP,HieraModel:()=>tP,HieraPreTrainedModel:()=>jl,HubertForCTC:()=>cP,HubertForSequenceClassification:()=>uP,HubertModel:()=>lP,HubertPreTrainedModel:()=>iP,HunYuanDenseV1ForCausalLM:()=>hP,HunYuanDenseV1Model:()=>dP,HunYuanDenseV1PreTrainedModel:()=>ql,IJepaForImageClassification:()=>_P,IJepaModel:()=>fP,IJepaPreTrainedModel:()=>Wl,Idefics3ForConditionalGeneration:()=>Gm,JAISLMHeadModel:()=>mP,JAISModel:()=>pP,JAISPreTrainedModel:()=>Hl,JinaCLIPModel:()=>gP,JinaCLIPPreTrainedModel:()=>va,JinaCLIPTextModel:()=>$m,JinaCLIPVisionModel:()=>wP,Lfm2ForCausalLM:()=>yP,Lfm2Model:()=>vP,Lfm2MoeForCausalLM:()=>xP,Lfm2MoeModel:()=>MP,Lfm2MoePreTrainedModel:()=>Xl,Lfm2PreTrainedModel:()=>Ql,Lfm2VlForConditionalGeneration:()=>kP,LightOnOcrForConditionalGeneration:()=>bP,LiteWhisperForConditionalGeneration:()=>MO,Llama4ForCausalLM:()=>AP,Llama4PreTrainedModel:()=>Vm,LlamaForCausalLM:()=>EP,LlamaModel:()=>TP,LlamaPreTrainedModel:()=>Yl,LlavaForConditionalGeneration:()=>lr,LlavaOnevisionForConditionalGeneration:()=>lr,LlavaPreTrainedModel:()=>Pm,LlavaQwen2ForCausalLM:()=>MS,LongT5ForConditionalGeneration:()=>SP,LongT5Model:()=>CP,LongT5PreTrainedModel:()=>Jl,M2M100ForConditionalGeneration:()=>FP,M2M100Model:()=>PP,M2M100PreTrainedModel:()=>Kl,MBartForCausalLM:()=>RP,MBartForConditionalGeneration:()=>zP,MBartForSequenceClassification:()=>BP,MBartModel:()=>DP,MBartPreTrainedModel:()=>cn,MPNetForMaskedLM:()=>TF,MPNetForQuestionAnswering:()=>CF,MPNetForSequenceClassification:()=>EF,MPNetForTokenClassification:()=>AF,MPNetModel:()=>kF,MPNetPreTrainedModel:()=>Ms,MT5ForConditionalGeneration:()=>LF,MT5Model:()=>FF,MT5PreTrainedModel:()=>cc,MarianMTModel:()=>IP,MarianModel:()=>LP,MarianPreTrainedModel:()=>Zl,MaskFormerForInstanceSegmentation:()=>NP,MaskFormerModel:()=>OP,MaskFormerPreTrainedModel:()=>ec,Metric3DForDepthEstimation:()=>GP,Metric3DPreTrainedModel:()=>Um,Metric3Dv2ForDepthEstimation:()=>$P,Metric3Dv2PreTrainedModel:()=>jm,MgpstrForSceneTextRecognition:()=>VP,MgpstrModelOutput:()=>qm,MgpstrPreTrainedModel:()=>Wm,MimiDecoderModel:()=>Ym,MimiDecoderOutput:()=>Qm,MimiEncoderModel:()=>Xm,MimiEncoderOutput:()=>Hm,MimiModel:()=>UP,MimiPreTrainedModel:()=>ya,Mistral4ForCausalLM:()=>HP,Mistral4Model:()=>WP,Mistral4PreTrainedModel:()=>rc,MistralForCausalLM:()=>qP,MistralModel:()=>jP,MistralPreTrainedModel:()=>tc,MobileBertForMaskedLM:()=>XP,MobileBertForQuestionAnswering:()=>JP,MobileBertForSequenceClassification:()=>YP,MobileBertModel:()=>QP,MobileBertPreTrainedModel:()=>un,MobileLLMForCausalLM:()=>ZP,MobileLLMModel:()=>KP,MobileLLMPreTrainedModel:()=>sc,MobileNetV1ForImageClassification:()=>tF,MobileNetV1ForSemanticSegmentation:()=>rF,MobileNetV1Model:()=>eF,MobileNetV1PreTrainedModel:()=>ba,MobileNetV2ForImageClassification:()=>nF,MobileNetV2ForSemanticSegmentation:()=>aF,MobileNetV2Model:()=>sF,MobileNetV2PreTrainedModel:()=>Ma,MobileNetV3ForImageClassification:()=>iF,MobileNetV3ForSemanticSegmentation:()=>lF,MobileNetV3Model:()=>oF,MobileNetV3PreTrainedModel:()=>xa,MobileNetV4ForImageClassification:()=>uF,MobileNetV4ForSemanticSegmentation:()=>dF,MobileNetV4Model:()=>cF,MobileNetV4PreTrainedModel:()=>ka,MobileViTForImageClassification:()=>fF,MobileViTModel:()=>hF,MobileViTPreTrainedModel:()=>nc,MobileViTV2ForImageClassification:()=>pF,MobileViTV2Model:()=>_F,MobileViTV2PreTrainedModel:()=>ac,ModernBertDecoderForCausalLM:()=>bF,ModernBertDecoderModel:()=>yF,ModernBertDecoderPreTrainedModel:()=>oc,ModernBertForMaskedLM:()=>gF,ModernBertForSequenceClassification:()=>wF,ModernBertForTokenClassification:()=>vF,ModernBertModel:()=>mF,ModernBertPreTrainedModel:()=>dn,Moondream1ForConditionalGeneration:()=>bS,MoonshineForConditionalGeneration:()=>xF,MoonshineModel:()=>MF,MoonshinePreTrainedModel:()=>ic,MptForCausalLM:()=>PF,MptModel:()=>SF,MptPreTrainedModel:()=>lc,MultiModalityCausalLM:()=>IF,MultiModalityPreTrainedModel:()=>Jm,MusicgenForCausalLM:()=>NF,MusicgenForConditionalGeneration:()=>Km,MusicgenModel:()=>OF,MusicgenPreTrainedModel:()=>uc,NanoChatForCausalLM:()=>zF,NanoChatModel:()=>DF,NanoChatPreTrainedModel:()=>dc,NemotronHForCausalLM:()=>RF,NemotronHModel:()=>BF,NemotronHPreTrainedModel:()=>hc,NeoBertForMaskedLM:()=>$F,NeoBertForQuestionAnswering:()=>jF,NeoBertForSequenceClassification:()=>VF,NeoBertForTokenClassification:()=>UF,NeoBertModel:()=>GF,NeoBertPreTrainedModel:()=>xs,NomicBertModel:()=>qF,NomicBertPreTrainedModel:()=>Zm,OPTForCausalLM:()=>aL,OPTModel:()=>nL,OPTPreTrainedModel:()=>vc,Olmo2ForCausalLM:()=>XF,Olmo2Model:()=>QF,Olmo2PreTrainedModel:()=>_c,Olmo3ForCausalLM:()=>JF,Olmo3Model:()=>YF,Olmo3PreTrainedModel:()=>pc,OlmoForCausalLM:()=>HF,OlmoHybridForCausalLM:()=>ZF,OlmoHybridModel:()=>KF,OlmoHybridPreTrainedModel:()=>mc,OlmoModel:()=>WF,OlmoPreTrainedModel:()=>fc,OpenAIPrivacyFilterForTokenClassification:()=>tL,OpenAIPrivacyFilterModel:()=>eL,OpenAIPrivacyFilterPreTrainedModel:()=>gc,OpenELMForCausalLM:()=>sL,OpenELMModel:()=>rL,OpenELMPreTrainedModel:()=>wc,OwlViTForObjectDetection:()=>cL,OwlViTModel:()=>lL,OwlViTPreTrainedModel:()=>bc,Owlv2ForObjectDetection:()=>iL,Owlv2Model:()=>oL,Owlv2PreTrainedModel:()=>yc,PaliGemmaForConditionalGeneration:()=>uL,ParakeetForCTC:()=>dL,ParakeetPreTrainedModel:()=>eg,PatchTSMixerForPrediction:()=>fL,PatchTSMixerModel:()=>hL,PatchTSMixerPreTrainedModel:()=>Mc,PatchTSTForPrediction:()=>pL,PatchTSTModel:()=>_L,PatchTSTPreTrainedModel:()=>xc,Phi3ForCausalLM:()=>vL,Phi3Model:()=>wL,Phi3PreTrainedModel:()=>Tc,Phi3VForCausalLM:()=>rg,Phi3VPreTrainedModel:()=>tg,PhiForCausalLM:()=>gL,PhiModel:()=>mL,PhiPreTrainedModel:()=>kc,PreTrainedModel:()=>S,PvtForImageClassification:()=>bL,PvtModel:()=>yL,PvtPreTrainedModel:()=>Ec,PyAnnoteForAudioFrameClassification:()=>xL,PyAnnoteModel:()=>ML,PyAnnotePreTrainedModel:()=>Ac,Qwen2ForCausalLM:()=>TL,Qwen2Model:()=>kL,Qwen2MoeForCausalLM:()=>AL,Qwen2MoeModel:()=>EL,Qwen2MoePreTrainedModel:()=>Sc,Qwen2PreTrainedModel:()=>Cc,Qwen2VLForCausalLM:()=>Nm,Qwen2VLForConditionalGeneration:()=>Fl,Qwen2VLPreTrainedModel:()=>Om,Qwen2_5_VLForCausalLM:()=>Dm,Qwen2_5_VLForConditionalGeneration:()=>Ll,Qwen3ForCausalLM:()=>SL,Qwen3Model:()=>CL,Qwen3MoeForCausalLM:()=>FL,Qwen3MoeModel:()=>PL,Qwen3MoePreTrainedModel:()=>Fc,Qwen3NextForCausalLM:()=>IL,Qwen3NextModel:()=>LL,Qwen3NextPreTrainedModel:()=>Lc,Qwen3PreTrainedModel:()=>Pc,Qwen3VLForCausalLM:()=>sg,Qwen3VLForConditionalGeneration:()=>Ic,Qwen3VLMoeForCausalLM:()=>NL,Qwen3VLMoeForConditionalGeneration:()=>OL,Qwen3_5ForCausalLM:()=>ng,Qwen3_5ForConditionalGeneration:()=>Oc,Qwen3_5MoeForCausalLM:()=>zL,Qwen3_5MoeForConditionalGeneration:()=>DL,RFDetrForObjectDetection:()=>$L,RFDetrModel:()=>GL,RFDetrObjectDetectionOutput:()=>ag,RFDetrPreTrainedModel:()=>Dc,RTDetrForObjectDetection:()=>iC,RTDetrModel:()=>oC,RTDetrObjectDetectionOutput:()=>an,RTDetrPreTrainedModel:()=>hl,RTDetrV2ForObjectDetection:()=>ZL,RTDetrV2Model:()=>KL,RTDetrV2ObjectDetectionOutput:()=>og,RTDetrV2PreTrainedModel:()=>zc,ResNetForImageClassification:()=>RL,ResNetModel:()=>BL,ResNetPreTrainedModel:()=>Nc,RoFormerForMaskedLM:()=>QL,RoFormerForQuestionAnswering:()=>JL,RoFormerForSequenceClassification:()=>XL,RoFormerForTokenClassification:()=>YL,RoFormerModel:()=>HL,RoFormerPreTrainedModel:()=>Ts,RobertaForMaskedLM:()=>UL,RobertaForQuestionAnswering:()=>WL,RobertaForSequenceClassification:()=>jL,RobertaForTokenClassification:()=>qL,RobertaModel:()=>VL,RobertaPreTrainedModel:()=>ks,Sam2ImageSegmentationOutput:()=>cg,Sam2Model:()=>Bc,Sam2PreTrainedModel:()=>ug,Sam3TrackerModel:()=>rI,SamImageSegmentationOutput:()=>ig,SamModel:()=>eI,SamPreTrainedModel:()=>lg,SapiensForDepthEstimation:()=>nI,SapiensForNormalEstimation:()=>aI,SapiensForSemanticSegmentation:()=>sI,SapiensPreTrainedModel:()=>Ta,SegformerForImageClassification:()=>iI,SegformerForSemanticSegmentation:()=>lI,SegformerModel:()=>oI,SegformerPreTrainedModel:()=>Ea,SiglipModel:()=>cI,SiglipPreTrainedModel:()=>Rc,SiglipTextModel:()=>dg,SiglipVisionModel:()=>uI,SmolLM3ForCausalLM:()=>hI,SmolLM3Model:()=>dI,SmolLM3PreTrainedModel:()=>Gc,SmolVLMForConditionalGeneration:()=>fI,SnacDecoderModel:()=>fg,SnacEncoderModel:()=>hg,SnacModel:()=>_I,SnacPreTrainedModel:()=>Aa,SolarOpenForCausalLM:()=>mI,SolarOpenModel:()=>pI,SolarOpenPreTrainedModel:()=>$c,SpeechT5ForSpeechToText:()=>wI,SpeechT5ForTextToSpeech:()=>vI,SpeechT5HifiGan:()=>yI,SpeechT5Model:()=>gI,SpeechT5PreTrainedModel:()=>Ca,SqueezeBertForMaskedLM:()=>MI,SqueezeBertForQuestionAnswering:()=>kI,SqueezeBertForSequenceClassification:()=>xI,SqueezeBertModel:()=>bI,SqueezeBertPreTrainedModel:()=>hn,StableLmForCausalLM:()=>EI,StableLmModel:()=>TI,StableLmPreTrainedModel:()=>Vc,Starcoder2ForCausalLM:()=>CI,Starcoder2Model:()=>AI,Starcoder2PreTrainedModel:()=>Uc,StyleTextToSpeech2Model:()=>SI,StyleTextToSpeech2PreTrainedModel:()=>_g,SupertonicForConditionalGeneration:()=>mg,SupertonicPreTrainedModel:()=>pg,Swin2SRForImageSuperResolution:()=>OI,Swin2SRModel:()=>II,Swin2SRPreTrainedModel:()=>jc,SwinForImageClassification:()=>FI,SwinForSemanticSegmentation:()=>LI,SwinModel:()=>PI,SwinPreTrainedModel:()=>Sa,T5ForConditionalGeneration:()=>DI,T5Model:()=>NI,T5PreTrainedModel:()=>qc,TableTransformerForObjectDetection:()=>BI,TableTransformerModel:()=>zI,TableTransformerObjectDetectionOutput:()=>gg,TableTransformerPreTrainedModel:()=>Wc,TrOCRForCausalLM:()=>RI,TrOCRPreTrainedModel:()=>wg,UltravoxModel:()=>Vl,UltravoxPreTrainedModel:()=>zm,UniSpeechForCTC:()=>$I,UniSpeechForSequenceClassification:()=>VI,UniSpeechModel:()=>GI,UniSpeechPreTrainedModel:()=>Pa,UniSpeechSatForAudioFrameClassification:()=>WI,UniSpeechSatForCTC:()=>jI,UniSpeechSatForSequenceClassification:()=>qI,UniSpeechSatModel:()=>UI,UniSpeechSatPreTrainedModel:()=>fn,VaultGemmaForCausalLM:()=>QI,VaultGemmaModel:()=>HI,VaultGemmaPreTrainedModel:()=>Hc,ViTForImageClassification:()=>JI,ViTMAEModel:()=>KI,ViTMAEPreTrainedModel:()=>vg,ViTMSNForImageClassification:()=>eO,ViTMSNModel:()=>ZI,ViTMSNPreTrainedModel:()=>Xc,ViTModel:()=>YI,ViTPreTrainedModel:()=>Qc,VisionEncoderDecoderModel:()=>XI,VitMatteForImageMatting:()=>tO,VitMattePreTrainedModel:()=>yg,VitPoseForPoseEstimation:()=>rO,VitPosePreTrainedModel:()=>bg,VitsModel:()=>sO,VitsModelOutput:()=>Mg,VitsPreTrainedModel:()=>xg,VoxtralForConditionalGeneration:()=>nO,VoxtralRealtimeForConditionalGeneration:()=>Tg,VoxtralRealtimePreTrainedModel:()=>kg,Wav2Vec2BertForCTC:()=>hO,Wav2Vec2BertForSequenceClassification:()=>fO,Wav2Vec2BertModel:()=>dO,Wav2Vec2BertPreTrainedModel:()=>Fa,Wav2Vec2ForAudioFrameClassification:()=>oP,Wav2Vec2ForCTC:()=>nP,Wav2Vec2ForSequenceClassification:()=>aP,Wav2Vec2Model:()=>sP,Wav2Vec2PreTrainedModel:()=>kr,WavLMForAudioFrameClassification:()=>wO,WavLMForCTC:()=>pO,WavLMForSequenceClassification:()=>mO,WavLMForXVector:()=>gO,WavLMModel:()=>_O,WavLMPreTrainedModel:()=>Es,WeSpeakerResNetModel:()=>vO,WeSpeakerResNetPreTrainedModel:()=>Ag,WhisperForConditionalGeneration:()=>Cg,WhisperModel:()=>bO,WhisperPreTrainedModel:()=>Yc,XLMForQuestionAnswering:()=>AO,XLMForSequenceClassification:()=>TO,XLMForTokenClassification:()=>EO,XLMModel:()=>xO,XLMPreTrainedModel:()=>As,XLMRobertaForMaskedLM:()=>SO,XLMRobertaForQuestionAnswering:()=>LO,XLMRobertaForSequenceClassification:()=>PO,XLMRobertaForTokenClassification:()=>FO,XLMRobertaModel:()=>CO,XLMRobertaPreTrainedModel:()=>Cs,XLMWithLMHeadModel:()=>kO,XVectorOutput:()=>Eg,YolosForObjectDetection:()=>OO,YolosModel:()=>IO,YolosObjectDetectionOutput:()=>Sg,YolosPreTrainedModel:()=>Jc,YoutuForCausalLM:()=>DO,YoutuModel:()=>NO,YoutuPreTrainedModel:()=>Kc});var nn=class extends S{},eA=class extends nn{},tA=class extends nn{async _call(e){return new se(await super._call(e))}},rA=class extends nn{async _call(e){return new ct(await super._call(e))}},sA=class extends nn{async _call(e){return new He(await super._call(e))}},Ji=class extends S{},nA=class extends Ji{},aA=class extends Ji{},Ki=class extends S{},oA=class extends Ki{},iA=class extends Ki{},Zi=class extends S{},lA=class extends Zi{},cA=class extends Zi{},el=class extends S{},uA=class extends el{},dA=class extends el{},_a=class extends S{},hA=class extends _a{},fA=class extends _a{},_A=class extends _a{async _call(e){return new se(await super._call(e))}},tl=class extends S{},pA=class extends tl{},mA=class extends tl{async _call(e){return new se(await super._call(e))}},ps=class extends S{},gA=class extends ps{},wA=class extends ps{async _call(e){return new He(await super._call(e))}},vA=class extends ps{async _call(e){return new se(await super._call(e))}},yA=class extends ps{async _call(e){return new Ue(await super._call(e))}},bA=class extends ps{async _call(e){return new ct(await super._call(e))}},rl=class extends S{},MA=class extends rl{},xA=class extends rl{},sl=class extends S{},kA=class extends sl{},TA=class extends sl{},nl=class extends S{},EA=class extends nl{},AA=class extends nl{},ms=class extends S{},CA=class extends ms{},SA=class extends ms{async _call(e){return new He(await super._call(e))}},PA=class extends ms{async _call(e){return new se(await super._call(e))}},FA=class extends ms{async _call(e){return new Ue(await super._call(e))}},LA=class extends ms{async _call(e){return new ct(await super._call(e))}},IA=4299n,Ef=6561n,dm=class extends S{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},hm=class extends dm{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:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:c=null,audio_tokens:d=null,speaker_embeddings:h=null,speaker_features:_=null,...p}){let w;if(!a){const M=this.sessions.embed_tokens.inputNames,y={input_ids:e};if(M.includes("exaggeration")){if(!(s instanceof V)){const k=e.dims[0];if(s==null)s=ot([k],.5);else if(typeof s=="number")s=ot([k],s);else if(Array.isArray(s))s=new V("float32",s,[k]);else throw new Error("Unsupported type for `exaggeration` input")}y.exaggeration=s}if(M.includes("position_ids")&&(y.position_ids=n),{inputs_embeds:a}=await ye(this.sessions.embed_tokens,y),c&&d&&h&&_&&(w={audio_features:c,audio_tokens:d,speaker_embeddings:h,speaker_features:_}),w||r)w??=await this.encode_speech(r),a=Ne([w.audio_features,a],1),t=ft([a.dims[0],a.dims[1]]);else{const k=a.dims[1];if(!o||k!==1)throw new Error("Incorrect state encountered during generation.");const A=o.get_seq_length();t=ft([a.dims[0],A+k])}}return{...await ir(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...w}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const s=Array.from({length:e.length},(n,a)=>e[a].length-e[a].findLastIndex(o=>o==Ef)-1);t.position_ids=new V("int64",s,[e.length,1])}else{const n=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=Ef?0:o++)});t.position_ids=new V("int64",n.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),Qs(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:s,speaker_features:n}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=ot([a.dims[0],3],IA),i=Ne([r,a,o],1),{waveform:l}=await ye(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:n,speaker_embeddings:s});return l}},fm=class extends S{},OA=class extends fm{},_m=class extends S{},NA=class extends _m{},pa=class extends S{},DA=class extends pa{},pm=class extends pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},mm=class extends pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},$r=class extends S{},zA=class extends $r{},BA=class extends $r{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},gm=class extends $r{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},RA=class extends $r{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},GA=class extends $r{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},al=class extends S{},$A=class extends al{},VA=class extends al{},ol=class extends S{},UA=class extends ol{},jA=class extends ol{},il=class extends S{},qA=class extends il{},WA=class extends il{},ll=class extends S{},HA=class extends ll{},QA=class extends ll{},cl=class extends S{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},XA=class extends cl{},YA=class extends cl{},gs=class extends S{},JA=class extends gs{},KA=class extends gs{async _call(e){return new He(await super._call(e))}},ZA=class extends gs{async _call(e){return new se(await super._call(e))}},eC=class extends gs{async _call(e){return new Ue(await super._call(e))}},tC=class extends gs{async _call(e){return new ct(await super._call(e))}},ul=class extends S{},rC=class extends ul{},sC=class extends ul{async _call(e){return new se(await super._call(e))}},dl=class extends S{},nC=class extends dl{},aC=class extends dl{async _call(e){return new se(await super._call(e))}},hl=class extends S{},oC=class extends hl{},iC=class extends hl{async _call(e){return new an(await super._call(e))}},an=class extends We{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},fl=class extends S{},lC=class extends fl{},cC=class extends fl{async _call(e){return new an(await super._call(e))}},wm=class extends We{constructor({audio_codes:e}){super(),this.audio_codes=e}},vm=class extends We{constructor({audio_values:e}){super(),this.audio_values=e}},ma=class extends S{main_input_name="input_values";forward_params=["input_values"]},uC=class extends ma{async encode(e){return new wm(await ye(this.sessions.encoder_model,e))}async decode(e){return new vm(await ye(this.sessions.decoder_model,e))}},ym=class extends ma{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},bm=class extends ma{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},ws=class extends S{},dC=class extends ws{},hC=class extends ws{async _call(e){return new He(await super._call(e))}},fC=class extends ws{async _call(e){return new se(await super._call(e))}},_C=class extends ws{async _call(e){return new Ue(await super._call(e))}},pC=class extends ws{async _call(e){return new ct(await super._call(e))}},_l=class extends S{},mC=class extends _l{},gC=class extends _l{},vs=class extends S{},wC=class extends vs{},vC=class extends vs{async _call(e){return new He(await super._call(e))}},yC=class extends vs{async _call(e){return new se(await super._call(e))}},bC=class extends vs{async _call(e){return new Ue(await super._call(e))}},MC=class extends vs{async _call(e){return new ct(await super._call(e))}},Mm=class extends S{},xC=class extends Mm{},pl=class extends S{},kC=class extends pl{},TC=class extends pl{async _call(e){return new se(await super._call(e))}},xm=class extends S{},EC=class extends xm{},km=class extends S{},AC=class extends km{},ga=class extends S{},CC=class extends ga{},SC=class extends ga{async _call(e){return new ml(await super._call(e))}},PC=class extends ga{async _call(e){return new Tm(await super._call(e))}},ml=class extends We{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Tm=class extends We{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},gl=class extends S{},FC=class extends gl{},LC=class extends gl{async _call(e){return new se(await super._call(e))}},wl=class extends S{},IC=class extends wl{},OC=class extends wl{async _call(e){return new se(await super._call(e))}},Em=class extends S{},NC=class extends Em{},Am=class extends S{},DC=class extends Am{},ys=class extends S{},zC=class extends ys{},BC=class extends ys{async _call(e){return new se(await super._call(e))}},RC=class extends ys{async _call(e){return new Ue(await super._call(e))}},GC=class extends ys{async _call(e){return new ct(await super._call(e))}},$C=class extends ys{async _call(e){return new He(await super._call(e))}},Cm=class extends S{},VC=class extends Cm{},vl=class extends S{},UC=class extends vl{},jC=class extends vl{},yl=class extends S{},qC=class extends yl{},WC=class extends yl{async _call(e){return new se(await super._call(e))}},bs=class extends S{},HC=class extends bs{},QC=class extends bs{async _call(e){return new He(await super._call(e))}},XC=class extends bs{async _call(e){return new se(await super._call(e))}},YC=class extends bs{async _call(e){return new Ue(await super._call(e))}},JC=class extends bs{async _call(e){return new ct(await super._call(e))}},bl=class extends S{},KC=class extends bl{},ZC=class extends bl{},on=class extends S{},eS=class extends on{},tS=class extends on{async _call(e){return new He(await super._call(e))}},rS=class extends on{async _call(e){return new se(await super._call(e))}},sS=class extends on{async _call(e){return new Ue(await super._call(e))}},ln=class extends S{},nS=class extends ln{},aS=class extends ln{async _call(e){return new He(await super._call(e))}},oS=class extends ln{async _call(e){return new se(await super._call(e))}},iS=class extends ln{async _call(e){return new Ue(await super._call(e))}},Ml=class extends S{},lS=class extends Ml{},cS=class extends Ml{},xl=class extends S{},uS=class extends xl{},dS=class extends xl{},kl=class extends S{},hS=class extends kl{},fS=class extends kl{},Tl=class extends S{},_S=class extends Tl{},pS=class extends Tl{async _call(e){return new se(await super._call(e))}},Sm=class extends S{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},mS=class extends Sm{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:s}){return{inputs_embeds:Ne([t,e],1),attention_mask:Ne([ft(t.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:s}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,a;return e&&(n=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),n&&a?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:a,input_ids:e,attention_mask:s}):r=n||a,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:n,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:d}=await xr(this,{inputs_embeds:i,attention_mask:r});a=d}if(!l){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:s})}return await ir(this,{inputs_embeds:l,attention_mask:n,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},El=class extends S{},gS=class extends El{},wS=class extends El{},Al=class extends S{},vS=class extends Al{},yS=class extends Al{},Pm=class extends S{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},lr=class extends Pm{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Xi({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},bS=class extends lr{},MS=class extends lr{},Fm=class extends S{},xS=class extends Fm{},Lm=class extends lr{},kS=class extends Lm{},Im=class extends S{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},wa=class extends Im{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:s=null,input_features_mask:n=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,...h}){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:p}=await this._encode_vision({pixel_values:r,...h});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(s){const{audio_features:p}=await ye(this.sessions.audio_encoder,{input_features:s,input_features_mask:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await ir(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d},!0)}_encode_vision(e){return ye(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Xi({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 um({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},TS=class extends wa{},Cl=class extends wa{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return ye(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},ES=class extends Cl{},Sl=class extends S{},AS=class extends Sl{},CS=class extends Sl{},Pl=class extends S{},SS=class extends Pl{},PS=class extends Pl{},Om=class extends S{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Fl=class extends Om{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){const{data:r,dims:s}=lm(t),n=BigInt64Array.from({length:3*r.length},(o,i)=>r[i%r.length]),a=Array.from({length:s[0]},(o,i)=>$e(r.subarray(s[1]*i,s[1]*(i+1)))[0]+1n+BigInt(s[1]));return[new V("int64",n,[3,...s]),new V("int64",a,[a.length,1])]}else{const[r,s]=e.dims,n=BigInt64Array.from({length:3*r*s},(a,o)=>BigInt(Math.floor(o%s/r)));return[new V("int64",n,[3,...e.dims]),ip([r,1])]}}_reorder_and_write_positions(e,t,r,s){const n=e.reduce((l,c)=>l+c.length,0),a=new Array(n);let o=0;for(let l=0;l<3;++l)for(const c of e){const d=c.length/3;for(let h=l*d;h<(l+1)*d;++h)a[o++]=c[h]}let i=0;for(let l=0;l<t.length;++l)if(t[l]==1){for(let c=0;c<3;++c)r[c][s][l]=a[c*n/3+i];++i}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:s,state:n}){const{image_token_id:a,video_token_id:o,vision_start_token_id:i}=this.config,l=e,d=l.reduce((y,k,A)=>(k==i&&y.push(A),y),[]).map(y=>l[y+1]),h=d.filter(y=>y==a).length,_=d.filter(y=>y==o).length,p=[];let w=0,v=h,M=_;for(let y=0;y<d.length;++y){const k=l.findIndex((R,H)=>H>w&&R==a),A=l.findIndex((R,H)=>H>w&&R==o),E=v>0&&k!==-1?k:l.length+1,C=M>0&&A!==-1?A:l.length+1;let L,x,G,B;E<C?([x,G,B]=t[n.image_index],++n.image_index,--v,L=E):([x,G,B]=r[n.video_index],++n.video_index,--M,L=C);const[j,X,W]=[Number(x),Math.floor(Number(G)/s),Math.floor(Number(B)/s)],N=L-w,O=p.length>0?$e(p.at(-1))[0]+1:0;p.push(Array.from({length:3*N},(R,H)=>O+H%N));const U=N+O,Q=j*X*W,ee=Array.from({length:Q},(R,H)=>U+Math.floor(H/(X*W))),I=Array.from({length:Q},(R,H)=>U+Math.floor(H/W)%X),D=Array.from({length:Q},(R,H)=>U+H%W);p.push([ee,I,D].flat()),w=L+Q}if(w<l.length){const y=p.length>0?$e(p.at(-1))[0]+1:0,k=l.length-w;p.push(Array.from({length:3*k},(A,E)=>y+E%k))}return p}get_rope_index(e,t,r,s){const{vision_config:n}=this.config,a=n.spatial_merge_size??2;if(t||r){const o=e.tolist();s||(s=op(e));const i=s.tolist(),l=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],d=r?r.tolist():[],h={image_index:0,video_index:0},_=[];for(let p=0;p<o.length;++p){const w=o[p].filter((y,k)=>i[p][k]==1),v=this._get_multimodal_rope_positions({filtered_ids:w,image_grid_thw_list:c,video_grid_thw_list:d,spatial_merge_size:a,state:h}),M=this._reorder_and_write_positions(v,i[p],l,p);_.push($e(M)[0]+1-o[p].length)}return[new V("int64",l.flat(1/0),[3,e.dims[0],e.dims[1]]),new V("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,s)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await ye(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Xi({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const n=t.past_key_values.get_seq_length();if(n<t.input_ids.dims[1]){const[a,o]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=o,t.position_ids=a.slice(null,null,[n,null]),t.input_ids=t.input_ids.slice(null,[n,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));const a=BigInt(n),o=t.rope_deltas.map(i=>a+i);t.position_ids=or([o,o,o],0)}}return t}},Nm=class extends Fl{},Ll=class extends Fl{image_grid_thw_name="image_grid_thw"},Dm=class extends Nm{image_grid_thw_name="image_grid_thw"},FS=class extends Ll{get_vision_position_ids(e,t,r,s){const n=Math.floor(t[0]/r),a=Math.floor(t[1]/s),o=Math.floor(t[2]/s),i=a*o*n,l=Array.from({length:i},()=>e),c=Array.from({length:i},(h,_)=>e+Math.floor(_/(o*n))),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:s,state:n}){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,M)=>c+M%w)),c+=w}else{const w=t[n.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(c,w,v,s)),c+=Math.max(w[1],w[2])/s}return d}},Il=class extends S{},LS=class extends Il{},IS=class extends Il{},Ol=class extends S{},OS=class extends Ol{},NS=class extends Ol{},Nl=class extends S{},DS=class extends Nl{},zS=class extends Nl{},Dl=class extends S{},BS=class extends Dl{},RS=class extends Dl{},zl=class extends S{},GS=class extends zl{},$S=class extends zl{},Bl=class extends S{},VS=class extends Bl{},US=class extends Bl{},Rl=class extends S{},jS=class extends Rl{},qS=class extends Rl{},Gl=class extends S{},WS=class extends Gl{},HS=class extends Gl{},$l=class extends S{},QS=class extends $l{},XS=class extends $l{},zm=class extends S{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Vl=class extends zm{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return um({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},YS=class extends Vl{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},Bm=class extends S{},JS=class extends Bm{},Rm=class extends S{},KS=class extends Rm{},Ul=class extends S{},ZS=class extends Ul{},eP=class extends Ul{},jl=class extends S{},tP=class extends jl{},rP=class extends jl{async _call(e){return new se(await super._call(e))}},kr=class extends S{},sP=class extends kr{},nP=class extends kr{async _call(e){return new Gr(await super._call(e))}},aP=class extends kr{async _call(e){return new se(await super._call(e))}},oP=class extends kr{async _call(e){return new Ue(await super._call(e))}},iP=class extends S{},lP=class extends kr{},cP=class extends kr{async _call(e){return new Gr(await super._call(e))}},uP=class extends kr{async _call(e){return new se(await super._call(e))}},ql=class extends S{},dP=class extends ql{},hP=class extends ql{},Gm=class extends lr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},Wl=class extends S{},fP=class extends Wl{},_P=class extends Wl{async _call(e){return new se(await super._call(e))}},Hl=class extends S{},pP=class extends Hl{},mP=class extends Hl{},va=class extends S{},gP=class extends va{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=ft([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=ot([0,3,l,l],0)}const{text_embeddings:s,image_embeddings:n,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=s,i.l2norm_text_embeddings=a),r||(i.image_embeddings=n,i.l2norm_image_embeddings=o),i}},$m=class extends va{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},wP=class extends va{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ql=class extends S{},vP=class extends Ql{},yP=class extends Ql{},bP=class extends lr{},Xl=class extends S{},MP=class extends Xl{},xP=class extends Xl{},kP=class extends lr{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},Yl=class extends S{},TP=class extends Yl{},EP=class extends Yl{},Vm=class extends S{},AP=class extends Vm{},Jl=class extends S{},CP=class extends Jl{},SP=class extends Jl{},Kl=class extends S{},PP=class extends Kl{},FP=class extends Kl{},Zl=class extends S{},LP=class extends Zl{},IP=class extends Zl{},ec=class extends S{},OP=class extends ec{},NP=class extends ec{},cn=class extends S{},DP=class extends cn{},zP=class extends cn{},BP=class extends cn{async _call(e){return new se(await super._call(e))}},RP=class extends cn{},Um=class extends S{},GP=class extends Um{},jm=class extends S{},$P=class extends jm{},qm=class extends We{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]}},Wm=class extends S{},VP=class extends Wm{async _call(e){return new qm(await super._call(e))}},Hm=class extends We{constructor({audio_codes:e}){super(),this.audio_codes=e}},Qm=class extends We{constructor({audio_values:e}){super(),this.audio_values=e}},ya=class extends S{main_input_name="input_values";forward_params=["input_values"]},UP=class extends ya{async encode(e){return new Hm(await ye(this.sessions.encoder_model,e))}async decode(e){return new Qm(await ye(this.sessions.decoder_model,e))}},Xm=class extends ya{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Ym=class extends ya{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},tc=class extends S{},jP=class extends tc{},qP=class extends tc{},rc=class extends S{},WP=class extends rc{},HP=class extends rc{},un=class extends S{},QP=class extends un{},XP=class extends un{async _call(e){return new He(await super._call(e))}},YP=class extends un{async _call(e){return new se(await super._call(e))}},JP=class extends un{async _call(e){return new ct(await super._call(e))}},sc=class extends S{},KP=class extends sc{},ZP=class extends sc{},ba=class extends S{},eF=class extends ba{},tF=class extends ba{async _call(e){return new se(await super._call(e))}},rF=class extends ba{},Ma=class extends S{},sF=class extends Ma{},nF=class extends Ma{async _call(e){return new se(await super._call(e))}},aF=class extends Ma{},xa=class extends S{},oF=class extends xa{},iF=class extends xa{async _call(e){return new se(await super._call(e))}},lF=class extends xa{},ka=class extends S{},cF=class extends ka{},uF=class extends ka{async _call(e){return new se(await super._call(e))}},dF=class extends ka{},nc=class extends S{},hF=class extends nc{},fF=class extends nc{async _call(e){return new se(await super._call(e))}},ac=class extends S{},_F=class extends ac{},pF=class extends ac{async _call(e){return new se(await super._call(e))}},dn=class extends S{},mF=class extends dn{},gF=class extends dn{async _call(e){return new He(await super._call(e))}},wF=class extends dn{async _call(e){return new se(await super._call(e))}},vF=class extends dn{async _call(e){return new Ue(await super._call(e))}},oc=class extends S{},yF=class extends oc{},bF=class extends oc{},ic=class extends S{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},MF=class extends ic{},xF=class extends ic{},Ms=class extends S{},kF=class extends Ms{},TF=class extends Ms{async _call(e){return new He(await super._call(e))}},EF=class extends Ms{async _call(e){return new se(await super._call(e))}},AF=class extends Ms{async _call(e){return new Ue(await super._call(e))}},CF=class extends Ms{async _call(e){return new ct(await super._call(e))}},lc=class extends S{},SF=class extends lc{},PF=class extends lc{},cc=class extends S{},FF=class extends cc{},LF=class extends cc{},Jm=class extends S{},IF=class extends Jm{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let r;if(t==="text"||!e.past_key_values){const i=this.sessions.prepare_inputs_embeds,l=Ke(e,i.inputNames);r=await ye(i,l)}else{const i=this.sessions.gen_img_embeds,l=Ke({image_ids:e.input_ids},i.inputNames);r=await ye(i,l)}const s={...e,...r},n=await ir(this,s),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);const o=await ye(a,Ke(n,a.inputNames));return{...r,...n,...o}}prepare_inputs_for_generation(e,t,r){const s=!!t.past_key_values;return r.guidance_scale!==null&&r.guidance_scale>1&&(s?t.input_ids=Ne([t.input_ids,t.input_ids],0):(t.input_ids=Ne([t.input_ids,Zo(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=Ne([t.attention_mask,Zo(t.attention_mask,0n)],0))),(s||!t.pixel_values)&&(t.pixel_values=ot([0,0,3,384,384],1)),s&&(t.images_seq_mask=new V("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new V("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),n=this.sessions.image_decode,{decoded_image:a}=await ye(n,{generated_tokens:s}),o=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const l of o){const c=Ot.fromTensor(l);i.push(c)}return i}},uc=class extends S{},OF=class extends uc{},NF=class extends uc{},Km=class extends S{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,r]=e.dims,s=this.config.decoder.num_codebooks,n=r-s;let a=0;for(let l=0;l<e.size;++l){if(e.data[l]==this.config.decoder.pad_token_id)continue;const c=l%r,d=Math.floor(l/r)%s,h=c-d;h>0&&h<=n&&(e.data[a++]=e.data[l])}const o=Math.floor(t/s),i=a/(o*s);return new V(e.type,e.data.slice(0,a),[o,s,i])}prepare_inputs_for_generation(e,t,r){const s=BigInt(this.config.decoder.pad_token_id);let n=structuredClone(e);for(let a=0;a<n.length;++a)for(let o=0;o<n[a].length;++o)a%this.config.decoder.num_codebooks>=o&&(n[a][o]=s);return r.guidance_scale!==null&&r.guidance_scale>1&&(n=n.concat(n)),ra(this,n,t)}async generate(e){const t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:s}=await ye(this.sessions.encodec_decode,{audio_codes:r});return s}},dc=class extends S{},DF=class extends dc{},zF=class extends dc{},hc=class extends S{},BF=class extends hc{},RF=class extends hc{},xs=class extends S{},GF=class extends xs{},$F=class extends xs{async _call(e){return new He(await super._call(e))}},VF=class extends xs{async _call(e){return new se(await super._call(e))}},UF=class extends xs{async _call(e){return new Ue(await super._call(e))}},jF=class extends xs{async _call(e){return new ct(await super._call(e))}},Zm=class extends S{},qF=class extends Zm{},fc=class extends S{},WF=class extends fc{},HF=class extends fc{},_c=class extends S{},QF=class extends _c{},XF=class extends _c{},pc=class extends S{},YF=class extends pc{},JF=class extends pc{},mc=class extends S{},KF=class extends mc{},ZF=class extends mc{},gc=class extends S{},eL=class extends gc{},tL=class extends gc{async _call(e){return new se(await super._call(e))}},wc=class extends S{},rL=class extends wc{},sL=class extends wc{},vc=class extends S{},nL=class extends vc{},aL=class extends vc{},yc=class extends S{},oL=class extends yc{},iL=class extends yc{},bc=class extends S{},lL=class extends bc{},cL=class extends bc{},uL=class extends lr{},eg=class extends S{},dL=class extends eg{async _call(e){return new Gr(await super._call(e))}},Mc=class extends S{},hL=class extends Mc{},fL=class extends Mc{},xc=class extends S{},_L=class extends xc{},pL=class extends xc{},kc=class extends S{},mL=class extends kc{},gL=class extends kc{},Tc=class extends S{},wL=class extends Tc{},vL=class extends Tc{},tg=class extends S{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},rg=class extends tg{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!a){let h;if(r&&e.dims[1]!==1){if(!s)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:h}=await ye(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}))}else{const _=this.config.normalized_config.hidden_size;h=new V("float32",[],[0,_])}({inputs_embeds:a}=await ye(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:h}))}return await ir(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:n,generation_config:i,logits_processor:l},!1)}},Ec=class extends S{},yL=class extends Ec{},bL=class extends Ec{async _call(e){return new se(await super._call(e))}},Ac=class extends S{},ML=class extends Ac{},xL=class extends Ac{async _call(e){return new Ue(await super._call(e))}},Cc=class extends S{},kL=class extends Cc{},TL=class extends Cc{},Sc=class extends S{},EL=class extends Sc{},AL=class extends Sc{},Pc=class extends S{},CL=class extends Pc{},SL=class extends Pc{},Fc=class extends S{},PL=class extends Fc{},FL=class extends Fc{},Lc=class extends S{},LL=class extends Lc{},IL=class extends Lc{},Ic=class extends Ll{},sg=class extends Dm{},OL=class extends Ic{},NL=class extends sg{},Oc=class extends Ic{},ng=class extends Oc{},DL=class extends Oc{},zL=class extends ng{},Nc=class extends S{},BL=class extends Nc{},RL=class extends Nc{async _call(e){return new se(await super._call(e))}},Dc=class extends S{},GL=class extends Dc{},$L=class extends Dc{async _call(e){return new ag(await super._call(e))}},ag=class extends an{},ks=class extends S{},VL=class extends ks{},UL=class extends ks{async _call(e){return new He(await super._call(e))}},jL=class extends ks{async _call(e){return new se(await super._call(e))}},qL=class extends ks{async _call(e){return new Ue(await super._call(e))}},WL=class extends ks{async _call(e){return new ct(await super._call(e))}},Ts=class extends S{},HL=class extends Ts{},QL=class extends Ts{async _call(e){return new He(await super._call(e))}},XL=class extends Ts{async _call(e){return new se(await super._call(e))}},YL=class extends Ts{async _call(e){return new Ue(await super._call(e))}},JL=class extends Ts{async _call(e){return new ct(await super._call(e))}},zc=class extends S{},KL=class extends zc{},ZL=class extends zc{async _call(e){return new og(await super._call(e))}},og=class extends an{},ig=class extends We{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},lg=class extends S{},eI=class extends lg{async get_image_embeddings({pixel_values:e}){return await xr(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??=ft(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 ig(await super._call(e))}},cg=class extends We{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}},ug=class extends S{},Bc=class extends ug{async get_image_embeddings({pixel_values:e}){return await xr(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??=ft(a.slice(0,-1)),e.input_boxes??=ot([a[0],0,4],0)}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=ot([a[0],a[1],0],-1n),e.input_points=ot([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const s=this.sessions.prompt_encoder_mask_decoder,n=Ke(e,s.inputNames);return await ye(s,n)}async _call(e){return new cg(await super._call(e))}},tI=class extends Bc{},rI=class extends Bc{},Ta=class extends S{},sI=class extends Ta{},nI=class extends Ta{},aI=class extends Ta{},Ea=class extends S{},oI=class extends Ea{},iI=class extends Ea{},lI=class extends Ea{},Rc=class extends S{},cI=class extends Rc{},dg=class extends Rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},uI=class extends $r{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Gc=class extends S{},dI=class extends Gc{},hI=class extends Gc{},fI=class extends Gm{},Aa=class extends S{main_input_name="input_values";forward_params=["input_values"]},_I=class extends Aa{async encode(e){return await ye(this.sessions.encoder_model,e)}async decode(e){return await ye(this.sessions.decoder_model,e)}},hg=class extends Aa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},fg=class extends Aa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},$c=class extends S{},pI=class extends $c{},mI=class extends $c{},Ca=class extends S{},gI=class extends Ca{},wI=class extends Ca{},vI=class extends Ca{async generate_speech(e,t,{threshold:r=.5,minlenratio:s=0,maxlenratio:n=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await xr(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),h=Math.floor(c*s),_=this.config.num_mel_bins;let p=[],w=null,v=null,M=0;for(;;){++M;const A=am(!!v);let E;v?E=v.output_sequence_out:E=new V("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:A,output_sequence:E,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};Qi(this,C,w),v=await ye(this.sessions.decoder_model_merged,C),w=oi(v,w);const{prob:L,spectrum:x}=v;if(p.push(x),M>=h&&(Array.from(L.data).filter(G=>G>=r).length>0||M>=d))break}const y=Ne(p),{waveform:k}=await ye(a.sessions.model,{spectrogram:y});return{spectrogram:y,waveform:k}}},yI=class extends S{main_input_name="spectrogram"},hn=class extends S{},bI=class extends hn{},MI=class extends hn{async _call(e){return new He(await super._call(e))}},xI=class extends hn{async _call(e){return new se(await super._call(e))}},kI=class extends hn{async _call(e){return new ct(await super._call(e))}},Vc=class extends S{},TI=class extends Vc{},EI=class extends Vc{},Uc=class extends S{},AI=class extends Uc{},CI=class extends Uc{},_g=class extends S{},SI=class extends _g{},pg=class extends S{},mg=class extends pg{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:s=5,speed:n=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(n).mul_(a),_=i*o,p=h.data,w=Int32Array.from(p,B=>Math.ceil(B/_)),v=Math.max(...w),M=e.dims[0],y=new BigInt64Array(M*v);for(let B=0;B<M;++B)y.fill(1n,B*v,B*v+w[B]);const k=new V("int64",y,[M,v]),A=l*o,E=A*v;let C=rk([M,A,v]);const L=C.data;for(let B=0;B<M;++B)if(w[B]!==v)for(let j=0;j<A;++j)L.fill(0,B*E+j*v+w[B],B*E+(j+1)*v);const x=ot([M],s);for(let B=0;B<s;++B){const j=ot([M],B);({denoised_latents:C}=await ye(this.sessions.latent_denoiser,{style:r,noisy_latents:C,latent_mask:k,encoder_outputs:c,attention_mask:t,timestep:j,num_inference_steps:x}))}const{waveform:G}=await ye(this.sessions.voice_decoder,{latents:C});return{waveform:G,durations:h}}},Sa=class extends S{},PI=class extends Sa{},FI=class extends Sa{async _call(e){return new se(await super._call(e))}},LI=class extends Sa{},jc=class extends S{},II=class extends jc{},OI=class extends jc{},qc=class extends S{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},NI=class extends qc{},DI=class extends qc{},Wc=class extends S{},zI=class extends Wc{},BI=class extends Wc{async _call(e){return new gg(await super._call(e))}},gg=class extends ml{},wg=class extends S{},RI=class extends wg{},Pa=class extends S{},GI=class extends Pa{},$I=class extends Pa{async _call(e){return new Gr(await super._call(e))}},VI=class extends Pa{async _call(e){return new se(await super._call(e))}},fn=class extends S{},UI=class extends fn{},jI=class extends fn{async _call(e){return new Gr(await super._call(e))}},qI=class extends fn{async _call(e){return new se(await super._call(e))}},WI=class extends fn{async _call(e){return new Ue(await super._call(e))}},Hc=class extends S{},HI=class extends Hc{},QI=class extends Hc{},XI=class extends S{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},Qc=class extends S{},YI=class extends Qc{},JI=class extends Qc{async _call(e){return new se(await super._call(e))}},vg=class extends S{},KI=class extends vg{},Xc=class extends S{},ZI=class extends Xc{},eO=class extends Xc{async _call(e){return new se(await super._call(e))}},yg=class extends S{},tO=class extends yg{async _call(e){return new E2(await super._call(e))}},bg=class extends S{},rO=class extends bg{},Mg=class extends We{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},xg=class extends S{},sO=class extends xg{async _call(e){return new Mg(await super._call(e))}},nO=class extends Vl{},Af=2,aO=1,Go=new WeakMap;function oO(e,t){const{text_config:r,audio_config:s}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=s,i=a+o,l=new Wi,c=da(s),d={batch_size:1};let h="float32";for(const v of n.inputMetadata){if(v.name==="past_padding_cache"){h=v.type;continue}if(!c.has(v.name))continue;const M=om(v.shape,d),y=M.reduce((A,E)=>A*E,1),k=Js[v.type];l[v.name]=new V(v.type,new k(y),M)}const _=Js[h],p=new V(h,new _(i*Af),[1,i,Af]),w=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,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 iO(e,t){const r=t.dims[2],s=Math.floor((aO+r-3)/2)+1,n=new V("int64",BigInt64Array.from({length:s},(d,h)=>BigInt(e.enc_past_seq_len+h)),[1,s]),a=e.enc_past_seq_len+s,o=ft([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await ye(e.encoder_session,{input_features:t,attention_mask:o,position_ids:n,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];_?.location==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[h]=c[d]}return e.enc_past_seq_len=a,i}async function lO(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 s=await iO(e,r.value);e.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),e.audio_embed_total_tokens+=s.dims[1]}}function cO(e,t,r){if(e.audio_embed_queue.length===0)return;const s=t.data;let n=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)s[n*e.text_hidden_size+d]+=o.data[c+d];n+=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 uO=class extends ha{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)}},kg=class extends S{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Tg=class extends kg{async forward({input_ids:e,past_key_values:t,...r}){const s=e.dims[1],n=Go.get(this);n&&await lO(n,n.audio_consumed+s);const{inputs_embeds:a}=await ye(this.sessions.embed_tokens,{input_ids:e});n&&cO(n,a,s);const o={inputs_embeds:a,...r};Qi(this,o,t);const i=this.sessions.decoder_model_merged,l=Ke(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 s=oO(this,e);Go.set(this,s);const n=new em;n.push(new uO(s)),t&&n.extend(t);try{return await super.generate({...r,stopping_criteria:n})}finally{s.enc_kv_cache.dispose(),Go.delete(this)}}},Fa=class extends S{},dO=class extends Fa{},hO=class extends Fa{async _call(e){return new Gr(await super._call(e))}},fO=class extends Fa{async _call(e){return new se(await super._call(e))}},Eg=class extends We{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Es=class extends S{},_O=class extends Es{},pO=class extends Es{async _call(e){return new Gr(await super._call(e))}},mO=class extends Es{async _call(e){return new se(await super._call(e))}},gO=class extends Es{async _call(e){return new Eg(await super._call(e))}},wO=class extends Es{async _call(e){return new Ue(await super._call(e))}},Ag=class extends S{},vO=class extends Ag{},yO=class extends Zp{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},Yc=class extends S{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},bO=class extends Yc{},Cg=class extends Yc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,yO)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const s=e.task;if(e.is_multilingual){r||(ie.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[s??"transcribe"])}else if(r||s)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&&(ie.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,...n}){t=this._prepare_generation_config(t,n);const a=n.decoder_input_ids instanceof V?zi(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new ni,r.push(new F2(t,a))),t.begin_suppress_tokens&&(r??=new ni,r.push(new Kp(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"&&ie.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&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:n});const o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...n});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:s,kwargs:n}){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 y=Math.min(p+_,c),k=l.slice(null,null,[p,y]);let A;const E=k.dims[2];if(E<_){const Q=l.dims[1],ee=new Float32Array(Q*_),I=k.data;for(let D=0;D<Q;++D)ee.set(I.subarray(D*E,(D+1)*E),D*_);A=new V("float32",ee,[1,Q,_])}else A=k;if(r)for(const Q of r)"begin_index"in Q&&(Q.begin_index=s.length);const C=await super.generate({inputs:A,generation_config:t,logits_processor:r,decoder_input_ids:s,...n}),x=(i?C.sequences:C)[0].tolist().map(Number).slice(s.length);let G;if(i){C.token_timestamps=this._extract_token_timestamps(C,t.alignment_heads,Math.floor((y-p)/d),.02,s.length);const Q=p/d*.02;G=C.token_timestamps[0].tolist().slice(s.length).map(ee=>ee+Q)}if(x.length>0&&x.at(-1)===o&&x.pop(),x.length===0)break;const B=x.map(Q=>Q>=a),j=x.length>=2&&B[x.length-1]&&!B[x.length-2],X=[];for(let Q=0;Q<x.length-1;++Q)B[Q]&&B[Q+1]&&X.push(Q+1);let W,N=x.length;if(X.length>0)if(j)W=y-p;else{const Q=X.at(-1);W=(x[Q-1]-a)*d,N=Q}else W=y-p;const O=Math.floor(p/d),U=a+1500;for(let Q=0;Q<N;++Q)x[Q]>=a&&(x[Q]=Math.min(x[Q]+O,U));w.push(...x.slice(0,N)),G&&v.push(...G.slice(0,N)),p+=W}w.push(o);const M=[...s,...w];if(i){const y=new V("int64",M.map(BigInt),[1,M.length]),k=[...new Array(s.length).fill(0),...v,0],A=new V("float32",new Float32Array(k),[1,k.length]);return{sequences:y,token_timestamps:A}}return new V("int64",M.map(BigInt),[1,M.length])}_extract_token_timestamps(e,t,r=null,s=.02,n=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&&ie.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&&(ie.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},(M,y)=>Ne(o.map(k=>k[y]),2)),l=or(t.map(([M,y])=>{if(M>=i.length)throw new Error(`Layer index ${M} is out of bounds for cross attentions (length ${i.length}).`);return r?i[M].slice(null,y,null,[0,r]):i[M].slice(null,y)})).transpose(1,0,2,3),[c,d]=tk(l,-2,0,!0),h=l.clone();for(let M=0;M<h.dims[0];++M){const y=h[M];for(let k=0;k<y.dims[0];++k){const A=y[k],E=c[M][k][0].data,C=d[M][k][0].data;for(let L=0;L<A.dims[0];++L){let x=A[L].data;for(let G=0;G<x.length;++G)x[G]=(x[G]-C[G])/E[G];x.set(z1(x,a))}}}const _=n>0?h.slice(null,null,[n,h.dims[2]],null):h,p=[Ni(_,1)],w=e.sequences.dims,v=new V("float32",new Float32Array(w[0]*w[1]),w);for(let M=0;M<w[0];++M){const y=p[M].neg().squeeze_(0),[k,A]=R1(y.tolist()),E=Array.from({length:k.length-1},(G,B)=>k[B+1]-k[B]),C=Ht([1],E).map(G=>!!G),L=[];for(let G=0;G<C.length;++G)C[G]&&L.push(A[G]*s);const x=new Array(n).fill(0);x.push(...L),L.length>0&&x.push(L.at(-1)),v[M].data.set(x)}return v}},MO=class extends Cg{},As=class extends S{},xO=class extends As{},kO=class extends As{async _call(e){return new He(await super._call(e))}},TO=class extends As{async _call(e){return new se(await super._call(e))}},EO=class extends As{async _call(e){return new Ue(await super._call(e))}},AO=class extends As{async _call(e){return new ct(await super._call(e))}},Cs=class extends S{},CO=class extends Cs{},SO=class extends Cs{async _call(e){return new He(await super._call(e))}},PO=class extends Cs{async _call(e){return new se(await super._call(e))}},FO=class extends Cs{async _call(e){return new Ue(await super._call(e))}},LO=class extends Cs{async _call(e){return new ct(await super._call(e))}},Jc=class extends S{},IO=class extends Jc{},OO=class extends Jc{async _call(e){return new Sg(await super._call(e))}},Sg=class extends We{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Kc=class extends S{},NO=class extends Kc{},DO=class extends Kc{},zO=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"]]),BO=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"]]),RO=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),GO=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),Pg=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Fg=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Lg=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Ig=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"]]),Og=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"]]),Ng=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Dg=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),$O=new Map([["multi_modality","MultiModalityCausalLM"]]),zg=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"]]),Bg=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"]]),Rg=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Gg=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),$g=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),VO=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Vg=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),Ug=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),jg=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),ns=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),qg=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Wg=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Hg=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Qg=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Xg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Yg=new Map([["wavlm","WavLMForXVector"]]),Jg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),Kg=new Map([["vitmatte","VitMatteForImageMatting"]]),UO=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),Zg=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),ew=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),tw=new Map([["sapiens","SapiensForNormalEstimation"]]),rw=new Map([["vitpose","VitPoseForPoseEstimation"]]),sw=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),nw=[[zO,q.EncoderOnly],[BO,q.EncoderDecoder],[GO,q.DecoderOnlyWithoutHead],[RO,q.AutoEncoder],[Ig,q.EncoderOnly],[Og,q.EncoderOnly],[Ng,q.Seq2Seq],[Pg,q.Seq2Seq],[Dg,q.DecoderOnly],[$O,q.MultiModality],[zg,q.EncoderOnly],[Bg,q.EncoderOnly],[Rg,q.Vision2Seq],[Gg,q.ImageTextToText],[$g,q.AudioTextToText],[Vg,q.EncoderOnly],[ns,q.EncoderOnly],[Wg,q.EncoderOnly],[qg,q.EncoderOnly],[Kg,q.EncoderOnly],[UO,q.EncoderOnly],[Zg,q.EncoderOnly],[ew,q.EncoderOnly],[tw,q.EncoderOnly],[rw,q.EncoderOnly],[Ug,q.EncoderOnly],[jg,q.EncoderOnly],[Hg,q.MaskGeneration],[Qg,q.EncoderOnly],[Xg,q.EncoderOnly],[Fg,q.Seq2Seq],[Lg,q.EncoderOnly],[Yg,q.EncoderOnly],[Jg,q.EncoderOnly],[sw,q.EncoderOnly]];for(const[e,t]of nw)for(const r of e.values()){ar.set(r,t);const s=Yi[r];cs.set(s,r),Hi.set(r,s)}var jO=[["MusicgenForConditionalGeneration",Km,q.Musicgen],["Phi3VForCausalLM",rg,q.Phi3V],["CLIPTextModelWithProjection",gm,q.EncoderOnly],["SiglipTextModel",dg,q.EncoderOnly],["JinaCLIPTextModel",$m,q.EncoderOnly],["ClapTextModelWithProjection",pm,q.EncoderOnly],["ClapAudioModelWithProjection",mm,q.EncoderOnly],["DacEncoderModel",ym,q.EncoderOnly],["DacDecoderModel",bm,q.EncoderOnly],["MimiEncoderModel",Xm,q.EncoderOnly],["MimiDecoderModel",Ym,q.EncoderOnly],["SnacEncoderModel",hg,q.EncoderOnly],["SnacDecoderModel",fg,q.EncoderOnly],["Gemma3nForConditionalGeneration",wa,q.ImageAudioTextToText],["Gemma4ForConditionalGeneration",Cl,q.ImageAudioTextToText],["SupertonicForConditionalGeneration",mg,q.Supertonic],["ChatterboxModel",hm,q.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Tg,q.VoxtralRealtime]];for(const[e,t,r]of jO)ar.set(e,r),cs.set(t,e),Hi.set(e,t);var aw=new Map([["modnet",ns],["birefnet",ns],["isnet",ns],["ben",ns]]);for(const[e,t]of aw.entries())t.set(e,"PreTrainedModel"),ar.set(e,q.EncoderOnly),Hi.set(e,S);var qO=new Set(aw.keys());ar.set("PreTrainedModel",q.EncoderOnly);cs.set(S,"PreTrainedModel");var Ae={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Ig,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Og,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Fg,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Lg,MODEL_FOR_MASKED_LM_MAPPING_NAMES:zg,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Bg,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Vg,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:ns,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:qg,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Wg,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Ug,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:jg,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Hg,MODEL_FOR_CTC_MAPPING_NAMES:Qg,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Xg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Yg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Jg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:VO,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:Kg,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:Zg,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:ew,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:tw,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:rw,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:sw,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Gg,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:$g,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Ng,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Pg,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Dg,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Rg};H2(Ae);var Ce=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(const t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!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:s,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h};if(_.config=await Zs.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 M of w.values())if(M[0]===p){v=M;break}if(!v)continue}return await Yi[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return qO.has(p)||ie.warn(`Unknown model class "${p}", attempting to construct from base class.`),await S.from_pretrained(e,_);throw Error(`Unsupported model type: ${p}`)}},Ws=class extends Ce{static MODEL_CLASS_MAPPINGS=nw.map(e=>e[0]);static BASE_IF_FAIL=!0},Cf=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},WO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},$o=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},HO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},QO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},XO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},YO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},JO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},KO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},ZO=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},eN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Sf=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Pf=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Ff=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},tN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},rN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var sN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_CTC_MAPPING_NAMES]},nN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});var aN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var oN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},iN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});var lN=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends Ce{static MODEL_CLASS_MAPPINGS=[Ae.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});async function Rt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>Ot.read(t)))}async function as(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 ii(e,t){t&&(e=e.map(o=>o|0));const[r,s,n,a]=e;return{xmin:r,ymin:s,xmax:n,ymax:a}}var Ge=class extends _t{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}},cN=class extends Ge{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),{problem_type:n,id2label:a}=this.model.config,o=n==="multi_label_classification"?l=>l.sigmoid():l=>new V("float32",rt(l.data),l.dims),i=[];for(const l of s.logits){const c=o(l),d=await _s(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]}},uN=class extends Ge{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 s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),o=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let c=0;c<o.dims[0];++c){const d=n.input_ids[c].tolist(),h=o[c],_=[];for(let p=0;p<h.dims[0];++p){const w=h[p],v=$e(w.data)[1],M=i?i[v]:`LABEL_${v}`;if(t.includes(M))continue;const y=this.tokenizer.decode([d[p]],{skip_special_tokens:!0});if(y==="")continue;const k=rt(w.data);_.push({entity:M,score:k[v],index:p,word:y})}l.push(r==="simple"?hN(_,d,this.tokenizer):_)}return s?l:l[0]}};function dN(e){const t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function hN(e,t,r){const s=[];let n=null;for(let a=0;a<e.length;++a){const[o,i]=dN(e[a].entity);n===i&&o!=="B"&&o!=="S"?(s[s.length-1].end=a+1,o==="E"&&(n=null)):(s.push({tag:i,start:a,end:a+1}),n=o==="S"?null:i)}return s.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 fN=class extends Ge{async _call(e,t,{top_k:r=1}={}){const s=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),n=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(s),i=s.input_ids.tolist(),l=s.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(),M=o[_].tolist();for(let C=1;C<v.length;++C)(l[_]==0||C<=w||c.findIndex(L=>L==p[C])!==-1)&&(v[C]=-1/0,M[C]=-1/0);const y=rt(v).map((C,L)=>[C,L]),k=rt(M).map((C,L)=>[C,L]);y[0][0]=0,k[0][0]=0;const A=l0(y,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,L)=>L[2]-C[2]),E=[];for(let C=0;C<Math.min(A.length,r);++C){const[L,x,G]=A[C],B=p.slice(L,x+1),j=this.tokenizer.decode(B,{skip_special_tokens:!0});E.push({answer:j,score:G})}r===1?h.push(...E):h.push(E)}return n?h:h[0]}},_N=class extends Ge{async _call(e,{top_k:t=5}={}){const{mask_token_id:r,mask_token:s}=this.tokenizer,n=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(n),o=[],i=n.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 (${s}) not found in text.`);const h=a[l][d],_=await _s(new V("float32",rt(h.data),h.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((v,M)=>{const y=c.slice();return y[d]=v,{score:p[M],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(y,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Zc=class extends Ge{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(i=>this.model.config.prefix+i));const r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(i=>r[this.task].prefix+i));const s=this.tokenizer,n={padding:!0,truncation:!0};let a;this.task==="translation"&&"_build_translation_inputs"in s?a=s._build_translation_inputs(e,n,t):a=s(e,n);const o=await this.model.generate({...a,...this._default_generation_config,...t});return s.batch_decode(o,{skip_special_tokens:!0}).map(i=>({[this._key]:i}))}},pN=class extends Zc{_key="summary_text"},mN=class extends Zc{_key="translation_text"};function Lf(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var gN=class extends Ge{_default_generation_config={max_new_tokens:256};async _call(e,t={}){const{add_special_tokens:r,return_full_text:s,tools:n,documents:a,chat_template:o,tokenizer_encode_kwargs:i,...l}=t;let c=!1,d=!1,h=r??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,_=i,p;if(typeof e=="string")p=e=[e];else if(Array.isArray(e)&&e.every(E=>typeof E=="string"))c=!0,p=e;else{if(Lf(e))e=[e];else if(Array.isArray(e)&&e.every(Lf))c=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");d=!0;const E={tokenize:!1,add_generation_prompt:!0,...Ke({tools:n,documents:a,chat_template:o},["tools","documents","chat_template"]),..._};p=e.map(C=>this.tokenizer.apply_chat_template(C,E)),h=!1,_=void 0}const w=d?!1:s??!0;this.tokenizer.padding_side="left";const v=this.tokenizer(p,{add_special_tokens:h,padding:!0,truncation:!0,..._}),M=await this.model.generate({...v,...this._default_generation_config,...l}),y=this.tokenizer.batch_decode(M,{skip_special_tokens:!0});let k;!w&&v.input_ids.dims.at(-1)>0&&(k=this.tokenizer.batch_decode(v.input_ids,{skip_special_tokens:!0}).map(E=>E.length));const A=Array.from({length:e.length},E=>[]);for(let E=0;E<y.length;++E){const C=Math.floor(E/M.dims[0]*e.length);k&&(y[E]=y[E].slice(k[C])),A[C].push({generated_text:d?[...e[C],{role:"assistant",content:y[E]}]:y[E]})}return!c&&A.length===1?A[0]:A}},wN=class extends Ge{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&&(ie.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&&(ie.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:s=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>r.replace("{}",l)),o=s||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(_=>rt(_)[1]):rt(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:h.map(_=>t[_[1]]),scores:h.map(_=>_[0])})}return n?i:i[0]}},vN=class extends Ge{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await as(e,r),n=this.model.config.id2label,a=[];for(const o of s){const i=await this.processor(o),c=(await this.model(i)).logits[0],d=await _s(new V("float32",rt(c.data),c.dims),t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:n?n[w]:`LABEL_${w}`,score:h[v]}));a.push(p)}return Array.isArray(e)?a:a[0]}},yN=class extends Ge{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const n=t.map(c=>r.replace("{}",c)),a=this.tokenizer(n,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await as(e,o),l=[];for(const c of i){const d=await this.processor(c),h=await this.model({...a,...d}),_=rt(h.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})))}return s?l[0]:l}},bN=class extends Ge{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);case"cohere_asr":return this._call_cohere_asr(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&ie.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&ie.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const r=!Array.isArray(e),s=r?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,a=await as(s,n),o=[];for(const i of a){const l=await this.processor(i),d=(await this.model(l)).logits[0],h=[];for(const p of d)h.push($e(p.data)[1]);const _=this.tokenizer.decode(h,{skip_special_tokens:!0}).trim();o.push({text:_})}return r?o[0]:o}async _call_whisper(e,t){const r=t.return_timestamps??!1,s=t.chunk_length_s??0,n=t.force_full_sequences??!1;let a=t.stride_length_s??null;const o={...t};r==="word"&&(o.return_token_timestamps=!0,o.return_timestamps=!0);const i=!Array.isArray(e),l=i?[e]:e,c=this.processor.feature_extractor.config,d=c.chunk_length/this.model.config.max_source_positions,h=c.hop_length,_=c.sampling_rate,p=await as(l,_),w=[];for(const v of p){let M=[];if(s>0){if(a===null)a=s/6;else if(s<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const A=_*s,E=_*a,C=A-2*E;let L=0;for(;;){const x=L+A,G=v.subarray(L,x),B=await this.processor(G),j=L===0,X=x>=v.length;if(M.push({stride:[G.length,j?0:E,X?0:E],input_features:B.input_features,is_last:X}),X)break;L+=C}}else M=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(const A of M){o.num_frames=Math.floor(A.stride[0]/h);const E=await this.model.generate({inputs:A.input_features,...o});if(r==="word"){const C=E.sequences.tolist()[0],L=E.token_timestamps.tolist()[0],x=this.tokenizer.timestamp_begin,G=Math.max(C.findIndex(B=>Number(B)>=x),0);A.tokens=C.slice(G),A.token_timestamps=L.slice(G).map(B=>qs(B,2))}else A.tokens=E[0].tolist();A.stride=A.stride.map(C=>C/_)}const[y,k]=this.tokenizer._decode_asr(M,{time_precision:d,return_timestamps:r,force_full_sequences:n});w.push({text:y,...k})}return i?w[0]:w}async _call_moonshine(e,t){const r=!Array.isArray(e),s=r?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,a=await as(s,n),o=[];for(const i of a){const l=await this.processor(i),c=Math.floor(i.length/n)*6,d=await this.model.generate({max_new_tokens:c,...t,...l}),h=this.processor.batch_decode(d,{skip_special_tokens:!0})[0];o.push({text:h})}return r?o[0]:o}async _call_cohere_asr(e,t){const r=!Array.isArray(e),s=r?[e]:e,n=this.processor.feature_extractor,a=n.config.sampling_rate,o=await as(s,a),i=t.language??"en",l=this.processor.get_decoder_prompt_ids(i),c=[];for(const d of o){const h=n.split_audio(d),_=[];for(const w of h){const v=await this.processor(w),M=await this.model.generate({...v,decoder_input_ids:l,...t}),y=this.tokenizer.decode(M[0].tolist(),{skip_special_tokens:!0}).trim();_.push(y)}const p=this.processor.constructor.join_chunks(_,i);c.push({text:p})}return r?c[0]:c}},MN=class extends Ge{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await we.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new V("float32",e,[e.length]);else if(!(e instanceof V))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw new Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,r,s=null){const n=t.data,[a,o]=t.dims,i=s?s.data:null,l=[];for(let c=0;c<a;++c){const d=i?Math.min(Math.ceil(i[c]),o):o,h=c*o;l.push(new mT(n.slice(h,h+d),r))}return Array.isArray(e)?l:l[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type==="supertonic"?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:r,speed:s}){if(!t)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:n,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),i=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,i),t=t.view(i,-1,a);const{waveform:l,durations:c}=await this.model.generate_speech({...o,style:t,num_inference_steps:r,speed:s});return this._postprocess_waveform(e,l,n,c)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(t),s=this.model.config.sampling_rate;return this._postprocess_waveform(e,r,s)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||(ie.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Ws.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),s=r.dims[0];t=await this._prepare_speaker_embeddings(t,s),t=t.view(s,-1);const{waveform:n}=await this.model.generate_speech(r,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,n,a)}},xN=class extends Ge{async _call(e,t={}){const r=Array.isArray(e),s=await Rt(e),{pixel_values:n}=await this.processor(s),a=[];for(const o of n){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]}},kN=class extends Ge{async _call(e,{top_k:t=5}={}){const r=await Rt(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s}),{id2label:a}=this.model.config,o=[];for(const i of n.logits){const l=await _s(new V("float32",rt(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]}},If={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},ow=class extends Ge{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:n=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 Rt(e),c=l.map(y=>[y.height,y.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 y=h[0];if(y in d)throw Error(`Input name ${y} already exists in the inputs.`);d[y]=d.pixel_values}const p=await this.model(d);let w=null;if(o!==null)w=If[o];else if(this.processor.image_processor){for(const[y,k]of Object.entries(If))if(k in this.processor.image_processor){w=this.processor.image_processor[k].bind(this.processor.image_processor),o=y;break}}const v=this.model.config.id2label,M=[];if(o)if(o==="panoptic"||o==="instance"){const y=w(p,t,r,s,n,a??c)[0],k=y.segmentation;for(const A of y.segments_info){const E=new Uint8ClampedArray(k.data.length);for(let L=0;L<k.data.length;++L)k.data[L]===A.id&&(E[L]=255);const C=new Ot(E,k.dims[1],k.dims[0],1);M.push({score:A.score,label:v[A.label_id],mask:C})}}else if(o==="semantic"){const{segmentation:y,labels:k}=w(p,a??c)[0];for(const A of k){const E=new Uint8ClampedArray(y.data.length);for(let L=0;L<y.data.length;++L)y.data[L]===A&&(E[L]=255);const C=new Ot(E,y.dims[1],y.dims[0],1);M.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 E=c[A],C=k[A];C.data.some(x=>x<-1e-5||x>1+1e-5)&&C.sigmoid_();const L=await Ot.fromTensor(C.mul_(255).to("uint8")).resize(E[1],E[0]);M.push({label:null,score:null,mask:L})}}return M}},TN=class extends ow{async _call(e,t={}){const r=await Rt(e),s=await super._call(e,t),n=r.map((a,o)=>{const i=a.clone();return i.putAlpha(s[o].mask),i});return Array.isArray(e)?n:n[0]}},EN=class extends Ge{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const s=Array.isArray(e),n=await Rt(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(n),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>rt(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 s?d:d[0]}},AN=class extends Ge{async _call(e,{threshold:t=.9,percentage:r=!1}={}){const s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await Rt(e),a=r?null:n.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(n),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:ii(p,!r)})));return s?h:h[0]}},CN=class extends Ge{async _call(e,t,{threshold:r=.1,top_k:s=null,percentage:n=!1}={}){const a=Array.isArray(e),o=await Rt(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],_=n?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 M=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];v=M.boxes.map((y,k)=>({score:M.scores[k],label:M.labels[k],box:ii(y,!n)}))}else{const M=this.processor.image_processor.post_process_object_detection(w,r,_,!0)[0];v=M.boxes.map((y,k)=>({score:M.scores[k],label:t[M.classes[k]],box:ii(y,!n)}))}v.sort((M,y)=>y.score-M.score),s!==null&&(v=v.slice(0,s)),c.push(v)}return a?c:c[0]}},SN=class extends Ge{_default_generation_config={max_new_tokens:256};async _call(e,t,r={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}const s=(await Rt(e))[0],{pixel_values:n}=await this.processor(s),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,i=await this.model.generate({inputs:n,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...r}),c=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/);let d=null;return c&&c.length>=2&&(d=c[1].trim()),[{answer:d}]}},PN=class extends Ge{async _call(e){const t=await Rt(e),r=await this.processor(t),s=await this.model(r),n=[];for(const a of s.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(Ot.fromTensor(o))}return Array.isArray(e)?n:n[0]}},FN=class extends Ge{async _call(e){const t=await Rt(e),r=await this.processor(t),{predicted_depth:s}=await this.model(r),n=[];for(let a=0;a<t.length;++a){const o=s[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,h=(await It(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=Ot.fromTensor(w);n.push({predicted_depth:h,depth:v})}return Array.isArray(e)?n:n[0]}},LN=class extends Ge{async _call(e,{pooling:t="none",normalize:r=!1,quantize:s=!1,precision:n="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)),s&&(i=sk(i,n)),i}},IN=class extends Ge{async _call(e,{pool:t=null}={}){const r=await Rt(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s});let a;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=n.pooler_output}else a=n.last_hidden_state??n.logits??n.image_embeds;return a}},sa=Object.freeze({"text-classification":{pipeline:cN,model:Cf,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:uN,model:WO,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:fN,model:KO,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:_N,model:JO,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:pN,model:$o,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:mN,model:$o,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Zc,model:$o,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:gN,model:YO,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:wN,model:Cf,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:vN,model:nN,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:yN,model:Ws,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:bN,model:[HO,sN],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:MN,model:[XO,QO],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:xN,model:ZO,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:kN,model:eN,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ow,model:[Sf,Pf,Ff],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:TN,model:[Sf,Pf,Ff],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:EN,model:Ws,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:AN,model:tN,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:CN,model:rN,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:SN,model:aN,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:PN,model:oN,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:FN,model:iN,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:LN,model:Ws,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:IN,model:[lN,Ws],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),iw=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ON(e){if(!e)throw new Error("modelId is required");return(await sn(e,Ks,{})).exists?[Ks]:[]}async function NN(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await nm(e,{config:t,dtype:r,device:s,model_file_name:n});if(a){const l=await cp(e);i.push(...l)}if(o){const l=await ON(e);i.push(...l)}return i}async function DN(e,t,r={}){e=iw[e]??e;const s=sa[e];if(!s)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(sa).join(", ")}]`);const{type:n}=s,i=await NN(t,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){const l=await sm(t,r),c=rm(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 zN(e,t=null,{progress_callback:r=null,config:s=null,cache_dir:n=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=iw[e]??e;const p=sa[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(sa)}]`);t||(t=p.default.model,ie.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype&&(l=p.default.dtype));const w=await DN(e,t,{device:i,dtype:l});let v={};r&&(await Promise.all(w.map(async X=>sn(t,X)))).forEach((X,W)=>{X.exists&&(v[w[W]]={loaded:0,total:X.size??0})});const M={progress_callback:r?new Qo(r,v):void 0,config:s,cache_dir:n,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:h,session_options:_},y=w.includes("tokenizer.json"),k=w.includes("preprocessor_config.json"),A=p.model;let E;if(Array.isArray(A)){const j=s??await Zs.from_pretrained(t,M),{model_type:X}=j,W=A.find(N=>N.supports(X));if(!W)throw Error(`Unsupported model type "${X}" for task "${e}". None of the candidate model classes support this type.`);E=W.from_pretrained(t,{...M,config:j})}else E=A.from_pretrained(t,M);const[C,L,x]=await Promise.all([y?Te.from_pretrained(t,M):null,k?w2.from_pretrained(t,M):null,E]),G={task:e,model:x};C&&(G.tokenizer=C),L&&(G.processor=L),yr(r,{status:"ready",task:e,model:t});const B=p.pipeline;return new B(G)}de.IS_PROCESS_AVAILABLE;we.allowLocalModels=!1;const BN="onnx-community/whisper-tiny.en",Un=self;let Vo=null,Of=null;function RN(){return Vo?Promise.resolve(Vo):(Of??=zN("automatic-speech-recognition",BN,{device:"wasm",session_options:{graphOptimizationLevel:"basic"},progress_callback:e=>{e.status==="progress"&&Un.postMessage({type:"loading",progress:e.progress??null})}}).then(e=>(Vo=e,e)),Of)}Un.onmessage=async e=>{const t=e.data;if(!(!t||t.type!=="transcribe"||!(t.audio instanceof Float32Array)))try{const s=await(await RN())(t.audio);Un.postMessage({type:"result",text:s.text.trim()})}catch(r){Un.postMessage({type:"error",message:r instanceof Error?r.message:String(r)})}};
|