murmur-rag 1.0.0 → 1.2.0
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 +27 -23
- package/dist/cdn/anthropic-ynz7717b.js +2 -0
- package/dist/cdn/chunk-hpx6rpea.js +1 -0
- package/dist/cdn/{embed-59r4jck6.js → embed-0m8xctqy.js} +3 -3
- package/dist/cdn/{embed-pnm9593k.js → embed-7pk91zq8.js} +2 -2
- package/dist/cdn/embed-dbkjhg16.js +83 -0
- package/dist/cdn/{embed-q6y6vgv1.js → embed-krrjjyf5.js} +4 -4
- package/dist/cdn/embed-n5nzhrf2.js +9 -0
- package/dist/cdn/{embed-hn0r8fmg.js → embed-rp9gb1qq.js} +2 -2
- package/dist/cdn/embed-xtkxyrpe.js +44 -0
- package/dist/cdn/google-k5kwa54v.js +14 -0
- package/dist/cdn/index-db4ne93m.js +1 -0
- package/dist/cdn/index-gyd02jvt.js +9 -0
- package/dist/cdn/index-qc8kgsdt.js +1 -0
- package/dist/cdn/index-t0qn2m4r.js +1 -0
- package/dist/cdn/index-y0faj89r.js +1 -0
- package/dist/cdn/mistral-p2qcnn42.js +3 -0
- package/dist/cdn/murmur-d6t6cjc7.js +5 -0
- package/dist/cdn/murmur.js +24 -5
- package/dist/cdn/openai-compatible-psnkrpxy.js +11 -0
- package/dist/cdn/openai-d3q1d6cz.js +18 -0
- package/dist/cdn/retriever-6qvn2maq.js +1 -0
- package/dist/cdn/transformers.web-xn16v7pz.js +46 -0
- package/dist/cli.js +2 -0
- package/dist/lib/chunks/{index-ynjdey8j.js → index-8h9c8ekq.js} +4 -2
- package/dist/lib/chunks/{index-6re28wc1.js → index-b77xqap3.js} +13 -1
- package/dist/lib/chunks/{index-10g918kt.js → index-p86sy3y4.js} +1 -1
- package/dist/lib/chunks/{index-4at214g0.js → index-y3v46yjp.js} +314 -27
- package/dist/lib/chunks/{murmur-c1c79eh8.js → murmur-t36hd4vt.js} +2 -2
- package/dist/lib/chunks/{retriever-h8nz6jsc.js → retriever-wxshtnm0.js} +1 -1
- package/dist/lib/embed.js +4 -2
- package/dist/lib/index.js +5 -3
- package/dist/lib/indexer/index.js +2 -0
- package/dist/lib/local/index.js +163 -0
- package/dist/lib/rag/index.js +13 -11
- package/dist/lib/widget/index.js +2 -2
- package/dist/types/local/index.d.ts +56 -0
- package/dist/types/rag/ground.d.ts +7 -0
- package/dist/types/rag/index.d.ts +1 -1
- package/dist/types/widget/element.d.ts +3 -0
- package/dist/types/widget/i18n.d.ts +14 -0
- package/dist/types/widget/session.d.ts +32 -1
- package/dist/types/widget/styles.d.ts +1 -1
- package/package.json +17 -3
- package/dist/cdn/anthropic-w7nkjk5e.js +0 -2
- package/dist/cdn/chunk-e0j28zmb.js +0 -1
- package/dist/cdn/embed-2xm309sb.js +0 -7
- package/dist/cdn/embed-n7jskdxd.js +0 -44
- package/dist/cdn/embed-sgjh2kg2.js +0 -83
- package/dist/cdn/google-qha5xyx4.js +0 -14
- package/dist/cdn/index-11c9cspb.js +0 -1
- package/dist/cdn/index-e5entetm.js +0 -1
- package/dist/cdn/index-hv290nbv.js +0 -9
- package/dist/cdn/index-kk9hgxdc.js +0 -1
- package/dist/cdn/mistral-16bekg8b.js +0 -3
- package/dist/cdn/murmur-bnm335nb.js +0 -5
- package/dist/cdn/openai-compatible-za7hc1fv.js +0 -11
- package/dist/cdn/openai-dhy4fp4c.js +0 -18
- package/dist/cdn/retriever-m8peqj5t.js +0 -1
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import{Ct,It}from"./embed-n5nzhrf2.js";var _i={};Ct(_i,{InferenceSession:()=>Zo,TRACE:()=>Xs,TRACE_EVENT_BEGIN:()=>kr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>Hr,TRACE_FUNC_END:()=>Qr,Tensor:()=>Nt,default:()=>uM,env:()=>Be,registerBackend:()=>qr});/*!
|
|
2
|
+
* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0
|
|
3
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
4
|
+
* Licensed under the MIT License.
|
|
5
|
+
*/var{defineProperty:Ko,getOwnPropertyDescriptor:D0,getOwnPropertyNames:z0}=Object,B0=Object.prototype.hasOwnProperty,R0=((e)=>It)(function(e){return It.apply(this,arguments)}),we=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}},ns=(e,t)=>{for(var r in t)Ko(e,r,{get:t[r],enumerable:!0})},$0=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of z0(t))!B0.call(e,s)&&s!==r&&Ko(e,s,{get:()=>t[s],enumerable:!(n=D0(t,s))||n.enumerable});return e},Qs=(e)=>$0(Ko({},"__esModule",{value:!0}),e),Yn,br,qr,Qf,Mh,xh=we(()=>{Yn=new Map,br=[],qr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=Yn.get(e);if(n===void 0)Yn.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=br.indexOf(e);s!==-1&&br.splice(s,1);for(let a=0;a<br.length;a++)if(Yn.get(br[a]).priority<=r){br.splice(a,0,e);return}br.push(e)}return}throw TypeError("not a valid backend")},Qf=async(e)=>{let t=Yn.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Mh=async(e)=>{let t=e.executionProviders||[],r=t.map((l)=>typeof l=="string"?l:l.name),n=r.length===0?br:r,s,a=[],o=new Set;for(let l of n){let c=await Qf(l);typeof c=="string"?a.push({name:l,err:c}):(s||(s=c),s===c&&o.add(l))}if(!s)throw Error(`no available backend found. ERR: ${a.map((l)=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter((l)=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),G0=we(()=>{xh()}),kh,V0=we(()=>{kh="1.31.0-dev.20260911-2a43ec07e"}),Eo,Ze,Th=we(()=>{V0(),Eo="warning",Ze={wasm:{},webgl:{},webgpu:{},versions:{common:kh},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Eo=e}},get logLevel(){return Eo}},Object.defineProperty(Ze,"logLevel",{enumerable:!0})}),Be,U0=we(()=>{Th(),Be=Ze}),Eh,Ah,j0=we(()=>{Eh=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*s,f=0,_=d,p=d*2,w=-1;o==="RGBA"?(f=0,_=d,p=d*2,w=d*3):o==="RGB"?(f=0,_=d,p=d*2):o==="RBG"&&(f=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<s;y++){let b=(e.data[f++]-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];n.fillStyle="rgba("+b+","+k+","+A+","+E+")",n.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw Error("toDataURL is not supported")}else throw Error("Can not access image data")},Ah=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,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 f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw Error("Tensor format doesn't match input tensor dims");let _=4,p=0,w=1,v=2,y=3,b=0,k=f,A=f*2,E=-1;i==="RGBA"?(b=0,k=f,A=f*2,E=f*3):i==="RGB"?(b=0,k=f,A=f*2):i==="RBG"&&(b=0,A=f,k=f*2),n=r.createImageData(s,a);for(let C=0;C<a*s;p+=_,w+=_,v+=_,y+=_,C++)n.data[p]=(e.data[b++]-d[0])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[y]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw Error("Can not access image data");return n}}),Vs,Ch,Sh,Ph,Fh,Ih,W0=we(()=>{Jo(),Vs=(e,t)=>{if(e===void 0)throw Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,p=1,w=2,v=3,y=0,b=c,k=c*2,A=-1;i==="RGB"&&(f=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,k=c,b=c*2):l==="BGR"&&(k=0,b=c,y=c*2);for(let E=0;E<c;E++,_+=f,w+=f,p+=f,v+=f)d[y++]=(e[_]+o[0])/a[0],d[b++]=(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 bt("float32",d,[1,4,r,n]):new bt("float32",d,[1,3,r,n])},Ch=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw 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 f=c(d);if(f!=null){let{height:_,width:p}=e;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 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;f.drawImage(e,0,0),o=f.getImageData(0,0,p,_).data}else throw Error("Can not access image data")}else if(n){let d,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,f=t.resizedWidth):(d=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=f,t!==void 0){let _=l();_.width=f,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,f,d).data;else throw Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let f=c(d);if(f!=null){let{height:_,width:p}=e;return f.drawImage(e,0,0,p,_),o=f.getImageData(0,0,p,_).data,i.height=_,i.width=p,Vs(o,i)}else throw Error("Can not access image data")}else{if(a)return new Promise((d,f)=>{let _=l(),p=c(_);if(!e||!p)return f();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(Vs(v.data,i))}});throw Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Vs(o,i);throw Error("Input data provided is not supported - aborted tensor creation")},Sh=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t;return new bt({location:"texture",type:"float32",texture:e,dims:[1,n,r,4],download:s,dispose:a})},Ph=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},Fh=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},Ih=(e,t,r)=>new bt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),jr,ts,Ao,Lh,q0=we(()=>{jr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ts=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ao=!1,Lh=()=>{if(!Ao){Ao=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(jr.set("int64",BigInt64Array),ts.set(BigInt64Array,"int64")),t&&(jr.set("uint64",BigUint64Array),ts.set(BigUint64Array,"uint64")),n?(jr.set("float16",r),ts.set(r,"float16")):jr.set("float16",Uint16Array)}}}),Oh,Nh,H0=we(()=>{Jo(),Oh=(e)=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},Nh=(e,t)=>{switch(e.location){case"cpu":return new bt(e.type,e.data,t);case"cpu-pinned":return new bt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new bt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new bt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new bt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),bt,Jo=we(()=>{j0(),W0(),q0(),H0(),bt=class{constructor(e,t,r){Lh();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let o=jr.get(n);if(!o)throw TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e=="string")if(n=e,i=r,e==="string"){if(!Array.isArray(t))throw TypeError("A string tensor's data must be a string array.");o=t}else{let l=jr.get(e);if(l===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw 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 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 TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",o=e;else if(l==="boolean")n="bool",o=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let l=ts.get(e.constructor);if(l===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw TypeError("A tensor's dims must be a number array");s=i,this.cpuData=o,this.dataLocation="cpu"}let a=Oh(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Ch(e,t)}static fromTexture(e,t){return Sh(e,t)}static fromGpuBuffer(e,t){return Ph(e,t)}static fromMLTensor(e,t){return Fh(e,t)}static fromPinnedBuffer(e,t,r){return Ih(e,t,r)}toDataURL(e){return Eh(this,e)}toImageData(e){return Ah(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw 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 Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw 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 Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw 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 Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return Nh(this,e)}}}),Nt,Dh=we(()=>{Jo(),Nt=bt}),Xs,Co,Hr,Qr,kr,Tr,zh=we(()=>{Th(),Xs=(e,t)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.timeStamp(`${e}::ORT::${t}`)},Co=(e,t)=>{let r=Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s<r.length;s++){if(n&&!r[s].includes("TRACE_FUNC")){let a=`FUNC_${e}::${r[s].trim().split(" ")[1]}`;t&&(a+=`::${t}`),Xs("CPU",a);return}r[s].includes("TRACE_FUNC")&&(n=!0)}},Hr=(e)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||Co("BEGIN",e)},Qr=(e)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||Co("END",e)},kr=(e)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.time(`ORT::${e}`)},Tr=(e)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.timeEnd(`ORT::${e}`)}}),Bh,Q0=we(()=>{xh(),Dh(),zh(),Bh=class e{constructor(t){this.handler=t}async run(t,r,n){Hr(),kr("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Nt||Array.isArray(t))throw 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 TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Nt)throw TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw TypeError("'fetches' cannot be an empty array.");o=!1;for(let c of r){if(typeof c!="string")throw TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(d.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof Nt)&&(c=!0,o=!1,s[f]=_)}if(c){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)s[c]=null;let i=await this.handler.run(t,s,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof Nt?l[c]=d:l[c]=new Nt(d.type,d.data,d.dims)}return Tr("InferenceSession.run"),Qr(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Hr(),kr("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 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 TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,f=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw RangeError("'byteOffset' must be an integer.");if(f<0||f>=d.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-f,typeof n=="number"){if(_=n,!Number.isSafeInteger(_))throw RangeError("'byteLength' must be an integer.");if(_<=0||f+_>d.byteLength)throw RangeError(`'byteLength' is out of range (0, ${d.byteLength-f}].`);if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw TypeError("'options' must be an object.")}else if(typeof n<"u")throw TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw TypeError("'options' must be an object.");a=new Uint8Array(d,f,_)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Mh(o),c=await i.createInferenceSessionHandler(a,l);return Tr("InferenceSession.create"),Qr(),new e(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}}}),Zo,X0=we(()=>{Q0(),Zo=Bh}),Y0=we(()=>{}),K0=we(()=>{}),J0=we(()=>{}),Z0=we(()=>{}),Rh={};ns(Rh,{InferenceSession:()=>Zo,TRACE:()=>Xs,TRACE_EVENT_BEGIN:()=>kr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>Hr,TRACE_FUNC_END:()=>Qr,Tensor:()=>Nt,env:()=>Be,registerBackend:()=>qr});var Xr=we(()=>{G0(),U0(),X0(),Dh(),Y0(),K0(),zh(),J0(),Z0()}),ei=we(()=>{}),$h={};ns($h,{default:()=>Gh});var So,Po,Gh,eM=we(()=>{r_(),Yr(),ti(),So="ort-wasm-proxy-worker",Po=globalThis.self?.name===So,Po&&(self.onmessage=(e)=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":ri(r.wasm).then(()=>{ii(r).then(()=>{postMessage({type:t})},(n)=>{postMessage({type:t,err:n})})},(n)=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;li(s,n).then(()=>{postMessage({type:t})},(a)=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=Js(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;ci(n,s).then((a)=>{postMessage({type:t,out:a})},(a)=>{postMessage({type:t,err:a})});break}case"release":ui(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;di(n,s,a,o,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},hi([...a,...l]))},(l)=>{postMessage({type:t,err:l})});break}case"end-profiling":fi(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),Gh=Po?null:(e)=>new Worker(e??vt,{type:"module",name:So})}),Vh={};ns(Vh,{default:()=>Uh});async function Xf(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(u,h)=>{u.startsWith("./")&&(u=u.substring(2)),(t.ed||(t.ed=new Map)).set(u,h)},t.unmountExternalData=()=>{delete t.ed,delete t.Te,delete t.Se,delete t.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let u=(h)=>(...m)=>{let g=Kt;return m=h(...m),Kt!=g?new Promise((x,T)=>{io={resolve:x,reject:T}}):m};(()=>{for(let h of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[h]=u(t[h])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,i,l=(u,h)=>{throw h},c=import.meta.url,d="";if(r||n){try{d=new URL(".",c).href}catch{}n&&(i=(u)=>{var h=new XMLHttpRequest;return h.open("GET",u,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),o=async(u)=>{if(N(u))return new Promise((m,g)=>{var x=new XMLHttpRequest;x.open("GET",u,!0),x.responseType="arraybuffer",x.onload=()=>{x.status==200||x.status==0&&x.response?m(x.response):g(x.status)},x.onerror=g,x.send(null)});var h=await fetch(u,{credentials:"same-origin"});if(h.ok)return h.arrayBuffer();throw Error(h.status+" : "+h.url)}}var f,_,p,w,v,y,b=console.log.bind(console),k=console.error.bind(console),A=b,E=k,C=!1,N=(u)=>u.startsWith("file://");function M(){vr.buffer!=q.buffer&&V()}if(s){let u=function(h){try{var m=h.data,g=m.$c;if(g==="load"){let x=[];self.onmessage=(T)=>x.push(T),y=()=>{postMessage({$c:"loaded"});for(let T of x)u(T);self.onmessage=u};for(let T of m.ue)t[T]&&!t[T].proxy||(t[T]=(...F)=>{postMessage({$c:"callHandler",te:T,args:F})},T=="print"&&(A=t[T]),T=="printErr"&&(E=t[T]));vr=m.Me,V(),_=m.Ne,Fe(),Gs()}else if(g==="run"){(function(x){var T=(M(),P)[x+52>>>2>>>0];x=(M(),P)[x+56>>>2>>>0],tf(T,T-x),re(T)})(m.Xc),yo(m.Xc,0,0,1,0,0),Nu(),so(m.Xc),R||(Dd(),R=!0);try{Ev(m.ze,m.kd)}catch(x){if(x!="unwind")throw x}}else m.target!=="setimmediate"&&(g==="checkMailbox"?R&&Fs():g&&(E(`worker: received unknown command ${g}`),E(m)))}catch(x){throw Yd(),x}};var G=u,R=!1;self.onunhandledrejection=(h)=>{throw h.reason||h},self.onmessage=u}var q,X,Q,H,B,P,Y,ue,Z,se,L,O=!1;function V(){var u=vr.buffer;t.HEAP8=q=new Int8Array(u),Q=new Int16Array(u),t.HEAPU8=X=new Uint8Array(u),H=new Uint16Array(u),t.HEAP32=B=new Int32Array(u),t.HEAPU32=P=new Uint32Array(u),Y=new Float32Array(u),ue=new Float64Array(u),Z=new BigInt64Array(u),se=new BigUint64Array(u)}function de(){O=!0,s?y():dr.hc()}function te(u){throw E(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v?.(u),u}function We(){return{a:{qa:Yb,f:Av,K:Cv,k:Sv,p:Pv,l:Fv,fa:Iv,b:Lv,da:Ov,gc:Gu,q:Nv,ea:Wu,Ua:qu,cc:Hu,ec:Qu,Va:Xu,Sa:Yu,La:Ku,Ra:Ju,oa:Zu,dc:ed,ac:td,Ta:rd,bc:nd,_a:Dv,Ba:Bv,Xb:Rv,Vb:Gv,Aa:Uv,O:jv,J:Wv,Wb:qv,ka:Zv,Yb:ey,Oa:ty,_b:ny,Ea:sy,Tb:ay,Ca:oy,Na:so,Xa:iy,U:dy,n:my,c:ro,qb:gy,w:wy,N:vy,A:yy,j:by,o:dd,rb:My,H:xy,T:ky,g:Ty,u:Ey,m:Ay,i:Cy,Ia:Sy,Ja:Py,Ka:Fy,Ga:pd,Ha:md,Ub:gd,ab:Ly,Za:Dy,Z:zy,pb:By,Da:Ry,Ya:Oy,X:$y,Wa:Gy,$b:Vy,G:Iy,db:Uy,_:jy,pa:Ds,Zb:qy,cb:Wy,bb:Hy,lb:ob,z:ib,sa:lb,ra:cb,nb:ub,Y:db,v:fb,kb:hb,jb:_b,ib:pb,mb,gb,fb:wb,eb:vb,Pa:Cd,Qa:Sd,fc:Ja,W:Pd,Fa:Fd,ma:Id,Ma:Ld,la:Od,Fb:O0,va:C0,Gb:L0,wa:A0,E:_0,e:e0,r:Jb,x:Kb,C:u0,Ib:k0,ca:x0,D:n0,xa:T0,aa:S0,ha:M0,Jb:b0,Kb:y0,za:m0,Lb:w0,ya:v0,Mb:g0,ua:I0,ba:E0,d:Zb,B:r0,s:t0,Eb:N0,t:a0,y:f0,F:s0,I:o0,L:h0,Nb:p0,R:P0,ia:c0,$:F0,Pb:l0,Rb:i0,Ob:d0,h:bb,a:vr,$a:sn,Hb:Mb,V:xb,M:kb,na:Tb,Db:Eb,ja:Ab,S:Cb,Ab:Sb,Bb:Pb,vb:Fb,wb:Ib,P:Lb,xb:Ob,yb:Nb,ta:Db,Sb:zb,ob:Bb,Q:Rb,hb:$b,Cb:Gb,sb:Vb,tb:jb,ub:Wb,ga:qb,zb:Hb,Qb}}}async function Fe(){function u(g,x){var T=dr=g.exports;g={};for(let[F,S]of Object.entries(T))typeof S=="function"?(T=ly(S),g[F]=T):g[F]=S;return dr=g,dr=function(){var F=dr,S=(j)=>(he)=>j(he)>>>0,D=(j)=>()=>j()>>>0;return(F=Object.assign({},F)).ic=S(F.ic),F.Nc=D(F.Nc),F.Pc=S(F.Pc),F.Bd=((j)=>(he,me)=>j(he,me)>>>0)(F.Bd),F.Gd=S(F.Gd),F.Hd=D(F.Hd),F.Ld=S(F.Ld),F}(),Lu.push(dr.sd),Nd=(g=dr).ic,Dd=g.jc,t._OrtInit=g.kc,t._OrtGetLastError=g.lc,t._OrtCreateSessionOptions=g.mc,t._OrtAppendExecutionProvider=g.nc,t._OrtAddFreeDimensionOverride=g.oc,t._OrtAddSessionConfigEntry=g.pc,t._OrtReleaseSessionOptions=g.qc,t._OrtCreateSession=g.rc,t._OrtReleaseSession=g.sc,t._OrtGetInputOutputCount=g.tc,t._OrtGetInputOutputMetadata=g.uc,t._OrtFree=g.vc,t._OrtCreateTensor=g.wc,t._OrtGetTensorData=g.xc,t._OrtReleaseTensor=g.yc,t._OrtCreateRunOptions=g.zc,t._OrtAddRunConfigEntry=g.Ac,t._OrtReleaseRunOptions=g.Bc,t._OrtCreateBinding=g.Cc,t._OrtBindInput=g.Dc,t._OrtBindOutput=g.Ec,t._OrtClearBoundOutputs=g.Fc,t._OrtReleaseBinding=g.Gc,t._OrtRunWithBinding=g.Hc,t._OrtRun=g.Ic,t._OrtEndProfiling=g.Jc,zd=t._OrtCreateWebGpuInstance=g.Kc,t._wgpuCreateInstance=g.Lc,_o=t._OrtGetWebGpuDevice=g.Mc,Rs=g.Nc,Et=t._free=g.Oc,Rr=t._malloc=g.Pc,Bd=t._wgpuBufferRelease=g.Qc,Rd=g.Rc,$d=g.Sc,Gd=g.Tc,Vd=g.Uc,Ud=g.Vc,jd=g.Yc,Wd=g.Zc,qd=g.hd,Hd=g.id,Qd=g.jd,po=g.ld,mo=g.md,go=g.nd,wo=g.od,Qn=g.pd,vo=g.qd,Xd=g.rd,yo=g.ud,Yd=g.vd,Kd=g.wd,Jd=g.xd,bo=g.yd,Zd=g.zd,ef=g.Ad,Mo=g.Bd,_e=g.Cd,Xn=g.Dd,tf=g.Ed,re=g.Fd,$s=g.Gd,ne=g.Hd,rf=g.Id,xo=g.Jd,nf=g.Kd,sf=g.Ld,af=g.Md,ko=g.Nd,of=g.Od,lf=g.Pd,cf=g.Qd,uf=g.Rd,df=g.Sd,ff=g.Td,hf=g.Ud,_f=g.Vd,pf=g.Wd,mf=g.Xd,gf=g.Yd,wf=g.Zd,vf=g._d,yf=g.$d,bf=g.ae,Mf=g.be,xf=g.ce,kf=g.de,Tf=g.fe,Ef=g.ge,Af=g.he,Cf=g.ie,Sf=g.je,Pf=g.ke,Ff=g.le,If=g.me,Lf=g.Ae,Of=g.Be,Nf=g.Ce,Df=g.De,zf=g.Ee,Bf=g.Fe,Rf=g.Ge,$f=g.He,Gf=g.Ie,Vf=g.Je,Uf=g.Ke,jf=g.nf,Wf=g.of,qf=g.pf,Hf=g.qf,_=x,dr}var h,m=We();return t.instantiateWasm?new Promise((g)=>{t.instantiateWasm(m,(x,T)=>{g(u(x,T))})}):s?u(new WebAssembly.Instance(_,We()),_):(L??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,h=await async function(g){var x=L;if(!f&&!N(x))try{var T=fetch(x,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(F){E(`wasm streaming compile failed: ${F}`),E("falling back to ArrayBuffer instantiation")}return async function(F,S){try{var D=await async function(j){if(!f)try{var he=await o(j);return new Uint8Array(he)}catch{}if(j==L&&f)j=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";j=i(j)}return j}(F);return await WebAssembly.instantiate(D,S)}catch(j){E(`failed to asynchronously prepare wasm: ${j}`),te(j)}}(x,g)}(m),u(h.instance,h.module))}class be{name="ExitStatus";constructor(u){this.message=`Program terminated with exit(${u})`,this.status=u}}var Ge=(u)=>{u.terminate(),u.onmessage=()=>{}},Oe=[],Me=0,Ye=null,Xt=(u)=>{wr.length==0&&(zu(),Du(wr[0]));var h=wr.pop();if(!h)return 6;qn.push(h),Dr[u.Xc]=h,h.Xc=u.Xc;var m={$c:"run",ze:u.ye,kd:u.kd,Xc:u.Xc};return h.postMessage(m,u.oe),0},xe=0,Ie=(u,h,...m)=>{var g,x=16*m.length,T=ne(),F=$s(x),S=F>>>3;for(g of m)typeof g=="bigint"?((M(),Z)[S++>>>0]=1n,(M(),Z)[S++>>>0]=g):((M(),Z)[S++>>>0]=0n,(M(),ue)[S++>>>0]=g);return u=Kd(u,0,x,F,h),re(T),u};function sn(u){if(s)return Ie(0,1,u);if(p=u,!(0<xe)){for(var h of qn)Ge(h);for(h of wr)Ge(h);wr=[],qn=[],Dr={},C=!0}l(0,new be(u))}function Wn(u){if(s)return Ie(1,0,u);Ja(u)}var Ja=(u)=>{if(p=u,s)throw Wn(u),"unwind";sn(u)},wr=[],qn=[],Lu=[],Dr={},Ou=(u)=>{var h=u.Xc;delete Dr[h],wr.push(u),qn.splice(qn.indexOf(u),1),u.Xc=0,Jd(h)};function Nu(){Lu.forEach((u)=>u())}var Du=(u)=>new Promise((h)=>{u.onmessage=(x)=>{var T=x.data;if(x=T.$c,T.gd&&T.gd!=Rs()){var F=Dr[T.gd];F?F.postMessage(T,T.oe):E(`Internal error! Worker sent a message "${x}" to target pthread ${T.gd}, but that thread no longer exists!`)}else x==="checkMailbox"?Fs():x==="spawnThread"?Xt(T):x==="cleanupThread"?ht(()=>{Ou(Dr[T.Le])}):x==="loaded"?(u.loaded=!0,h(u)):T.target==="setimmediate"?u.postMessage(T):x==="uncaughtException"?u.onerror(T.error):x==="callHandler"?t[T.te](...T.args):x&&E(`worker sent an unknown command ${x}`)},u.onerror=(x)=>{throw E(`worker sent an error! ${x.filename}:${x.lineno}: ${x.message}`),x};var m,g=[];for(m of[])t.propertyIsEnumerable(m)&&g.push(m);u.postMessage({$c:"load",ue:g,Me:vr,Ne:_})});function zu(){var u=new Worker((()=>{let h=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new h("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});wr.push(u)}var vr,Ev=(u,h)=>{xe=0,u=ko(u,h),0<xe?p=u:bo(u)},Cs=[],Ss=0,tt=(u)=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function Av(u){var h=new Ps(u>>>=0);return(M(),q)[h.ad+12>>>0]==0&&(Bu(h,!0),Ss--),Ru(h,!1),Cs.push(h),sf(u)}var an=0,Cv=()=>{_e(0,0);var u=Cs.pop();rf(u.td),an=0};function Bu(u,h){h=h?1:0,(M(),q)[u.ad+12>>>0]=h}function Ru(u,h){h=h?1:0,(M(),q)[u.ad+13>>>0]=h}class Ps{constructor(u){this.td=u,this.ad=u-24}}var Za=(u)=>{var h=an;if(!h)return Xn(0),0;var m=new Ps(h);(M(),P)[m.ad+16>>>2>>>0]=h;var g=(M(),P)[m.ad+4>>>2>>>0];if(!g)return Xn(0),h;for(var x of u){if(x===0||x===g)break;if(nf(x,g,m.ad+16))return Xn(x),h}return Xn(g),h};function Sv(){return Za([])}function Pv(u){return Za([u>>>0])}function Fv(u,h,m,g){return Za([u>>>0,h>>>0,m>>>0,g>>>0])}var Iv=()=>{var u=Cs.pop();u||te("no exception to throw");var h=u.td;throw(M(),q)[u.ad+13>>>0]==0&&(Cs.push(u),Ru(u,!0),Bu(u,!1),Ss++),xo(h),an=h};function Lv(u,h,m){var g=new Ps(u>>>=0);throw h>>>=0,m>>>=0,(M(),P)[g.ad+16>>>2>>>0]=0,(M(),P)[g.ad+4>>>2>>>0]=h,(M(),P)[g.ad+8>>>2>>>0]=m,xo(u),Ss++,an=u}var Ov=()=>Ss;function $u(u,h,m,g){return s?Ie(2,1,u,h,m,g):Gu(u,h,m,g)}function Gu(u,h,m,g){if(u>>>=0,h>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var x=[];return s&&x.length===0?$u(u,h,m,g):(u={ye:m,Xc:u,kd:g,oe:x},s?(u.$c="spawnThread",postMessage(u,x),0):Xt(u))}function Nv(u){throw an||=u>>>0,an}var Vu=globalThis.TextDecoder&&new TextDecoder,Uu=(u,h,m,g)=>{if(m=h+m,g)return m;for(;u[h]&&!(h>=m);)++h;return h},ju=(u,h=0,m,g)=>{if(16<(m=Uu(u,h>>>=0,m,g))-h&&u.buffer&&Vu)return Vu.decode(u.buffer instanceof ArrayBuffer?u.subarray(h,m):u.slice(h,m));for(g="";h<m;){var x=u[h++];if(128&x){var T=63&u[h++];if((224&x)==192)g+=String.fromCharCode((31&x)<<6|T);else{var F=63&u[h++];65536>(x=(240&x)==224?(15&x)<<12|T<<6|F:(7&x)<<18|T<<12|F<<6|63&u[h++])?g+=String.fromCharCode(x):(x-=65536,g+=String.fromCharCode(55296|x>>10,56320|1023&x))}}else g+=String.fromCharCode(x)}return g},on=(u,h,m)=>(u>>>=0)?ju((M(),X),u,h,m):"";function Wu(u,h,m){return s?Ie(3,1,u,h,m):0}function qu(u,h){if(s)return Ie(4,1,u,h)}function Hu(u,h){if(s)return Ie(5,1,u,h)}function Qu(u,h,m){if(s)return Ie(6,1,u,h,m)}function Xu(u,h,m){return s?Ie(7,1,u,h,m):0}function Yu(u,h){if(s)return Ie(8,1,u,h)}function Ku(u,h,m){if(s)return Ie(9,1,u,h,m)}function Ju(u,h,m,g){if(s)return Ie(10,1,u,h,m,g)}function Zu(u,h,m,g){if(s)return Ie(11,1,u,h,m,g)}function ed(u,h,m,g){if(s)return Ie(12,1,u,h,m,g)}function td(u){if(s)return Ie(13,1,u)}function rd(u,h){if(s)return Ie(14,1,u,h)}function nd(u,h,m){if(s)return Ie(15,1,u,h,m)}var Dv=()=>te(""),Yt=(u)=>{u>>>=0;for(var h="";;){var m=(M(),X)[u++>>>0];if(!m)return h;h+=String.fromCharCode(m)}},eo={},to={},zv={},ln=class extends Error{constructor(u){super(u),this.name="BindingError"}};function ir(u,h,m={}){return function(g,x,T={}){var F=x.name;if(!g)throw new ln(`type "${F}" must have a positive integer typeid pointer`);if(to.hasOwnProperty(g)){if(T.ve)return;throw new ln(`Cannot register type '${F}' twice`)}to[g]=x,delete zv[g],eo.hasOwnProperty(g)&&(x=eo[g],delete eo[g],x.forEach((S)=>S()))}(u,h,m)}var sd=(u,h,m)=>{switch(h){case 1:return m?(g)=>(M(),q)[g>>>0]:(g)=>(M(),X)[g>>>0];case 2:return m?(g)=>(M(),Q)[g>>>1>>>0]:(g)=>(M(),H)[g>>>1>>>0];case 4:return m?(g)=>(M(),B)[g>>>2>>>0]:(g)=>(M(),P)[g>>>2>>>0];case 8:return m?(g)=>(M(),Z)[g>>>3>>>0]:(g)=>(M(),se)[g>>>3>>>0];default:throw TypeError(`invalid integer width (${h}): ${u}`)}};function Bv(u,h,m,g,x){u>>>=0,m>>>=0,h=Yt(h>>>0);let T=(F)=>F;if(g=g===0n){let F=8*m;T=(S)=>BigInt.asUintN(F,S),x=T(x)}ir(u,{name:h,Wc:T,cd:(F,S)=>(typeof S=="number"&&(S=BigInt(S)),S),bd:sd(h,m,!g),dd:null})}function Rv(u,h,m,g){ir(u>>>=0,{name:h=Yt(h>>>0),Wc:function(x){return!!x},cd:function(x,T){return T?m:g},bd:function(x){return this.Wc((M(),X)[x>>>0])},dd:null})}var ad=[],zr=[0,1,,1,null,1,!0,1,!1,1];function ro(u){9<(u>>>=0)&&--zr[u+1]===0&&(zr[u]=void 0,ad.push(u))}var Tt=(u)=>{if(!u)throw new ln(`Cannot use deleted val. handle = ${u}`);return zr[u]},Lt=(u)=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=ad.pop()||zr.length;return zr[h]=u,zr[h+1]=1,h}};function no(u){return this.Wc((M(),P)[u>>>2>>>0])}var $v={name:"emscripten::val",Wc:(u)=>{var h=Tt(u);return ro(u),h},cd:(u,h)=>Lt(h),bd:no,dd:null};function Gv(u){return ir(u>>>0,$v)}var Vv=(u,h)=>{switch(h){case 4:return function(m){return this.Wc((M(),Y)[m>>>2>>>0])};case 8:return function(m){return this.Wc((M(),ue)[m>>>3>>>0])};default:throw TypeError(`invalid float width (${h}): ${u}`)}};function Uv(u,h,m){m>>>=0,ir(u>>>=0,{name:h=Yt(h>>>0),Wc:(g)=>g,cd:(g,x)=>x,bd:Vv(h,m),dd:null})}function jv(u,h,m,g,x){u>>>=0,m>>>=0,h=Yt(h>>>0);let T=(S)=>S;if(g===0){var F=32-8*m;T=(S)=>S<<F>>>F,x=T(x)}ir(u,{name:h,Wc:T,cd:(S,D)=>D,bd:sd(h,m,g!==0),dd:null})}function Wv(u,h,m){function g(T){var F=(M(),P)[T>>>2>>>0];return T=(M(),P)[T+4>>>2>>>0],new x((M(),q).buffer,T,F)}var x=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];ir(u>>>=0,{name:m=Yt(m>>>0),Wc:g,bd:g},{ve:!0})}var lr=(u,h,m)=>{var g=(M(),X);if(h>>>=0,0<m){var x=h;m=h+m-1;for(var T=0;T<u.length;++T){var F=u.codePointAt(T);if(127>=F){if(h>=m)break;g[h++>>>0]=F}else if(2047>=F){if(h+1>=m)break;g[h++>>>0]=192|F>>6,g[h++>>>0]=128|63&F}else if(65535>=F){if(h+2>=m)break;g[h++>>>0]=224|F>>12,g[h++>>>0]=128|F>>6&63,g[h++>>>0]=128|63&F}else{if(h+3>=m)break;g[h++>>>0]=240|F>>18,g[h++>>>0]=128|F>>12&63,g[h++>>>0]=128|F>>6&63,g[h++>>>0]=128|63&F,T++}}g[h>>>0]=0,u=h-x}else u=0;return u},cr=(u)=>{for(var h=0,m=0;m<u.length;++m){var g=u.charCodeAt(m);127>=g?h++:2047>=g?h+=2:55296<=g&&57343>=g?(h+=4,++m):h+=3}return h};function qv(u,h){ir(u>>>=0,{name:h=Yt(h>>>0),Wc(m){var g=(M(),P)[m>>>2>>>0];return g=on(m+4,g,!0),Et(m),g},cd(m,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var x=typeof g=="string";if(!(x||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new ln("Cannot pass non-string to std::string");var T=x?cr(g):g.length,F=Rr(4+T+1),S=F+4;return(M(),P)[F>>>2>>>0]=T,x?lr(g,S,T+1):(M(),X).set(g,S>>>0),m!==null&&m.push(Et,F),F},bd:no,dd(m){Et(m)}})}var od=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Hv=(u,h,m)=>{if(u>>>=1,16<(h=Uu((M(),H),u,h/2,m))-u&&od)return od.decode((M(),H).slice(u,h));for(m="";u<h;++u){var g=(M(),H)[u>>>0];m+=String.fromCharCode(g)}return m},Qv=(u,h,m)=>{if(m??=2147483647,2>m)return 0;var g=h;m=(m-=2)<2*u.length?m/2:u.length;for(var x=0;x<m;++x){var T=u.charCodeAt(x);(M(),Q)[h>>>1>>>0]=T,h+=2}return(M(),Q)[h>>>1>>>0]=0,h-g},Xv=(u)=>2*u.length,Yv=(u,h,m)=>{var g="";u>>>=2;for(var x=0;!(x>=h/4);x++){var T=(M(),P)[u+x>>>0];if(!T&&!m)break;g+=String.fromCodePoint(T)}return g},Kv=(u,h,m)=>{if(h>>>=0,m??=2147483647,4>m)return 0;var g=h;m=g+m-4;for(var x=0;x<u.length;++x){var T=u.codePointAt(x);if(65535<T&&x++,(M(),B)[h>>>2>>>0]=T,(h+=4)+4>m)break}return(M(),B)[h>>>2>>>0]=0,h-g},Jv=(u)=>{for(var h=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,h+=4;return h};function Zv(u,h,m){if(u>>>=0,h>>>=0,m=Yt(m>>>=0),h===2)var g=Hv,x=Qv,T=Xv;else g=Yv,x=Kv,T=Jv;ir(u,{name:m,Wc:(F)=>{var S=(M(),P)[F>>>2>>>0];return S=g(F+4,S*h,!0),Et(F),S},cd:(F,S)=>{if(typeof S!="string")throw new ln(`Cannot pass non-string to C++ string type ${m}`);var D=T(S),j=Rr(4+D+h);return(M(),P)[j>>>2>>>0]=D/h,x(S,j+4,D+h),F!==null&&F.push(Et,j),j},bd:no,dd(F){Et(F)}})}function ey(u,h){ir(u>>>=0,{we:!0,name:h=Yt(h>>>0),Wc:()=>{},cd:()=>{}})}function ty(u){yo(u>>>0,!n,1,!r,131072,!1),Nu()}var ht=(u)=>{if(!C)try{if(u(),!(0<xe))try{s?Rs()&&bo(p):Ja(p)}catch(h){h instanceof be||h=="unwind"||l(0,h)}}catch(h){h instanceof be||h=="unwind"||l(0,h)}},ry=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function so(u){u>>>=0,ry||(Atomics.waitAsync((M(),B),u>>>2,u).value.then(Fs),u+=128,Atomics.store((M(),B),u>>>2,1))}var Fs=()=>ht(()=>{var u=Rs();u&&(so(u),ef())});function ny(u,h){(u>>>=0)==h>>>0?setTimeout(Fs):s?postMessage({gd:u,$c:"checkMailbox"}):(u=Dr[u])&&u.postMessage({$c:"checkMailbox"})}var ao=[];function sy(u,h,m,g,x){for(h>>>=0,x>>>=0,ao.length=0,m=x>>>3,g=x+g>>>3;m<g;){var T;T=(M(),Z)[m++>>>0]?(M(),Z)[m++>>>0]:(M(),ue)[m++>>>0],ao.push(T)}return(h?To[h]:Xb[u])(...ao)}var ay=()=>{xe=0};function oy(u){u>>>=0,s?postMessage({$c:"cleanupThread",Le:u}):Ou(Dr[u])}function iy(u){}var Is=(u)=>{try{u()}catch(h){te(h)}};function ly(u){var h=(...m)=>{Ls.push(u);try{return u(...m)}finally{C||(Ls.pop(),Kt&&yr===1&&Ls.length===0&&(yr=0,xe+=1,Is(Wf),typeof Fibers<"u"&&Fibers.We()))}};return cd.set(u,h),h}var yr=0,Kt=null,id=0,Ls=[],oo=new Map,ld=new Map,cd=new Map,cy=0,io=null,uy=[],ud=(u)=>function(h){if(!C){if(yr===0){var m=!1,g=!1;h((x=0)=>{if(!C&&(id=x,m=!0,g)){yr=2,Is(()=>qf(Kt)),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.resume(),x=!1;try{var T=function(){var D=(M(),B)[Kt+8>>>2>>>0];return D=ld.get(D),D=cd.get(D),--xe,D()}()}catch(D){T=D,x=!0}var F=!1;if(!Kt){var S=io;S&&(io=null,(x?S.reject:S.resolve)(T),F=!0)}if(x&&!F)throw T}}),g=!0,m||(yr=1,Kt=function(){var x=Rr(65548),T=x+12;if((M(),P)[x>>>2>>>0]=T,(M(),P)[x+4>>>2>>>0]=T+65536,T=Ls[0],!oo.has(T)){var F=cy++;oo.set(T,F),ld.set(F,T)}return T=oo.get(T),(M(),B)[x+8>>>2>>>0]=T,x}(),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.pause(),Is(()=>jf(Kt)))}else yr===2?(yr=0,Is(Hf),Et(Kt),Kt=null,uy.forEach(ht)):te(`invalid state: ${yr}`);return id}}((h)=>{u().then(h)});function dy(u){return u>>>=0,ud(async()=>{var h=await Tt(u);return Lt(h)})}var lo=[],fy=(u)=>{var h=lo.length;return lo.push(u),h},hy=(u,h)=>{for(var m=Array(u),g=0;g<u;++g){var x=g,T=(M(),P)[h+4*g>>>2>>>0],F=to[T];if(F===void 0)throw u=`parameter ${g}`,T=Nd(T),h=Yt(T),Et(T),new ln(`${u} has unknown type ${h}`);m[x]=F}return m},_y=(u,h,m)=>{var g=[];return u=u(g,m),g.length&&((M(),P)[h>>>2>>>0]=Lt(g)),u},py={},Os=(u)=>{var h=py[u];return h===void 0?Yt(u):h};function my(u,h,m){var[g,...x]=hy(u,h>>>0);h=g.cd.bind(g);var T=x.map((D)=>D.bd.bind(D));u--;var F={toValue:Tt};switch(u=T.map((D,j)=>{var he=`argFromPtr${j}`;return F[he]=D,`${he}(args${j?"+"+8*j:""})`}),m){case 0:var S="toValue(handle)";break;case 2:S="new (toValue(handle))";break;case 3:S="";break;case 1:F.getStringOrSymbol=Os,S="toValue(handle)[getStringOrSymbol(methodName)]"}return S+=`(${u})`,g.we||(F.toReturnWire=h,F.emval_returnValue=_y,S=`return emval_returnValue(toReturnWire, destructorsRef, ${S})`),S=`return function (handle, methodName, destructorsRef, args) {
|
|
6
|
+
${S}
|
|
7
|
+
}`,m=Function(Object.keys(F),S)(...Object.values(F)),S=`methodCaller<(${x.map((D)=>D.name)}) => ${g.name}>`,fy(Object.defineProperty(m,"name",{value:S}))}function gy(u,h){return h>>>=0,(u=Tt(u>>>0))==Tt(h)}function wy(u){return(u>>>=0)?(u=Os(u),Lt(globalThis[u])):Lt(globalThis)}function vy(u){return u=Os(u>>>0),Lt(t[u])}function yy(u,h){return h>>>=0,u=Tt(u>>>0),h=Tt(h),Lt(u[h])}function by(u){9<(u>>>=0)&&(zr[u+1]+=1)}function dd(u,h,m,g,x){return lo[u>>>0](h>>>0,m>>>0,g>>>0,x>>>0)}function My(u,h,m,g,x){return dd(u>>>0,h>>>0,m>>>0,g>>>0,x>>>0)}function xy(){return Lt([])}function ky(u){u=Tt(u>>>0);for(var h=Array(u.length),m=0;m<u.length;m++)h[m]=u[m];return Lt(h)}function Ty(u){return Lt(Os(u>>>0))}function Ey(){return Lt({})}function Ay(u){for(var h=Tt(u>>>=0);h.length;){var m=h.pop();h.pop()(m)}ro(u)}function Cy(u,h,m){h>>>=0,m>>>=0,u=Tt(u>>>0),h=Tt(h),m=Tt(m),u[h]=m}function Sy(u,h){u=tt(u),h>>>=0,u=new Date(1000*u),(M(),B)[h>>>2>>>0]=u.getUTCSeconds(),(M(),B)[h+4>>>2>>>0]=u.getUTCMinutes(),(M(),B)[h+8>>>2>>>0]=u.getUTCHours(),(M(),B)[h+12>>>2>>>0]=u.getUTCDate(),(M(),B)[h+16>>>2>>>0]=u.getUTCMonth(),(M(),B)[h+20>>>2>>>0]=u.getUTCFullYear()-1900,(M(),B)[h+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/86400000|0,(M(),B)[h+28>>>2>>>0]=u}var fd=(u)=>u%4==0&&(u%100!=0||u%400==0),hd=[0,31,60,91,121,152,182,213,244,274,305,335],_d=[0,31,59,90,120,151,181,212,243,273,304,334];function Py(u,h){u=tt(u),h>>>=0,u=new Date(1000*u),(M(),B)[h>>>2>>>0]=u.getSeconds(),(M(),B)[h+4>>>2>>>0]=u.getMinutes(),(M(),B)[h+8>>>2>>>0]=u.getHours(),(M(),B)[h+12>>>2>>>0]=u.getDate(),(M(),B)[h+16>>>2>>>0]=u.getMonth(),(M(),B)[h+20>>>2>>>0]=u.getFullYear()-1900,(M(),B)[h+24>>>2>>>0]=u.getDay();var m=(fd(u.getFullYear())?hd:_d)[u.getMonth()]+u.getDate()-1|0;(M(),B)[h+28>>>2>>>0]=m,(M(),B)[h+36>>>2>>>0]=-60*u.getTimezoneOffset(),m=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(m!=g&&u.getTimezoneOffset()==Math.min(g,m)),(M(),B)[h+32>>>2>>>0]=u}function Fy(u){u>>>=0;var h=new Date((M(),B)[u+20>>>2>>>0]+1900,(M(),B)[u+16>>>2>>>0],(M(),B)[u+12>>>2>>>0],(M(),B)[u+8>>>2>>>0],(M(),B)[u+4>>>2>>>0],(M(),B)[u>>>2>>>0],0),m=(M(),B)[u+32>>>2>>>0],g=h.getTimezoneOffset(),x=new Date(h.getFullYear(),6,1).getTimezoneOffset(),T=new Date(h.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(T,x);return 0>m?(M(),B)[u+32>>>2>>>0]=+(x!=T&&F==g):0<m!=(F==g)&&(x=Math.max(T,x),h.setTime(h.getTime()+60000*((0<m?F:x)-g))),(M(),B)[u+24>>>2>>>0]=h.getDay(),m=(fd(h.getFullYear())?hd:_d)[h.getMonth()]+h.getDate()-1|0,(M(),B)[u+28>>>2>>>0]=m,(M(),B)[u>>>2>>>0]=h.getSeconds(),(M(),B)[u+4>>>2>>>0]=h.getMinutes(),(M(),B)[u+8>>>2>>>0]=h.getHours(),(M(),B)[u+12>>>2>>>0]=h.getDate(),(M(),B)[u+16>>>2>>>0]=h.getMonth(),(M(),B)[u+20>>>2>>>0]=h.getYear(),u=h.getTime(),BigInt(isNaN(u)?-1:u/1000)}function pd(u,h,m,g,x,T,F){return s?Ie(16,1,u,h,m,g,x,T,F):-52}function md(u,h,m,g,x,T){if(s)return Ie(17,1,u,h,m,g,x,T)}var Hn={},Iy=()=>performance.timeOrigin+performance.now();function gd(u,h){if(s)return Ie(18,1,u,h);if(Hn[u]&&(clearTimeout(Hn[u].id),delete Hn[u]),!h)return 0;var m=setTimeout(()=>{delete Hn[u],ht(()=>Zd(u,performance.timeOrigin+performance.now()))},h);return Hn[u]={id:m,Ve:h},0}function Ly(u,h,m,g){u>>>=0,h>>>=0,m>>>=0,g>>>=0;var x=new Date().getFullYear(),T=new Date(x,0,1).getTimezoneOffset();x=new Date(x,6,1).getTimezoneOffset();var F=Math.max(T,x);(M(),P)[u>>>2>>>0]=60*F,(M(),B)[h>>>2>>>0]=+(T!=x),u=(h=(S)=>{var D=Math.abs(S);return`UTC${0<=S?"-":"+"}${String(Math.floor(D/60)).padStart(2,"0")}${String(D%60).padStart(2,"0")}`})(T),h=h(x),x<T?(lr(u,m,17),lr(h,g,17)):(lr(u,g,17),lr(h,m,17))}var Oy=()=>Date.now(),Ny=1;function Dy(u,h,m){if(m>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!Ny)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(M(),Z)[m>>>3>>>0]=BigInt(u),0}var co=[],wd=(u,h)=>{co.length=0;for(var m;m=(M(),X)[u++>>>0];){var g=m!=105;h+=(g&=m!=112)&&h%8?4:0,co.push(m==112?(M(),P)[h>>>2>>>0]:m==106?(M(),Z)[h>>>3>>>0]:m==105?(M(),B)[h>>>2>>>0]:(M(),ue)[h>>>3>>>0]),h+=g?8:4}return co};function zy(u,h,m){return u>>>=0,h=wd(h>>>0,m>>>0),To[u](...h)}function By(u,h,m){return u>>>=0,h=wd(h>>>0,m>>>0),To[u](...h)}var Ry=()=>{};function $y(u,h){return E(on(u>>>0,h>>>0))}var Gy=()=>{throw xe+=1,"unwind"};function Vy(){return 4294901760}var Uy=()=>1,jy=()=>navigator.hardwareConcurrency,Br={},vd=(u)=>{var h=cr(u)+1,m=Rr(h);return m&&lr(u,m,h),m},Ns=(u)=>{var h;return(h=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(u))?+h[1]:(h=/:(\d+):\d+(?:\)|$)/.exec(u))?2147483648|+h[1]:0},yd=(u)=>{for(var h of u)(u=Ns(h))&&(Br[u]=h)};function Wy(){var u=Error().stack.toString().split(`
|
|
8
|
+
`);return u[0]=="Error"&&u.shift(),yd(u),Br.ee=Ns(u[3]),Br.xe=u,Br.ee}function Ds(u){if(!(u=Br[u>>>0]))return 0;var h;if(h=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(u))u=h[1];else if(h=/^\s+at (.*) \(.*\)$/.exec(u))u=h[1];else{if(!(h=/^(.+?)@/.exec(u)))return 0;u=h[1]}return Et(Ds.ne??0),Ds.ne=vd(u),Ds.ne}function qy(u){u>>>=0;var h=(M(),X).length;if(u<=h||4294901760<u)return!1;for(var m=1;4>=m;m*=2){var g=h*(1+0.2/m);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-vr.buffer.byteLength+65535)/65536|0;try{vr.grow(g),V();var x=1;break e}catch{}x=void 0}if(x)return!0}return!1}function Hy(u,h,m){if(u>>>=0,h>>>=0,Br.ee==u)var g=Br.xe;else(g=Error().stack.toString().split(`
|
|
9
|
+
`))[0]=="Error"&&g.shift(),yd(g);for(var x=3;g[x]&&Ns(g[x])!=u;)++x;for(u=0;u<m&&g[u+x];++u)(M(),B)[h+4*u>>>2>>>0]=Ns(g[u+x]);return u}var Jt=(u)=>{var h=cr(u)+1,m=$s(h);return lr(u,m,h),m},cn=(u)=>(M(),P)[u>>>2>>>0]+4294967296*(M(),B)[u+4>>>2>>>0],rt=[],bd=(u,h)=>{rt[u>>>0]=h},ur=[],zs=[],un=(u,h)=>{zs[u]=new Promise((m)=>h.finally(()=>m(u)))},ee=(u)=>{if(u)return rt[u>>>0]},uo=(u,h)=>{for(u=(M(),P)[u>>>2>>>0];u;u=(M(),P)[u>>>2>>>0])h[(M(),B)[u+4>>>2>>>0]](u)},Bs=(u,h,m)=>{(M(),P)[u>>>2>>>0]=h,(M(),P)[u+4>>>2>>>0]=m},Md=(u)=>{var h=(M(),P)[u>>>2>>>0];return u=(M(),P)[u+4>>>2>>>0],on(h,u)},Ot=(u)=>{var h=(M(),P)[u>>>2>>>0];return u=(M(),P)[u+4>>>2>>>0],h?on(h,u):u===0?"":void 0},Qy=(u)=>{var h=Ot(u+4),m=(m=(M(),P)[u+12>>>2>>>0])?ee(m):"auto";if(u+=16){var g=ee((M(),P)[u+4>>>2>>>0]),x=(M(),P)[u+16>>>2>>>0],T=(M(),P)[u+20>>>2>>>0];if(x){for(var F={},S=0;S<x;++S){var D=T+24*S;F[Md(D+4)]=(M(),ue)[D+16>>>3>>>0]}x=F}else x=void 0;u={module:g,constants:x,entryPoint:Ot(u+8)}}else u=void 0;return{label:h,layout:m,compute:u}},xd=(u,h)=>{function m(T,F,S,D=0){T=u[T]??D,(M(),P)[F+S>>>2>>>0]=T}function g(T,F,S,D=0){F+=S,T=u[T]??D,(M(),P)[F>>>2>>>0]=T,D=(M(),P)[F>>>2>>>0],(M(),P)[F+4>>>2>>>0]=(T-D)/4294967296}var x=(M(),P)[h>>>2>>>0];m("maxTextureDimension1D",h,4),m("maxTextureDimension2D",h,8),m("maxTextureDimension3D",h,12),m("maxTextureArrayLayers",h,16),m("maxBindGroups",h,20),m("maxBindGroupsPlusVertexBuffers",h,24),m("maxBindingsPerBindGroup",h,28),m("maxDynamicUniformBuffersPerPipelineLayout",h,32),m("maxDynamicStorageBuffersPerPipelineLayout",h,36),m("maxSampledTexturesPerShaderStage",h,40),m("maxSamplersPerShaderStage",h,44),m("maxStorageBuffersPerShaderStage",h,48),m("maxStorageTexturesPerShaderStage",h,52),m("maxUniformBuffersPerShaderStage",h,56),m("minUniformBufferOffsetAlignment",h,80),m("minStorageBufferOffsetAlignment",h,84),g("maxUniformBufferBindingSize",h,64),g("maxStorageBufferBindingSize",h,72),m("maxVertexBuffers",h,88),g("maxBufferSize",h,96),m("maxVertexAttributes",h,104),m("maxVertexBufferArrayStride",h,108),m("maxInterStageShaderVariables",h,112),m("maxColorAttachments",h,116),m("maxColorAttachmentBytesPerSample",h,120),m("maxComputeWorkgroupStorageSize",h,124),m("maxComputeInvocationsPerWorkgroup",h,128),m("maxComputeWorkgroupSizeX",h,132),m("maxComputeWorkgroupSizeY",h,136),m("maxComputeWorkgroupSizeZ",h,140),m("maxComputeWorkgroupsPerDimension",h,144),m("maxImmediateSize",h,148),x!==0&&(M(),m("maxStorageBuffersInVertexStage",x,8,u.maxStorageBuffersPerShaderStage),m("maxStorageBuffersInFragmentStage",x,16,u.maxStorageBuffersPerShaderStage),m("maxStorageTexturesInVertexStage",x,12,u.maxStorageTexturesPerShaderStage),m("maxStorageTexturesInFragmentStage",x,20,u.maxStorageTexturesPerShaderStage))},Xy=(u,h)=>{(M(),P)[h+52>>>2>>>0]=u.subgroupMinSize,(M(),P)[h+56>>>2>>>0]=u.subgroupMaxSize;var m=vd(u.vendor+u.architecture+u.device+u.description),g=cr(u.vendor);Bs(h+4,m,g),m+=g,g=cr(u.architecture),Bs(h+12,m,g),m+=g,g=cr(u.device),Bs(h+20,m,g),m+=g,g=cr(u.description),Bs(h+28,m,g),m+=g,(M(),B)[h+36>>>2>>>0]=2,m=u.isFallbackAdapter?3:4,(M(),B)[h+40>>>2>>>0]=m,(M(),P)[h+44>>>2>>>0]=0,(M(),P)[h+48>>>2>>>0]=0,uo(h,{327739:(x)=>{let T=0,F=0;if(u.subgroupMatrixConfigs){T=u.subgroupMatrixConfigs.length,F=Rr(20*T);for(let[S,D]of u.subgroupMatrixConfigs.entries()){let j=F+20*S,he=Td.indexOf(D.componentType),me=Td.indexOf(D.resultComponentType);(M(),B)[j>>>2>>>0]=he,(M(),B)[j+4>>>2>>>0]=me,(M(),P)[j+8>>>2>>>0]=D.M,(M(),P)[j+12>>>2>>>0]=D.N,(M(),P)[j+16>>>2>>>0]=D.K}}(M(),P)[x+12>>>2>>>0]=F,(M(),P)[x+8>>>2>>>0]=T}})},Yy=[,,"uniform","storage","read-only-storage"],Ky=[,"validation","out-of-memory","internal"],Jy=[,"compatibility","core"],kd={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},Zy=[,"low-power","high-performance"],eb=[,"occlusion","timestamp"],tb=[,,"filtering","non-filtering","comparison"],rb=[,,"write-only","read-only","read-write"],Td=[,"f32","f16","u32","i32","u8","i8"],nb=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],sb=[,,"float","unfilterable-float","depth","sint","uint"],Ed=[,"1d","2d","2d-array","cube","cube-array","3d"],ab={undefined:1,unknown:1,destroyed:2};function ob(u,h,m,g,x,T){h=tt(h),m=tt(m),g>>>=0,x>>>=0,T>>>=0;var F=ee(u>>>0);if(u={},T){var S=(M(),P)[T+12>>>2>>>0];if(S){var D=(M(),P)[T+16>>>2>>>0];u.requiredFeatures=Array.from((M(),P).subarray(D>>>2>>>0,D+4*S>>>2>>>0),(K)=>kd[K])}if(S=(M(),P)[T+20>>>2>>>0]){let K=function(_t,lt,$r,Gr=!1){lt+=$r,(lt=(M(),P)[lt>>>2>>>0])==4294967295||Gr&<==0||(me[_t]=lt)},Ae=function(_t,lt,$r){lt+=$r,$r=(M(),P)[lt>>>2>>>0];var Gr=(M(),P)[lt+4>>>2>>>0];$r==4294967295&&Gr==4294967295||(me[_t]=cn(lt))};var j=K,he=Ae;D=(M(),P)[S>>>2>>>0];var me={};K("maxTextureDimension1D",S,4),K("maxTextureDimension2D",S,8),K("maxTextureDimension3D",S,12),K("maxTextureArrayLayers",S,16),K("maxBindGroups",S,20),K("maxBindGroupsPlusVertexBuffers",S,24),K("maxBindingsPerBindGroup",S,28),K("maxDynamicUniformBuffersPerPipelineLayout",S,32),K("maxDynamicStorageBuffersPerPipelineLayout",S,36),K("maxSampledTexturesPerShaderStage",S,40),K("maxSamplersPerShaderStage",S,44),K("maxStorageBuffersPerShaderStage",S,48),K("maxStorageTexturesPerShaderStage",S,52),K("maxUniformBuffersPerShaderStage",S,56),K("minUniformBufferOffsetAlignment",S,80),K("minStorageBufferOffsetAlignment",S,84),Ae("maxUniformBufferBindingSize",S,64),Ae("maxStorageBufferBindingSize",S,72),K("maxVertexBuffers",S,88),Ae("maxBufferSize",S,96),K("maxVertexAttributes",S,104),K("maxVertexBufferArrayStride",S,108),K("maxInterStageShaderVariables",S,112),K("maxColorAttachments",S,116),K("maxColorAttachmentBytesPerSample",S,120),K("maxComputeWorkgroupStorageSize",S,124),K("maxComputeInvocationsPerWorkgroup",S,128),K("maxComputeWorkgroupSizeX",S,132),K("maxComputeWorkgroupSizeY",S,136),K("maxComputeWorkgroupSizeZ",S,140),K("maxComputeWorkgroupsPerDimension",S,144),K("maxImmediateSize",S,148,!0),D!==0&&(M(),("maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype)&&(K("maxStorageBuffersInVertexStage",D,8),K("maxStorageTexturesInVertexStage",D,12),K("maxStorageBuffersInFragmentStage",D,16),K("maxStorageTexturesInFragmentStage",D,20))),u.requiredLimits=me}(S=(M(),P)[T+24>>>2>>>0])&&(S={label:Ot(S+4)},u.defaultQueue=S),u.label=Ot(T+4)}xe+=1,un(h,F.requestDevice(u).then((K)=>{--xe,ht(()=>{rt[x>>>0]=K.queue,rt[g>>>0]=K,xe+=1,un(m,K.lost.then((Ae)=>{ht(()=>{K.onuncapturederror=()=>{};var _t=ne(),lt=Jt(Ae.message);mo(m,ab[Ae.reason],lt),re(_t)}),--xe})),K.onuncapturederror=(Ae)=>{var _t=5;Ae.error instanceof GPUValidationError?_t=2:Ae.error instanceof GPUOutOfMemoryError?_t=3:Ae.error instanceof GPUInternalError&&(_t=4);var lt=ne();Ae=Jt(Ae.error.message),Xd(g,_t,Ae),re(lt)},"adapterInfo"in K||(K.adapterInfo=F.info),vo(h,1,g,0)})},(K)=>{--xe,ht(()=>{var Ae=ne(),_t=Jt(K.message);vo(h,3,g,_t),m&&mo(m,4,_t),re(Ae)})}))}function ib(u){var h=ee(u>>>=0),m=ur[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete ur[u]}h.destroy()}function lb(u,h,m){m>>>=0;var g=ee(u>>>=0);m==4294967295&&(m=void 0);try{var x=g.getMappedRange(h>>>0,m)}catch{return 0}var T=Mo(16,x.byteLength);return(M(),X).set(new Uint8Array(x),T>>>0),ur[u].push(()=>Et(T)),T}function cb(u,h,m){m>>>=0;var g=ee(u>>>=0);m==4294967295&&(m=void 0);try{var x=g.getMappedRange(h>>>0,m)}catch{return 0}var T=Mo(16,x.byteLength);return(M(),X).fill(0,T,x.byteLength),ur[u].push(()=>{new Uint8Array(x).set((M(),X).subarray(T>>>0,T+x.byteLength>>>0)),Et(T)}),T}function ub(u,h,m,g,x){u>>>=0,h=tt(h),m=tt(m),x>>>=0;var T=ee(u);ur[u]=[],x==4294967295&&(x=void 0),xe+=1,un(h,T.mapAsync(m,g>>>0,x).then(()=>{--xe,ht(()=>{go(h,1,0)})},(F)=>{--xe,ht(()=>{ne();var S=Jt(F.message);go(h,F.name==="AbortError"?4:F.name==="OperationError"?3:0,S),delete ur[u]})}))}function db(u){var h=ee(u>>>=0),m=ur[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete ur[u],h.unmap()}}function fb(u){delete rt[u>>>0]}function hb(u,h,m){u>>>=0,h>>>=0,m>>>=0;var g=!!(M(),P)[h+32>>>2>>>0];h={label:Ot(h+4),usage:(M(),P)[h+16>>>2>>>0],size:cn(h+24),mappedAtCreation:g},u=ee(u);try{var x=u.createBuffer(h)}catch{return!1}return rt[m>>>0]=x,g&&(ur[m]=[]),!0}function _b(u,h,m,g){u>>>=0,h=tt(h),g>>>=0,m=Qy(m>>>0),u=ee(u),xe+=1,un(h,u.createComputePipelineAsync(m).then((x)=>{--xe,ht(()=>{rt[g>>>0]=x,po(h,1,g,0)})},(x)=>{--xe,ht(()=>{var T=ne(),F=Jt(x.message);po(h,x.reason==="validation"?3:x.reason==="internal"?4:0,g,F),re(T)})}))}function pb(u,h,m){u>>>=0,h>>>=0,m>>>=0;var g=(M(),P)[h>>>2>>>0],x=(M(),B)[g+4>>>2>>>0];h={label:Ot(h+4),code:""},x===2&&(h.code=Md(g+8)),u=ee(u).createShaderModule(h),rt[m>>>0]=u}var mb=(u)=>{(u=ee(u)).onuncapturederror=null,u.destroy()};function gb(u,h){h=tt(h),u=ee(u>>>0),xe+=1,un(h,u.popErrorScope().then((m)=>{--xe,ht(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var x=ne(),T=m?Jt(m.message):0;wo(h,1,g,T),re(x)})},(m)=>{--xe,ht(()=>{var g=ne(),x=Jt(m.message);wo(h,1,5,x),re(g)})}))}function wb(u,h,m,g){if(h=tt(h),g>>>=0,m>>>=0){var x={featureLevel:Jy[(M(),B)[m+4>>>2>>>0]],powerPreference:Zy[(M(),B)[m+8>>>2>>>0]],forceFallbackAdapter:!!(M(),P)[m+12>>>2>>>0]};(u=(M(),P)[m>>>2>>>0])!==0&&(M(),x.Ye=!!(M(),P)[u+8>>>2>>>0])}"gpu"in navigator?(xe+=1,un(h,navigator.gpu.requestAdapter(x).then((T)=>{--xe,ht(()=>{if(T)rt[g>>>0]=T,Qn(h,1,g,0);else{var F=ne(),S=Jt("WebGPU not available on this browser (requestAdapter returned null)");Qn(h,3,g,S),re(F)}})},(T)=>{--xe,ht(()=>{var F=ne(),S=Jt(T.message);Qn(h,4,g,S),re(F)})}))):(x=ne(),u=Jt("WebGPU not available on this browser (navigator.gpu is not available)"),Qn(h,3,g,u),re(x))}function vb(u,h,m){return u>>>=0,h>>>=0,m>>>=0,ud(async()=>{var g=[];if(m){var x=(M(),B)[m>>>2>>>0];g.length=h+1,g[h]=new Promise((S)=>setTimeout(S,x,0))}else g.length=h;for(var T=0;T<h;++T){var F=cn(u+8*T);if(!(F in zs))return F;g[T]=zs[F]}return g=await Promise.race(g),delete zs[g],g})}var fo,ho={},Ad=()=>{if(!fo){var u,h={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 ho)ho[u]===void 0?delete h[u]:h[u]=ho[u];var m=[];for(u in h)m.push(`${u}=${h[u]}`);fo=m}return fo};function Cd(u,h){if(s)return Ie(19,1,u,h);u>>>=0,h>>>=0;var m,g=0,x=0;for(m of Ad()){var T=h+g;(M(),P)[u+x>>>2>>>0]=T,g+=lr(m,T,1/0)+1,x+=4}return 0}function Sd(u,h){if(s)return Ie(20,1,u,h);u>>>=0,h>>>=0;var m=Ad();for(var g of((M(),P)[u>>>2>>>0]=m.length,u=0,m))u+=cr(g)+1;return(M(),P)[h>>>2>>>0]=u,0}function Pd(u){return s?Ie(21,1,u):52}function Fd(u,h,m,g,x){return s?Ie(22,1,u,h,m,g,x):52}function Id(u,h,m,g){return s?Ie(23,1,u,h,m,g):52}function Ld(u,h,m,g){return s?Ie(24,1,u,h,m,g):70}var yb=[null,[],[]];function Od(u,h,m,g){if(s)return Ie(25,1,u,h,m,g);h>>>=0,m>>>=0,g>>>=0;for(var x=0,T=0;T<m;T++){var F=(M(),P)[h>>>2>>>0],S=(M(),P)[h+4>>>2>>>0];h+=8;for(var D=0;D<S;D++){var j=u,he=(M(),X)[F+D>>>0],me=yb[j];he===0||he===10?((j===1?A:E)(ju(me)),me.length=0):me.push(he)}x+=S}return(M(),P)[g>>>2>>>0]=x,0}function bb(u){return u>>>0}function Mb(u,h){return xd(ee(u>>>0).limits,h>>>0),1}function xb(u,h){return ee(u>>>0).features.has(kd[h])}function kb(u){return BigInt(ee(u>>>0).size)}function Tb(u){return BigInt(ee(u>>>0).usage)}function Eb(u,h){if(u>>>=0,h>>>=0){var m=Ot(h+4);m={label:m,timestampWrites:h=(h=(M(),P)[h+12>>>2>>>0])!==0?{querySet:ee((M(),P)[h+4>>>2>>>0]),beginningOfPassWriteIndex:(M(),P)[h+8>>>2>>>0],endOfPassWriteIndex:(M(),P)[h+12>>>2>>>0]}:void 0}}return h=ee(u),u=Ud(0),m=h.beginComputePass(m),rt[u>>>0]=m,u}function Ab(u,h,m,g){m=tt(m),(g=tt(g))==-1&&(g=void 0),(u=ee(u>>>0)).clearBuffer(ee(h>>>0),m,g)}function Cb(u,h,m,g,x,T){m=tt(m),x=tt(x),T=tt(T),ee(u>>>0).copyBufferToBuffer(ee(h>>>0),m,ee(g>>>0),x,T)}function Sb(u){var h=ee(u>>>0);return u=Gd(0),h=h.finish(),rt[u>>>0]=h,u}function Pb(u,h,m,g,x,T){T=tt(T),ee(u>>>0).resolveQuerySet(ee(h>>>0),m,g,ee(x>>>0),T)}function Fb(u,h,m,g){ee(u>>>0).dispatchWorkgroups(h,m,g)}function Ib(u,h,m){m=tt(m),ee(u>>>0).dispatchWorkgroupsIndirect(ee(h>>>0),m)}function Lb(u){ee(u>>>0).end()}function Ob(u,h,m,g,x){g>>>=0,x>>>=0,u=ee(u>>>0),m=ee(m>>>0),g==0?u.setBindGroup(h,m):u.setBindGroup(h,m,(M(),P),x>>>2,g)}function Nb(u,h){ee(u>>>0).setPipeline(ee(h>>>0))}function Db(u,h,m){ee(u>>>0).Xe(ee(h>>>0),m)}function zb(u,h){function m(x){var T=(M(),P)[x+8>>>2>>>0],F=(M(),P)[x+32>>>2>>>0],S=(M(),P)[x+36>>>2>>>0],D=0;return uo(x,{14:(j)=>{D=(M(),P)[j+8>>>2>>>0]}}),T?((F=cn(x+24))==-1&&(F=void 0),T={buffer:ee(T),offset:cn(x+16),size:F}):T=ee(F||S||D),{binding:(M(),P)[x+4>>>2>>>0],resource:T}}u>>>=0,h={label:Ot((h>>>=0)+4),layout:ee((M(),P)[h+12>>>2>>>0]),entries:function(x,T){for(var F=[],S=0;S<x;++S)F.push(m(T+40*S));return F}((M(),P)[h+16>>>2>>>0],(M(),P)[h+20>>>2>>>0])},u=ee(u);var g=Rd(0);return bd(g,u.createBindGroup(h)),g}function Bb(u,h){function m(D){var j=(M(),P)[D+4>>>2>>>0];if(j)return{type:Yy[j],hasDynamicOffset:!!(M(),P)[D+8>>>2>>>0],minBindingSize:cn(D+16)}}function g(D){if(D=(M(),P)[D+4>>>2>>>0])return{type:tb[D]}}function x(D){var j=(M(),P)[D+4>>>2>>>0];if(j)return{sampleType:sb[j],viewDimension:Ed[(M(),B)[D+8>>>2>>>0]],multisampled:!!(M(),P)[D+12>>>2>>>0]}}function T(D){var j=(M(),P)[D+4>>>2>>>0];if(j)return{access:rb[j],format:nb[(M(),B)[D+8>>>2>>>0]],viewDimension:Ed[(M(),B)[D+12>>>2>>>0]]}}function F(D){var j={binding:(M(),P)[D+4>>>2>>>0],visibility:(M(),P)[D+8>>>2>>>0],buffer:m(D+24),sampler:g(D+48),texture:x(D+56),storageTexture:T(D+72)};return uo(D,{13:()=>{j.externalTexture={}}}),j}u>>>=0,h={label:Ot((h>>>=0)+4),entries:function(D,j){for(var he=[],me=0;me<D;++me)he.push(F(j+88*me));return he}((M(),P)[h+12>>>2>>>0],(M(),P)[h+16>>>2>>>0])},u=ee(u);var S=$d(0);return bd(S,u.createBindGroupLayout(h)),S}function Rb(u,h){var m;return u>>>=0,(h>>>=0)&&(m={label:Ot(h+4)}),h=ee(u),u=Vd(0),m=h.createCommandEncoder(m),rt[u>>>0]=m,u}function $b(u,h){u>>>=0,h>>>=0;for(var m=(M(),P)[h+12>>>2>>>0],g=(M(),P)[h+16>>>2>>>0],x=[],T=0;T<m;++T)x.push(ee((M(),P)[g+4*T>>>2>>>0]));return h={label:Ot(h+4),bindGroupLayouts:x,immediateSize:(M(),P)[h+20>>>2>>>0]},m=ee(u),u=jd(0),h=m.createPipelineLayout(h),rt[u>>>0]=h,u}function Gb(u,h){u>>>=0,h>>>=0,h={type:eb[(M(),B)[h+12>>>2>>>0]],count:(M(),P)[h+16>>>2>>>0]};var m=ee(u);return u=Wd(0),h=m.createQuerySet(h),rt[u>>>0]=h,u}function Vb(u,h){return Xy(ee(u>>>0).adapterInfo,h>>>0),1}var Ub={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function jb(u,h){h>>>=0;var m=ee(u>>>0);u=Rr(4*m.features.size);var g=0,x=0;for(let T of m.features)0<=(m=Ub[T])&&((M(),B)[u+g>>>2>>>0]=m,g+=4,x++);(M(),P)[h+4>>>2>>>0]=u,(M(),P)[h>>>2>>>0]=x}function Wb(u,h){return xd(ee(u>>>0).limits,h>>>0),1}function qb(u,h){ee(u>>>0).pushErrorScope(Ky[h])}function Hb(u,h,m){h>>>=0,m>>>=0,u=ee(u>>>0),h=Array.from((M(),B).subarray(m>>>2>>>0,m+4*h>>>2>>>0),(g)=>ee(g)),u.submit(h)}function Qb(u,h,m,g,x){m=tt(m),g>>>=0,x>>>=0,u=ee(u>>>0),h=ee(h>>>0),g=(M(),X).subarray(g>>>0,g+x>>>0),u.writeBuffer(h,m,g,0,x)}s||function(){for(var u=t.numThreads-1;u--;)zu();Oe.push(async()=>{var h=async function(){if(!s)return Promise.all(wr.map(Du))}();Me++,await h,--Me==0&&Ye&&(h=Ye,Ye=null,h())})}(),s||(vr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),V()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>ne(),t.stackRestore=(u)=>re(u),t.stackAlloc=(u)=>$s(u),t.setValue=function(u,h,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":(M(),q)[u>>>0]=h;break;case"i16":(M(),Q)[u>>>1>>>0]=h;break;case"i32":(M(),B)[u>>>2>>>0]=h;break;case"i64":(M(),Z)[u>>>3>>>0]=BigInt(h);break;case"float":(M(),Y)[u>>>2>>>0]=h;break;case"double":(M(),ue)[u>>>3>>>0]=h;break;case"*":(M(),P)[u>>>2>>>0]=h;break;default:te(`invalid type for setValue: ${m}`)}},t.getValue=function(u,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":return(M(),q)[u>>>0];case"i16":return(M(),Q)[u>>>1>>>0];case"i32":return(M(),B)[u>>>2>>>0];case"i64":return(M(),Z)[u>>>3>>>0];case"float":return(M(),Y)[u>>>2>>>0];case"double":return(M(),ue)[u>>>3>>>0];case"*":return(M(),P)[u>>>2>>>0];default:te(`invalid type for getValue: ${h}`)}},t.UTF8ToString=on,t.stringToUTF8=lr,t.lengthBytesUTF8=cr;var Nd,Dd,zd,_o,Rs,Et,Rr,Bd,Rd,$d,Gd,Vd,Ud,jd,Wd,qd,Hd,Qd,po,mo,go,wo,Qn,vo,Xd,yo,Yd,Kd,Jd,bo,Zd,ef,Mo,_e,Xn,tf,re,$s,ne,rf,xo,nf,sf,af,ko,of,lf,cf,uf,df,ff,hf,_f,pf,mf,gf,wf,vf,yf,bf,Mf,xf,kf,Tf,Ef,Af,Cf,Sf,Pf,Ff,If,Lf,Of,Nf,Df,zf,Bf,Rf,$f,Gf,Vf,Uf,jf,Wf,qf,Hf,dr,Xb=[sn,Wn,$u,Wu,qu,Hu,Qu,Xu,Yu,Ku,Ju,Zu,ed,td,rd,nd,pd,md,gd,Cd,Sd,Pd,Fd,Id,Ld,Od],To={1280444:(u,h,m,g,x)=>{if(t===void 0||!t.ed)return 1;if((u=on(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.ed.get(u)))return 2;if(h=Number(h>>>0),m=Number(m>>>0),g=Number(g>>>0),h+m>u.byteLength)return 3;try{let T=u.subarray(h,h+m);switch(x){case 0:(M(),X).set(T,g>>>0);break;case 1:t.pe?t.pe(g,T):t.Re(g,T);break;default:return 4}return 0}catch{return 4}},1281268:(u,h,m)=>{t.re(u,(M(),X).subarray(h>>>0,h+m>>>0))},1281332:()=>t.Pe(),1281374:(u)=>{t.qe(u)},1281411:()=>typeof wasmOffsetConverter<"u"};function Yb(){return typeof wasmOffsetConverter<"u"}function Kb(u,h,m,g){var x=ne();try{return _f(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function Jb(u,h,m){var g=ne();try{return df(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;_e(1,0)}}function Zb(u){var h=ne();try{of(u)}catch(m){if(re(h),m!==m+0)throw m;_e(1,0)}}function e0(u,h){var m=ne();try{return ko(u,h)}catch(g){if(re(m),g!==g+0)throw g;_e(1,0)}}function t0(u,h,m){var g=ne();try{af(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;_e(1,0)}}function r0(u,h){var m=ne();try{pf(u,h)}catch(g){if(re(m),g!==g+0)throw g;_e(1,0)}}function n0(u,h,m,g,x,T,F){var S=ne();try{return uf(u,h,m,g,x,T,F)}catch(D){if(re(S),D!==D+0)throw D;_e(1,0)}}function s0(u,h,m,g,x,T){var F=ne();try{lf(u,h,m,g,x,T)}catch(S){if(re(F),S!==S+0)throw S;_e(1,0)}}function a0(u,h,m,g){var x=ne();try{hf(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function o0(u,h,m,g,x,T,F){var S=ne();try{gf(u,h,m,g,x,T,F)}catch(D){if(re(S),D!==D+0)throw D;_e(1,0)}}function i0(u,h,m,g,x,T,F){var S=ne();try{wf(u,h,m,g,x,T,F)}catch(D){if(re(S),D!==D+0)throw D;_e(1,0)}}function l0(u,h,m,g,x,T,F,S){var D=ne();try{Cf(u,h,m,g,x,T,F,S)}catch(j){if(re(D),j!==j+0)throw j;_e(1,0)}}function c0(u,h,m,g,x,T,F,S,D,j,he,me){var K=ne();try{vf(u,h,m,g,x,T,F,S,D,j,he,me)}catch(Ae){if(re(K),Ae!==Ae+0)throw Ae;_e(1,0)}}function u0(u,h,m,g,x){var T=ne();try{return mf(u,h,m,g,x)}catch(F){if(re(T),F!==F+0)throw F;_e(1,0)}}function d0(u,h,m,g,x,T){var F=ne();try{Sf(u,h,m,g,x,T)}catch(S){if(re(F),S!==S+0)throw S;_e(1,0)}}function f0(u,h,m,g,x){var T=ne();try{cf(u,h,m,g,x)}catch(F){if(re(T),F!==F+0)throw F;_e(1,0)}}function h0(u,h,m,g,x,T,F,S){var D=ne();try{ff(u,h,m,g,x,T,F,S)}catch(j){if(re(D),j!==j+0)throw j;_e(1,0)}}function _0(u){var h=ne();try{return Pf(u)}catch(m){if(re(h),m!==m+0)throw m;_e(1,0)}}function p0(u,h,m,g,x,T,F,S,D){var j=ne();try{bf(u,h,m,g,x,T,F,S,D)}catch(he){if(re(j),he!==he+0)throw he;_e(1,0)}}function m0(u,h,m){var g=ne();try{return Ff(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;_e(1,0)}}function g0(u,h){var m=ne();try{return Uf(u,h)}catch(g){if(re(m),g!==g+0)throw g;return _e(1,0),0n}}function w0(u,h,m,g){var x=ne();try{return If(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function v0(u){var h=ne();try{return yf(u)}catch(m){if(re(h),m!==m+0)throw m;return _e(1,0),0n}}function y0(u,h,m,g){var x=ne();try{return Lf(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function b0(u,h,m,g,x){var T=ne();try{return Of(u,h,m,g,x)}catch(F){if(re(T),F!==F+0)throw F;_e(1,0)}}function M0(u,h,m,g,x,T){var F=ne();try{return Nf(u,h,m,g,x,T)}catch(S){if(re(F),S!==S+0)throw S;_e(1,0)}}function x0(u,h,m,g,x,T){var F=ne();try{return Ef(u,h,m,g,x,T)}catch(S){if(re(F),S!==S+0)throw S;_e(1,0)}}function k0(u,h,m,g,x,T){var F=ne();try{return Df(u,h,m,g,x,T)}catch(S){if(re(F),S!==S+0)throw S;_e(1,0)}}function T0(u,h,m,g,x,T,F,S){var D=ne();try{return Af(u,h,m,g,x,T,F,S)}catch(j){if(re(D),j!==j+0)throw j;_e(1,0)}}function E0(u,h,m,g,x){var T=ne();try{return zf(u,h,m,g,x)}catch(F){if(re(T),F!==F+0)throw F;return _e(1,0),0n}}function A0(u,h,m,g){var x=ne();try{return Bf(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function C0(u,h,m,g){var x=ne();try{return Rf(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function S0(u,h,m,g,x,T,F,S,D,j,he,me){var K=ne();try{return $f(u,h,m,g,x,T,F,S,D,j,he,me)}catch(Ae){if(re(K),Ae!==Ae+0)throw Ae;_e(1,0)}}function P0(u,h,m,g,x,T,F,S,D,j,he){var me=ne();try{Gf(u,h,m,g,x,T,F,S,D,j,he)}catch(K){if(re(me),K!==K+0)throw K;_e(1,0)}}function F0(u,h,m,g,x,T,F,S,D,j,he,me,K,Ae,_t,lt){var $r=ne();try{Vf(u,h,m,g,x,T,F,S,D,j,he,me,K,Ae,_t,lt)}catch(Gr){if(re($r),Gr!==Gr+0)throw Gr;_e(1,0)}}function I0(u,h,m){var g=ne();try{return xf(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;return _e(1,0),0n}}function L0(u,h,m){var g=ne();try{return Mf(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;_e(1,0)}}function O0(u,h,m){var g=ne();try{return kf(u,h,m)}catch(x){if(re(g),x!==x+0)throw x;_e(1,0)}}function N0(u,h,m,g){var x=ne();try{Tf(u,h,m,g)}catch(T){if(re(x),T!==T+0)throw T;_e(1,0)}}function Gs(){if(0<Me)Ye=Gs;else if(s)w?.(t),de();else{for(var u=Oe;0<u.length;)u.shift()(t);0<Me?Ye=Gs:(t.calledRun=!0,C||(de(),w?.(t)))}}return s||(dr=await Fe(),Gs()),t.PTR_SIZE=4,t.webgpuInit=(u)=>{let h=new WeakMap,m,g,x=1;t.webgpuRegisterDevice=(S)=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(S){var D=h.get(S);if(!D){let j=((he,me=0)=>{var K=Qd(me);return me=Hd(me,K),rt[K>>>0]=he.queue,rt[me>>>0]=he,me})(S,D=zd());D=[x++,D,j],h.set(S,D)}return m=S,g=D[0],D}m=void 0,g=0};let T=new Map;t.webgpuOnCreateSession=(S)=>{if(g!==void 0){var D=g;if(g=void 0,S){let j=_o(D);T.set(S,j),D===0&&u(m??ee(j))}m=void 0}},t.webgpuOnReleaseSession=(S)=>{T.delete(S)};let F=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(S,D,j)=>{if(j)return S[F]=[j,NaN],j;if(j=S[F])return j[1]++,j[0];if((D=T.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((he,me=0)=>(he.mapState==="unmapped"||te(),me=qd(me),rt[me>>>0]=he,me))(S,D),S[F]=[D,1],D},t.webgpuUnregisterBuffer=(S)=>{let D=S[F];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Bd(D[0]),delete S[F])},t.webgpuGetBuffer=(S)=>ee(S),t.webgpuCreateDownloader=(S,D,j)=>{if((j=T.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let he=ee(j),me=16*Math.ceil(Number(D)/16);return async()=>{let K=he.createBuffer({size:me,usage:9});try{let Ae=he.createCommandEncoder();return Ae.copyBufferToBuffer(S,0,K,0,me),he.queue.submit([Ae.finish()]),await K.mapAsync(GPUMapMode.READ),K.getMappedRange().slice(0,D)}finally{K.destroy()}}},t.pe=(S,D)=>{var j=D.buffer;let he=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),S=ee(S),!m){var K=_o(g);m=ee(K)}let Ae=(K=m.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(Ae).set(new Uint8Array(j,he,me)),K.unmap(),(j=m.createCommandEncoder()).copyBufferToBuffer(K,0,S,0,D),m.queue.submit([j.finish()]),K.destroy()}},t.webnnInit=(u)=>{let h=u[0];[t.Pe,t.qe,t.webnnEnsureTensor,t.re,t.webnnDownloadTensor,t.Oe,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.qe,t.webnnUploadTensor=t.re,t.webnnRegisterMLContext=t.Oe,t.webnnOnRunStart=(m)=>h.onRunStart(m),t.webnnOnRunEnd=h.onRunEnd.bind(h),t.webnnOnReleaseSession=(m)=>{h.onReleaseSession(m)},t.webnnCreateMLTensorDownloader=(m,g)=>h.createMLTensorDownloader(m,g),t.webnnRegisterMLTensor=(m,g,x,T)=>h.registerMLTensor(m,g,x,T),t.webnnCreateMLContext=(m)=>h.createMLContext(m),t.webnnRegisterGraphInput=h.registerGraphInput.bind(h),t.webnnIsGraphInput=h.isGraphInput.bind(h),t.webnnRegisterGraphOutput=h.registerGraphOutput.bind(h),t.webnnIsGraphOutput=h.isGraphOutput.bind(h),t.webnnCreateTemporaryTensor=h.createTemporaryTensor.bind(h),t.webnnIsGraphInputOutputTypeSupported=h.isGraphInputOutputTypeSupported.bind(h)},O?t:new Promise((u,h)=>{w=u,v=h})}var Uh,Yf,tM=we(()=>{Uh=Xf,Yf=globalThis.self?.name?.startsWith("em-pthread"),Yf&&Xf()}),Fo,Ho,Kf,vt,jh,Us,Jf,Zf,Io,eh,Lo,Wh,Oo,qh,ti=we(()=>{ei(),Fo=typeof location>"u"?void 0:location.origin,Ho=import.meta.url>"file:"&&import.meta.url<"file;",Kf=()=>{if(Ho)return new URL(new URL("ort.webgpu.bundle.min.mjs",import.meta.url).href,Fo).href;return import.meta.url},vt=Kf(),jh=()=>{if(vt&&!vt.startsWith("blob:"))return vt.substring(0,vt.lastIndexOf("/")+1)},Us=(e,t)=>{try{let r=t??vt;return(r?new URL(e,r):new URL(e)).origin===Fo}catch{return!1}},Jf=(e,t)=>{let r=t??vt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Zf=(e,t)=>`${t??"./"}${e}`,Io=async(e)=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},eh=async(e)=>(await import(e)).default,Lo=(eM(),Qs($h)).default,Wh=async()=>{if(!vt)throw Error("Failed to load proxy worker: cannot determine the script source URL.");if(Us(vt))return[void 0,Lo()];let e=await Io(vt);return[e,Lo(e)]},Oo=(tM(),Qs(Vh)).default,qh=async(e,t,r,n)=>{let s=Oo&&!(e||t);if(s)if(vt)s=Us(vt)||n&&!r;else if(n&&!r)s=!0;else throw Error("cannot determine the script source URL.");if(s)return[void 0,Oo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Jf(a,t),i=r&&o&&!Us(o,t),l=i?await Io(o):o??Zf(a,t);return[i?l:void 0,await eh(l)]}}}),No,js,Kn,Do,th,rh,nh,ri,Le,Yr=we(()=>{ti(),js=!1,Kn=!1,Do=!1,th=()=>{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}},rh=()=>{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}},nh=()=>{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}},ri=async(e)=>{if(js)return Promise.resolve();if(Kn)throw Error("multiple calls to 'initializeWebAssembly()' detected.");if(Do)throw Error("previous call to 'initializeWebAssembly()' failed.");Kn=!0;let{initTimeout:t,numThreads:r}=e;if(e.simd!==!1){if(e.simd==="relaxed"){if(!nh())throw Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!rh())throw Error("WebAssembly SIMD is not supported in the current environment.")}let n=th();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,o=s?.mjs,i=o?.href??o,l=s?.wasm,c=l?.href??l,d=e.wasmBinary,[f,_]=await qh(i,a,r>1,!!d||!!c),p=!1,w=[];if(t>0&&w.push(new Promise((v)=>{setTimeout(()=>{p=!0,v()},t)})),w.push(new Promise((v,y)=>{let b={numThreads:r};if(d)b.wasmBinary=d,b.locateFile=(k)=>k;else if(c||a)b.locateFile=(k)=>c??a+k;else if(i&&i.indexOf("blob:")!==0)b.locateFile=(k)=>new URL(k,i).href;else if(f){let k=jh();k&&(b.locateFile=(A)=>k+A)}_(b).then((k)=>{Kn=!1,js=!0,No=k,v(),f&&URL.revokeObjectURL(f)},(k)=>{Kn=!1,Do=!0,y(k)})})),await Promise.race(w),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Le=()=>{if(js&&No)return No;throw Error("WebAssembly is not initialized yet.")}}),yt,Ys,ke,ni=we(()=>{Yr(),yt=(e,t)=>{let r=Le(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ys=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let o=t?t+s:s;if(typeof a=="object")Ys(a,o+".",r,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw Error(`Can't handle extra config type: ${typeof a}`)})},ke=(e)=>{let t=Le(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),o=t.getValue(s+n,"*"),i=o?t.UTF8ToString(o):"";throw Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),Hh,rM=we(()=>{Yr(),ni(),Hh=(e)=>{let t=Le(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let a=0;return e?.tag!==void 0&&(a=yt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&ke("Can't create run options."),e?.extra!==void 0&&Ys(e.extra,"",new WeakSet,(o,i)=>{let l=yt(o,n),c=yt(i,n);t._OrtAddRunConfigEntry(r,l,c)!==0&&ke(`Can't set a run config entry: ${o} - ${i}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach((o)=>t._free(o)),a}}}),sh,ah,oh,dn,Zt,ih,Qh,nM=we(()=>{Yr(),ni(),sh=(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 Error(`unsupported graph optimization level: ${e}`)}},ah=(e)=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw Error(`unsupported execution mode: ${e}`)}},oh=(e)=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((r)=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},dn=(e,t,r,n)=>{let s=yt(t,n),a=yt(r,n);Le()._OrtAddSessionConfigEntry(e,s,a)!==0&&ke(`Can't set a session config entry: ${t} - ${r}.`)},Zt=(e,t,r,n)=>{let s=yt(t,n),a=yt(r,n);e.push([s,a])},ih=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",dn(e,"session.disable_quant_qdq","1",r),dn(e,"session.disable_qdq_constant_folding","1",r),typeof s!="string"){let f=s?.deviceType;f&&dn(e,"deviceType",f,r)}break;case"webgpu":{a="WebGPU";let f;if(typeof s!="string"){let p=s;if(p.device)if(typeof GPUDevice<"u"&&p.device instanceof GPUDevice)f=p.device;else throw Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&Zt(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&Zt(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let v=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];Zt(o,"forceCpuNodeNames",v.join(`
|
|
10
|
+
`),r)}p.validationMode&&Zt(o,"validationMode",p.validationMode,r),typeof p.enableMatmulFp32Accumulation=="boolean"&&Zt(o,"enableMatmulFp32Accumulation",p.enableMatmulFp32Accumulation?"1":"0",r);for(let v of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let y=p[v];if(y){if(y!=="disabled"&&y!=="lazyRelease"&&y!=="simple"&&y!=="bucket")throw Error(`${v} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${y}`);Zt(o,v,y,r)}}}let _=Le().webgpuRegisterDevice(f);if(_){let[p,w,v]=_;Zt(o,"deviceId",p.toString(),r),Zt(o,"webgpuInstance",w.toString(),r),Zt(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw Error(`not supported execution provider: ${a}`)}let i=yt(a,r),l=o.length,c=0,d=0;if(l>0){c=Le()._malloc(l*Le().PTR_SIZE),r.push(c),d=Le()._malloc(l*Le().PTR_SIZE),r.push(d);for(let f=0;f<l;f++)Le().setValue(c+f*Le().PTR_SIZE,o[f][0],"*"),Le().setValue(d+f*Le().PTR_SIZE,o[f][1],"*")}await Le()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&ke(`Can't append execution provider: ${a}.`)}},Qh=async(e)=>{let t=Le(),r=0,n=[],s=e||{};oh(s);try{let a=sh(s.graphOptimizationLevel??"all"),o=ah(s.executionMode??"sequential"),i=typeof s.logId=="string"?yt(s.logId,n):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw Error(`log severity level is not valid: ${l}`);let c=s.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let d=typeof s.optimizedModelFilePath=="string"?yt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,c,d),r===0&&ke("Can't create session options."),s.executionProviders&&await ih(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);dn(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[f,_]of Object.entries(s.freeDimensionOverrides)){if(typeof f!="string")throw Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw Error(`free dimension override value must be a non-negative integer: ${_}`);let p=yt(f,n);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&ke(`Can't set a free dimension override: ${f} - ${_}.`)}return s.extra!==void 0&&Ys(s.extra,"",new WeakSet,(f,_)=>{dn(r,f,_,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&ke("Can't release session options."),n.forEach((o)=>t._free(o)),a}}}),Wr,Hs,hn,rs,Ks,si,ai,Qo,_n=we(()=>{Wr=(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 Error(`unsupported data type: ${e}`)}},Hs=(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 Error(`unsupported data type: ${e}`)}},hn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,0.5,0.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},rs=(e)=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Ks=(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 Error(`unsupported logging level: ${e}`)}},si=(e)=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ai=(e)=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Qo=(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 Error(`unsupported data location: ${e}`)}}}),oi,Xh=we(()=>{ei(),oi=async(e)=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(i){if(i instanceof RangeError){let l=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Yh,sM=we(()=>{_n(),Yh=(e,t)=>new(rs(t))(e)}),lh,ch,uh,dh,Kh,fh,pt,Jh=we(()=>{_n(),lh=["V","I","W","E","F"],ch=(e,t)=>{console.log(`[${lh[e]},${new Date().toISOString()}]${t}`)},Kh=(e,t)=>{uh=e,dh=t},fh=(e,t)=>{let r=Ks(e),n=Ks(uh);r>=n&&ch(r,typeof t=="function"?t():t)},pt=(...e)=>{dh&&fh(...e)}}),zo,hh,Bo,_h,Ro,ph,$o,Go,Vo,mh,Zh,aM=we(()=>{_n(),Jh(),zo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),hh=(e,t)=>{if(t==="int32")return e;let r=zo.get(t);if(!r)throw Error(`WebNN backend does not support data type: ${t}`);let n=r/8;if(e.byteLength%n!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(rs(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i<s;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw 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 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 Error(`Unsupported data conversion from ${t} to 'int32'`)}},Bo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some((a)=>a<0))throw Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some((a)=>a<-128||a>127))throw Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some((s)=>s<0||s>255))throw Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some((a)=>a<0))throw Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},_h=1,Ro=()=>_h++,ph=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),$o=(e,t)=>{let r=zo.get(e);if(!r)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},Go=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return $o(this.dataType,this.tensorShape)}destroy(){pt("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=Bo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return new Uint8Array(r).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},Vo=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=ph.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);pt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==$o(t,r))throw Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=hh(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else pt("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?Bo(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 Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},mh=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 Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Ro();return this.tensorTrackersById.set(e,new Vo(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n,s){pt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw Error("Tensor not found.");r.upload(t)}async download(e,t){pt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter((t)=>t.sessionId!==e)}registerTensor(e,t,r,n){let s=this.getMLContext(e),a=Ro(),o=new Go({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new Vo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){pt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=e,f}pt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new Go({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)}},Zh=(...e)=>new mh(...e)}),e_={};ns(e_,{WebNNBackend:()=>t_});var Jn,gh,t_,oM=we(()=>{_n(),Yr(),sM(),aM(),Jh(),Jn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),gh=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},t_=class{constructor(e){this.tensorManager=Zh(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,Kh(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error("No active session");return this.activeSessionId}onRunStart(e){pt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){pt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)pt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex((n)=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex((n)=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex((r)=>gh(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex((s)=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){pt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=Jn.get(r);if(!a)throw Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){pt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=Jn.get(t);if(!n)throw Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!Le().shouldTransferToMLTensor)throw Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");pt("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 Yh(r,t)}}registerMLTensor(e,t,r,n){let s=Jn.get(r);if(!s)throw Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return pt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=Jn.get(Wr(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),wh,ii,li,Mr,vh,Uo,Js,ci,ui,jo,di,fi,hi,r_=we(()=>{Xr(),rM(),nM(),_n(),Yr(),ni(),Xh(),wh=(e,t)=>{Le()._OrtInit(e,t)!==0&&ke("Can't initialize onnxruntime.")},ii=async(e)=>{wh(e.wasm.numThreads,Ks(e.logLevel))},li=async(e,t)=>{Le().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!r)throw 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 Error("WebNN is not supported in current environment");if(t==="webgpu"&&Le().webgpuInit((n)=>{e.webgpu.device=n}),t==="webnn"){let n=new(oM(),Qs(e_)).WebNNBackend(e);Le().webnnInit([n,()=>n.reserveTensorId(),(s)=>n.releaseTensorId(s),async(s,a,o,i,l)=>n.ensureTensor(s,a,o,i,l),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},Mr=new Map,vh=(e)=>{let t=Le(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&ke("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},Uo=(e,t)=>{let r=Le(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&ke("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));s=Number(r.getValue(o+a,"*"));let l=r.HEAP32[s/4];if(l===0)return[i,0];let c=r.HEAPU32[s/4+1],d=[];for(let f=0;f<c;f++){let _=Number(r.getValue(s+8+f*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(s+8+(f+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},Js=(e)=>{let t=Le(),r=t._malloc(e.byteLength);if(r===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},ci=async(e,t)=>{let r,n,s=Le();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Js(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await Qh(t),t?.externalData&&s.mountExternalData){let E=[];for(let C of t.externalData){let N=typeof C=="string"?C:C.path,M=typeof C=="string"?C:C.data;E.push(oi(M).then((G)=>{s.mountExternalData(N,G)}))}await Promise.all(E)}for(let E of t?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof E!="string"){let C=E,N=C?.context,M=C?.gpuDevice,G=C?.deviceType,R=C?.powerPreference;N?s.currentContext=N:M?s.currentContext=await s.webnnCreateMLContext(M):s.currentContext=await s.webnnCreateMLContext({deviceType:G,powerPreference:R})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&ke("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[f,_]=vh(a),p=!!t?.enableGraphCapture,w=[],v=[],y=[],b=[],k=[];for(let E=0;E<f;E++){let[C,N,M]=Uo(a,E);C===0&&ke("Can't get an input name."),c.push(C);let G=s.UTF8ToString(C);w.push(G),y.push(N===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Hs(N),shape:M})}for(let E=0;E<_;E++){let[C,N,M]=Uo(a,E+f);C===0&&ke("Can't get an output name."),d.push(C);let G=s.UTF8ToString(C);v.push(G),b.push(N===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Hs(N),shape:M});{if(p&&t?.preferredOutputLocation===void 0){k.push("gpu-buffer");continue}let R=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[G]??"cpu",q=s.webnnIsGraphOutput;if(R==="cpu"&&q&&q(a,G)){k.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw Error(`Not supported preferred output location: ${R}.`);if(p&&R!=="gpu-buffer")throw Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);k.push(R)}}let A=null;return k.some((E)=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&ke("Can't create IO binding."),A={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map((E)=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map((E)=>Qo(E))}),Mr.set(a,[a,c,d,A,p,!1]),[a,w,v,y,b]}catch(f){throw c.forEach((_)=>s._OrtFree(_)),d.forEach((_)=>s._OrtFree(_)),i!==0&&s._OrtReleaseBinding(i)!==0&&ke("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&ke("Can't release session."),f}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&ke("Can't release session options."),l.forEach((f)=>s._free(f)),s.unmountExternalData?.()}},ui=(e)=>{let t=Le(),r=Mr.get(e);if(!r)throw Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&ke("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ke("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach((l)=>t._OrtFree(l)),a.forEach((l)=>t._OrtFree(l)),t._OrtReleaseSession(n)!==0&&ke("Can't release session."),Mr.delete(e)},jo=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Le(),l=i.PTR_SIZE,c=e[0],d=e[1],f=e[3],_=f,p,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw Error("String tensor is not supported on GPU.");if(o&&f!=="gpu-buffer")throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let b=e[2].gpuBuffer;w=hn(Wr(c),d);{let k=i.webgpuRegisterBuffer;if(!k)throw Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=k(b,n)}}else if(f==="ml-tensor"){let b=e[2].mlTensor;w=hn(Wr(c),d);let k=i.webnnRegisterMLTensor;if(!k)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=k(n,b,Wr(c),d)}else{let b=e[2];if(Array.isArray(b)){w=l*b.length,p=i._malloc(w),r.push(p);for(let k=0;k<b.length;k++){if(typeof b[k]!="string")throw TypeError(`tensor data at index ${k} is not a string`);i.setValue(p+k*l,yt(b[k],r),"*")}}else{let{webnnIsGraphInput:k,webnnIsGraphOutput:A}=i;if(c!=="string"&&k&&A){let E=i.UTF8ToString(s);if(k(n,E)||A(n,E)){let C=Wr(c);w=hn(C,d),_="ml-tensor";let{webnnCreateTemporaryTensor:N,webnnUploadTensor:M}=i;if(!N||!M)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await N(n,C,d);M(G,new Uint8Array(b.buffer,b.byteOffset,b.byteLength)),p=G}else w=b.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(b.buffer,b.byteOffset,w),p)}else w=b.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(b.buffer,b.byteOffset,w),p)}}let v=i.stackSave(),y=i.stackAlloc(4*d.length);try{d.forEach((k,A)=>i.setValue(y+A*l,k,l===4?"i32":"i64"));let b=i._OrtCreateTensor(Wr(c),p,w,y,d.length,Qo(_));b===0&&ke(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(b)}finally{i.stackRestore(v)}},di=async(e,t,r,n,s,a)=>{let o=Le(),i=o.PTR_SIZE,l=Mr.get(e);if(!l)throw Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],f=l[2],_=l[3],p=l[4],w=l[5],v=t.length,y=n.length,b=0,k=[],A=[],E=[],C=[],N=[],M=o.stackSave(),G=o.stackAlloc(v*i),R=o.stackAlloc(v*i),q=o.stackAlloc(y*i),X=o.stackAlloc(y*i);try{[b,k]=Hh(a),kr("wasm prepareInputOutputTensor");for(let P=0;P<v;P++)await jo(r[P],A,C,e,d[t[P]],t[P],p);for(let P=0;P<y;P++)await jo(s[P],E,C,e,f[n[P]],v+n[P],p);Tr("wasm prepareInputOutputTensor");for(let P=0;P<v;P++)o.setValue(G+P*i,A[P],"*"),o.setValue(R+P*i,d[t[P]],"*");for(let P=0;P<y;P++)o.setValue(q+P*i,E[P],"*"),o.setValue(X+P*i,f[n[P]],"*");if(_&&!w){let{handle:P,outputPreferredLocations:Y,outputPreferredLocationsEncoded:ue}=_;if(d.length!==v)throw Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${d.length}).`);kr("wasm bindInputsOutputs");for(let Z=0;Z<v;Z++){let se=t[Z];await o._OrtBindInput(P,d[se],A[Z])!==0&&ke(`Can't bind input[${Z}] for session=${e}.`)}for(let Z=0;Z<y;Z++){let se=n[Z];s[Z]?.[3]?(N.push(E[Z]),o._OrtBindOutput(P,f[se],E[Z],0)!==0&&ke(`Can't bind pre-allocated output[${Z}] for session=${e}.`)):o._OrtBindOutput(P,f[se],0,ue[se])!==0&&ke(`Can't bind output[${Z}] to ${Y[Z]} for session=${e}.`)}Tr("wasm bindInputsOutputs"),Mr.set(e,[c,d,f,_,p,!0])}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let Q;_?Q=await o._OrtRunWithBinding(c,_.handle,y,q,b):Q=await o._OrtRun(c,R,G,v,X,y,q,b),Q!==0&&ke("failed to call OrtRun().");let H=[],B=[];kr("wasm ProcessOutputTensor");for(let P=0;P<y;P++){let Y=Number(o.getValue(q+P*i,"*"));if(Y===E[P]||N.includes(E[P])){H.push(s[P]),Y!==E[P]&&o._OrtReleaseTensor(Y)!==0&&ke("Can't release tensor.");continue}let ue=o.stackSave(),Z=o.stackAlloc(4*i),se=!1,L,O=0;try{o._OrtGetTensorData(Y,Z,Z+i,Z+2*i,Z+3*i)!==0&&ke(`Can't access output tensor data on index ${P}.`);let V=i===4?"i32":"i64",de=Number(o.getValue(Z,V));O=o.getValue(Z+i,"*");let te=o.getValue(Z+i*2,"*"),We=Number(o.getValue(Z+i*3,V)),Fe=[];for(let Oe=0;Oe<We;Oe++)Fe.push(Number(o.getValue(te+Oe*i,V)));o._OrtFree(te)!==0&&ke("Can't free memory for tensor dims.");let be=Fe.reduce((Oe,Me)=>Oe*Me,1);L=Hs(de);let Ge=_?.outputPreferredLocations[n[P]];if(L==="string"){if(Ge==="gpu-buffer"||Ge==="ml-tensor")throw Error("String tensor is not supported on GPU.");let Oe=[];for(let Me=0;Me<be;Me++){let Ye=o.getValue(O+Me*i,"*"),Xt=o.getValue(O+(Me+1)*i,"*"),xe=Me===be-1?void 0:Xt-Ye;Oe.push(o.UTF8ToString(Ye,xe))}H.push([L,Fe,Oe,"cpu"])}else if(Ge==="gpu-buffer"&&be>0){let Oe=o.webgpuGetBuffer;if(!Oe)throw Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Me=Oe(O),Ye=hn(de,be);if(Ye===void 0||!si(L))throw Error(`Unsupported data type: ${L}`);se=!0;{o.webgpuRegisterBuffer(Me,e,O);let Xt=o.webgpuCreateDownloader(Me,Ye,e);H.push([L,Fe,{gpuBuffer:Me,download:async()=>{let xe=await Xt();return new(rs(L))(xe)},dispose:()=>{o._OrtReleaseTensor(Y)!==0&&ke("Can't release tensor.")}},"gpu-buffer"])}}else if(Ge==="ml-tensor"&&be>0){let{webnnEnsureTensor:Oe,webnnIsGraphInputOutputTypeSupported:Me}=o;if(!Oe||!Me)throw Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(hn(de,be)===void 0||!ai(L))throw Error(`Unsupported data type: ${L}`);if(!Me(e,L,!1))throw Error(`preferredLocation "ml-tensor" for ${L} output is not supported by current WebNN Context.`);let Ye=await Oe(e,O,de,Fe,!1);se=!0,H.push([L,Fe,{mlTensor:Ye,download:o.webnnCreateMLTensorDownloader(O,L),dispose:()=>{o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Y)}},"ml-tensor"])}else if(Ge==="ml-tensor-cpu-output"&&be>0){let Oe=o.webnnCreateMLTensorDownloader(O,L)(),Me=H.length;se=!0,B.push((async()=>{let Ye=[Me,await Oe];return o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Y),Ye})()),H.push([L,Fe,[],"cpu"])}else{let Oe=rs(L),Me=new Oe(be);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(o.HEAPU8.subarray(O,O+Me.byteLength)),H.push([L,Fe,Me,"cpu"])}}finally{o.stackRestore(ue),L==="string"&&O&&o._free(O),se||o._OrtReleaseTensor(Y)}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&ke("Can't clear bound outputs."),Mr.set(e,[c,d,f,_,p,!1]));for(let[P,Y]of await Promise.all(B))H[P][2]=Y;return Tr("wasm ProcessOutputTensor"),H}finally{o.webnnOnRunEnd?.(c),o.stackRestore(M),r.forEach((Q)=>{Q&&Q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(Q[2].gpuBuffer)}),s.forEach((Q)=>{Q&&Q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(Q[2].gpuBuffer)}),A.forEach((Q)=>o._OrtReleaseTensor(Q)),E.forEach((Q)=>o._OrtReleaseTensor(Q)),C.forEach((Q)=>o._free(Q)),b!==0&&o._OrtReleaseRunOptions(b),k.forEach((Q)=>o._free(Q))}},fi=(e)=>{let t=Le(),r=Mr.get(e);if(!r)throw Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&ke("Can't get an profile file name."),t._OrtFree(s)},hi=(e)=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),xr,At,fn,Zn,es,Ws,Wo,qs,Vr,Ur,yh,n_,s_,a_,o_,i_,l_,c_,u_=we(()=>{Xr(),r_(),Yr(),ti(),xr=()=>!!Be.wasm.proxy&&typeof document<"u",fn=!1,Zn=!1,es=!1,qs=new Map,Vr=(e,t)=>{let r=qs.get(e);r?r.push(t):qs.set(e,[t])},Ur=()=>{if(fn||!Zn||es||!At)throw Error("worker not ready")},yh=(e)=>{switch(e.data.type){case"init-wasm":fn=!1,e.data.err?(es=!0,Wo[1](e.data.err)):(Zn=!0,Wo[0]()),Ws&&(URL.revokeObjectURL(Ws),Ws=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=qs.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},n_=async()=>{if(!Zn){if(fn)throw Error("multiple calls to 'initWasm()' detected.");if(es)throw Error("previous call to 'initWasm()' failed.");if(fn=!0,xr())return new Promise((e,t)=>{At?.terminate(),Wh().then(([r,n])=>{try{At=n,At.onerror=(a)=>t(a),At.onmessage=yh,Wo=[e,t];let s={type:"init-wasm",in:Be};!s.in.wasm.wasmPaths&&(r||Ho)&&(s.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),At.postMessage(s),Ws=r}catch(s){t(s)}},t)});try{await ri(Be.wasm),await ii(Be),Zn=!0}catch(e){throw es=!0,e}finally{fn=!1}}},s_=async(e)=>{if(xr())return Ur(),new Promise((t,r)=>{Vr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:Be}};At.postMessage(n)});await li(Be,e)},a_=async(e)=>xr()?(Ur(),new Promise((t,r)=>{Vr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};At.postMessage(n,[e.buffer])})):Js(e),o_=async(e,t)=>{if(xr()){if(t?.preferredOutputLocation)throw Error('session option "preferredOutputLocation" is not supported for proxy.');return Ur(),new Promise((r,n)=>{Vr("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),At.postMessage(s,a)})}else return ci(e,t)},i_=async(e)=>{if(xr())return Ur(),new Promise((t,r)=>{Vr("release",[t,r]);let n={type:"release",in:e};At.postMessage(n)});ui(e)},l_=async(e,t,r,n,s,a)=>{if(xr()){if(r.some((o)=>o[3]!=="cpu"))throw Error("input tensor on GPU is not supported for proxy.");if(s.some((o)=>o))throw Error("pre-allocated output tensor is not supported for proxy.");return Ur(),new Promise((o,i)=>{Vr("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};At.postMessage(c,hi(l))})}else return di(e,t,r,n,s,a)},c_=async(e)=>{if(xr())return Ur(),new Promise((t,r)=>{Vr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};At.postMessage(n)});fi(e)}}),qo,bh,d_,iM=we(()=>{Xr(),u_(),_n(),ei(),Xh(),qo=(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 Error(`invalid data location: ${e.location} for ${t()}`)}},bh=(e)=>{switch(e[3]){case"cpu":return new Nt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!si(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Nt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!ai(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Nt.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw Error(`invalid data location: ${e[3]}`)}},d_=class{async fetchModelAndCopyToWasmMemory(e){return a_(await oi(e))}async loadModel(e,t){Hr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await o_(r,t),Qr()}async dispose(){return i_(this.sessionId)}async run(e,t,r){Hr();let n=[],s=[];Object.entries(e).forEach((f)=>{let _=f[0],p=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw Error(`invalid input '${_}'`);n.push(p),s.push(w)});let a=[],o=[];Object.entries(t).forEach((f)=>{let _=f[0],p=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw Error(`invalid output '${_}'`);a.push(p),o.push(w)});let i=n.map((f,_)=>qo(f,()=>`input "${this.inputNames[s[_]]}"`)),l=a.map((f,_)=>f?qo(f,()=>`output "${this.outputNames[o[_]]}"`):null),c=await l_(this.sessionId,s,i,o,l,r),d={};for(let f=0;f<c.length;f++)d[this.outputNames[o[f]]]=a[f]??bh(c[f]);return Qr(),d}startProfiling(){}endProfiling(){c_(this.sessionId)}}}),f_={};ns(f_,{OnnxruntimeWebAssemblyBackend:()=>Yo,initializeFlags:()=>Xo,wasmBackend:()=>h_});var Xo,Yo,h_,lM=we(()=>{Xr(),u_(),iM(),Xo=()=>{(typeof Be.wasm.initTimeout!="number"||Be.wasm.initTimeout<0)&&(Be.wasm.initTimeout=0);let e=Be.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.`),Be.wasm.simd=!1),typeof Be.wasm.proxy!="boolean"&&(Be.wasm.proxy=!1),typeof Be.wasm.trace!="boolean"&&(Be.wasm.trace=!1),typeof Be.wasm.numThreads!="number"||!Number.isInteger(Be.wasm.numThreads)||Be.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Be.wasm.numThreads=1;else{let t=typeof navigator>"u"?R0("node:os").cpus().length:navigator.hardwareConcurrency;Be.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Yo=class{async init(e){Xo(),await n_(),await s_(e)}async createInferenceSessionHandler(e,t){let r=new d_;return await r.loadModel(e,t),r}},h_=new Yo});Xr();Xr();Xr();var cM="1.31.0-dev.20260914-8d85527a0",uM=Rh;{let e=(lM(),Qs(f_)).wasmBackend;qr("webgpu",e,5),qr("webnn",e,5),qr("cpu",e,10),qr("wasm",e,10)}Object.defineProperty(Be.versions,"web",{value:cM,enumerable:!0});var __="1.30.0";var p_="warning",pi={wasm:{},webgl:{},webgpu:{},versions:{common:__},set logLevel(e){if(e===void 0)return;if(typeof e!=="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);p_=e},get logLevel(){return p_}};Object.defineProperty(pi,"logLevel",{enumerable:!0});var m_=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;if(t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC")s=e.dims[2],a=e.dims[3];else s=e.dims[3],a=e.dims[2];let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;if(i===void 0||i.mean===void 0)l=[255,255,255,255];else if(typeof i.mean==="number")l=[i.mean,i.mean,i.mean,i.mean];else if(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0)l[3]=i.mean[3];if(i===void 0||i.bias===void 0)c=[0,0,0,0];else if(typeof i.bias==="number")c=[i.bias,i.bias,i.bias,i.bias];else if(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0)c[3]=i.bias[3];let d=a*s,f=0,_=d,p=d*2,w=-1;if(o==="RGBA")f=0,_=d,p=d*2,w=d*3;else if(o==="RGB")f=0,_=d,p=d*2;else if(o==="RBG")f=0,p=d,_=d*2;for(let v=0;v<a;v++)for(let y=0;y<s;y++){let b=(e.data[f++]-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];n.fillStyle="rgba("+b+","+k+","+A+","+E+")",n.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();else throw Error("toDataURL is not supported")}else throw Error("Can not access image data")},g_=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;if(t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC")s=e.dims[2],a=e.dims[1],o=e.dims[3];else s=e.dims[3],a=e.dims[2],o=e.dims[1];let i=t!==void 0?t.format!==void 0?t.format:"RGB":"RGB",l=t?.norm,c,d;if(l===void 0||l.mean===void 0)c=[255,255,255,255];else if(typeof l.mean==="number")c=[l.mean,l.mean,l.mean,l.mean];else if(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0)c[3]=l.mean[3];if(l===void 0||l.bias===void 0)d=[0,0,0,0];else if(typeof l.bias==="number")d=[l.bias,l.bias,l.bias,l.bias];else if(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0)d[3]=l.bias[3];let f=a*s;if(t!==void 0){if(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR")throw Error("Tensor format doesn't match input tensor dims")}let _=4,p=0,w=1,v=2,y=3,b=0,k=f,A=f*2,E=-1;if(i==="RGBA")b=0,k=f,A=f*2,E=f*3;else if(i==="RGB")b=0,k=f,A=f*2;else if(i==="RBG")b=0,A=f,k=f*2;n=r.createImageData(s,a);for(let C=0;C<a*s;p+=_,w+=_,v+=_,y+=_,C++)n.data[p]=(e.data[b++]-d[0])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[y]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw Error("Can not access image data");return n};var mi=(e,t)=>{if(e===void 0)throw Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,o;if(typeof s.mean==="number")a=[s.mean,s.mean,s.mean,s.mean];else a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255];if(typeof s.bias==="number")o=[s.bias,s.bias,s.bias,s.bias];else o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0?t.tensorFormat!==void 0?t.tensorFormat:"RGB":"RGB",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,p=1,w=2,v=3,y=0,b=c,k=c*2,A=-1;if(i==="RGB")f=3,_=0,p=1,w=2,v=-1;if(l==="RGBA")A=c*3;else if(l==="RBG")y=0,k=c,b=c*2;else if(l==="BGR")k=0,b=c,y=c*2;for(let C=0;C<c;C++,_+=f,w+=f,p+=f,v+=f)if(d[y++]=(e[_]+o[0])/a[0],d[b++]=(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 ct("float32",d,[1,4,r,n]):new ct("float32",d,[1,3,r,n])},w_=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e==="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");else if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);else throw Error("Canvas is not supported")},c=(d)=>{if(typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement)return d.getContext("2d");else if(d instanceof OffscreenCanvas)return d.getContext("2d");else return null};if(r){let d=l();d.width=e.width,d.height=e.height;let f=c(d);if(f!=null){let{height:_,width:p}=e;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0)_=t.resizedHeight,p=t.resizedWidth;if(t!==void 0){if(i=t,t.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");else i.tensorFormat="RGBA";i.height=_,i.width=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;f.drawImage(e,0,0),o=f.getImageData(0,0,p,_).data}else throw Error("Can not access image data")}else if(n){let d,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0)d=t.resizedHeight,f=t.resizedWidth;else d=e.height,f=e.width;if(t!==void 0)i=t;if(i.format="RGBA",i.height=d,i.width=f,t!==void 0){let _=l();_.width=f,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,f,d).data;else throw Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let f=c(d);if(f!=null){let{height:_,width:p}=e;return f.drawImage(e,0,0,p,_),o=f.getImageData(0,0,p,_).data,i.height=_,i.width=p,mi(o,i)}else throw Error("Can not access image data")}else if(a)return new Promise((d,f)=>{let _=l(),p=c(_);if(!e||!p)return f();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(mi(v.data,i))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(o!==void 0)return mi(o,i);else throw Error("Input data provided is not supported - aborted tensor creation")},v_=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t;return new ct({location:"texture",type:"float32",texture:e,dims:[1,n,r,4],download:s,dispose:a})},y_=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new ct({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},b_=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new ct({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},M_=(e,t,r)=>new ct({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]});var Kr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ss=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),x_=!1,k_=()=>{if(!x_){x_=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;if(e)Kr.set("int64",BigInt64Array),ss.set(BigInt64Array,"int64");if(t)Kr.set("uint64",BigUint64Array),ss.set(BigUint64Array,"uint64");if(n)Kr.set("float16",r),ss.set(r,"float16");else Kr.set("float16",Uint16Array)}};var T_=(e)=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!=="number"||!Number.isSafeInteger(n))throw TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},E_=(e,t)=>{switch(e.location){case"cpu":return new ct(e.type,e.data,t);case"cpu-pinned":return new ct({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ct({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ct({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new ct({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};class ct{constructor(e,t,r){k_();let n,s;if(typeof e==="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let o=Kr.get(n);if(!o)throw TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e==="string")if(n=e,i=r,e==="string"){if(!Array.isArray(t))throw TypeError("A string tensor's data must be a string array.");o=t}else{let l=Kr.get(e);if(l===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t))if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);else if(e==="uint64"||e==="int64")o=l.from(t,BigInt);else 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 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 TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",o=e;else if(l==="boolean")n="bool",o=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let l=ss.get(e.constructor);if(l===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw TypeError("A tensor's dims must be a number array");s=i,this.cpuData=o,this.dataLocation="cpu"}let a=T_(s);if(this.cpuData&&a!==this.cpuData.length)if((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length);else throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return w_(e,t)}static fromTexture(e,t){return v_(e,t)}static fromGpuBuffer(e,t){return y_(e,t)}static fromMLTensor(e,t){return b_(e,t)}static fromPinnedBuffer(e,t,r){return M_(e,t,r)}toDataURL(e){return m_(this,e)}toImageData(e){return g_(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw 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 Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();if(this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer)this.disposer(),this.disposer=void 0;return t}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error("The current tensor is being downloaded.");if(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 Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return E_(this,e)}}var gi=ct;var __dirname="/home/runner/work/murmur/murmur/node_modules/@huggingface/transformers/dist",dM=Object.defineProperty,hs=(e,t)=>{for(var r in t)dM(e,r,{get:t[r],enumerable:!0})},kt={},rr={},fM={},hM="4.3.2",qi=typeof self<"u",xn=!zp(kt),Op=!zp(rr),ca=qi&&"caches"in self,_M=typeof globalThis.Deno<"u",qz=typeof globalThis.Bun<"u",Ta=_M&&ca&&!xn,Np=typeof process<"u",Dp=Np&&process?.release?.name==="node"&&!Ta,Hi=typeof window<"u"&&typeof window.document<"u",Qi=qi&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),pM=Hi||Qi||Ta,mM=Dp||typeof navigator<"u"&&"gpu"in navigator,gM=typeof navigator<"u"&&"ml"in navigator,wM=typeof crypto<"u"&&typeof crypto.getRandomValues==="function",vM=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id==="string",yM=typeof ServiceWorkerGlobalScope<"u"&&qi&&self instanceof ServiceWorkerGlobalScope,bM=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgent;if(!((navigator.vendor||"").indexOf("Apple")>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android")))return!1;let r=e.match(/Version\/(\d+)/);return r?parseInt(r[1],10)<26:!1},MM=bM(),pe=Object.freeze({IS_BROWSER_ENV:Hi,IS_WEBWORKER_ENV:Qi,IS_WEB_ENV:pM,IS_SERVICE_WORKER_ENV:yM,IS_DENO_WEB_RUNTIME:Ta,IS_WEB_CACHE_AVAILABLE:ca,IS_WEBGPU_AVAILABLE:mM,IS_WEBNN_AVAILABLE:gM,IS_SAFARI_BELOW_26:MM,IS_PROCESS_AVAILABLE:Np,IS_NODE_ENV:Dp,IS_FS_AVAILABLE:xn,IS_PATH_AVAILABLE:Op,IS_CRYPTO_AVAILABLE:wM,IS_CHROME_AVAILABLE:vM}),Xi=xn&&Op,ua="./";if(Xi){let e=import.meta.url;if(e)ua=rr.dirname(rr.dirname(fM.fileURLToPath(e)));else if(typeof __dirname<"u")ua=rr.dirname(__dirname)}var xM=Xi?rr.join(ua,"/.cache/"):null,A_="/models/",kM=Xi?rr.join(ua,A_):A_,TM=typeof globalThis.fetch==="function"?globalThis.fetch.bind(globalThis):void 0,zt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),C_=zt.WARNING,ve={version:hM,backends:{onnx:{}},get logLevel(){return C_},set logLevel(e){C_=e,ve.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Hi||Qi||Ta),localModelPath:kM,useFS:xn,useBrowserCache:ca,useFSCache:xn,cacheDir:xM,useCustomCache:!1,customCache:null,useWasmCache:ca||xn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:TM};function zp(e){return Object.keys(e).length===0}var mt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Pr(e,t){if(e)e(t)}var da=class extends mt{constructor(e,t){super();this.callback=e,this.files_loading=t,this.loads=new Map}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((s,a)=>s+a.loaded,0),r=Object.values(this.files_loading).reduce((s,a)=>s+a.total,0),n=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function EM(e){return Number.isInteger(e)||typeof e==="bigint"}function S_(e){return e===null||e===void 0||e===-1}function P_(e){let t=[],r=e;while(Array.isArray(r))t.push(r.length),r=r[0];return t}function Bt(...e){return Array.prototype.concat.apply([],e)}function AM(...e){return e.reduce((t,r)=>t.flatMap((n)=>r.map((s)=>[n,s])))}function fa(e,t){return Math.abs((e+t)%(2*t)-t)}function et(e,t){return Object.assign({},...t.map((r)=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function CM(e,t){let r=0;for(let n of e)if(n===t)++r;return r}var ce={error(...e){if(ve.logLevel<=zt.ERROR)console.error(...e)},warn(...e){if(ve.logLevel<=zt.WARNING)console.warn(...e)},info(...e){if(ve.logLevel<=zt.INFO)console.log(...e)},debug(...e){if(ve.logLevel<=zt.DEBUG)console.log(...e)},log(...e){this.info(...e)}},SM=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let r of e){let n=t;for(let s=0;s<r.length;++s){let a=r[s];n=n[a]??=Object.create(null)}n.end=r}return t}split(e){let t=[],r=e.length,n=0,s=0;while(s<r){let a=this.trie,o=null,i=s;while(i<r&&(a=a[e[i]])){if(a.end)o=a.end;++i}if(o){if(s>n)t.push(e.slice(n,s));t.push(o),s+=o.length,n=s}else++s}if(n<r)t.push(e.slice(n));return t}},F_=SM,PM=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}},FM=PM,Bp=(e,t)=>{try{return new RegExp(e,t)}catch(r){if(!(r instanceof SyntaxError))throw r;let n=new Map,s=e.replace(/(\\[pP])\{([^}=]+)\}/g,(a,o,i,l)=>{let c=0;for(let f=l-1;f>=0&&e[f]==="\\";--f)++c;if(c%2===1)return a;let d=n.get(i);if(d===void 0){try{new RegExp(`\\p{${i}}`,"u"),d=i}catch{d=`Script=${i}`}n.set(i,d)}return`${o}{${d}}`});if(s===e)throw r;try{return new RegExp(s,t)}catch{throw r}}},Yi=(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"),Ea=(e,t=!0)=>{if(e.Regex!==void 0){let r=QM(WM(e.Regex));return Bp(r,"gu")}else if(e.String!==void 0){let r=XM(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},Cn="\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}",Rp=`${Cn}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,nr=`[${Rp}]`,$p=`[^${Rp}]`,IM=`(?:(?<!${nr})(?=${nr})|(?<=${nr})(?!${nr}))`,LM=`(?:(?<!${nr})(?!${nr})|(?<=${nr})(?=${nr}))`,OM="(?:(?<![\\s\\S])|(?<=\\n))",NM="(?:(?=\\n)|(?![\\s\\S]))",ls="0-9A-Fa-f",DM=new Map([["A","(?<![\\s\\S])"],["z","(?![\\s\\S])"],["Z","(?=\\n?(?![\\s\\S]))"],["h",`[${ls}]`],["H",`[^${ls}]`],["w",nr],["W",$p],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["b",IM],["B",LM],["a","\\x07"],["e","\\x1B"]]),zM=new Map([["h",ls],["w",Cn],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["a","\\x07"],["e","\\x1B"]]),BM=new Map([["W",`[^${Cn}]`],["H",`[^${ls}]`]]),Gp=new Map([[`
|
|
11
|
+
`,"\\n"],["\r","\\r"],["\t","\\t"],["\f","\\f"],["\v","\\v"]]),RM=new Map([["alpha","\\p{Alphabetic}"],["alnum","\\p{Alphabetic}\\p{Nd}"],["digit","\\p{Nd}"],["lower","\\p{Lowercase}"],["upper","\\p{Uppercase}"],["space","\\p{White_Space}"],["blank","\\t\\p{Zs}"],["punct","\\p{P}\\p{S}"],["cntrl","\\p{Cc}"],["word",Cn],["xdigit",ls]]),Vp="^$\\.*+?()[]{}|/",$M=/^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,Up=/^\\([pPxu])\{([^}]*)\}/,GM=/^\{(\d+(?:,\d*)?|,\d+)\}/,VM=/^\[:(\^?)(\p{Alphabetic}+):\]/u,UM=/^\[:\^:\]/,jM=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,jp=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,Wp=(e)=>e>="A"&&e<="Z"||e>="a"&&e<="z",ha=(e,t)=>String.fromCodePoint(e.codePointAt(t)),I_=(e)=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let r=String.fromCharCode(t);return Wp(r)?`[${r.toLowerCase()}${r.toUpperCase()}]`:null},WM=(e)=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,"[^()|\\s$1]"),qp="[\\s\\S]",L_=256,O_=()=>({fragment:"",alternatives:[],tail:null,contains_complex_set:!1}),Ki=(e)=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},_a=(e,t,r,n=!0)=>{if(e.tail==="range")Ki(r);e.alternatives.push(t),e.tail="set",e.contains_complex_set=e.contains_complex_set||n},Fr=(e,t,r=!1,n=-1)=>{if(r&&e.tail==="range")Ki(n);if(e.tail==="range"){e.fragment+=t,e.tail="complete_range";return}e.fragment+=t,e.tail=r?"set":"scalar",e.contains_complex_set=e.contains_complex_set||r},qM=(e,t,r)=>{let n=Up.exec(e.slice(t));if(n){let[_,p,w]=n;if(p==="P"&&w==="Word")_a(r,`[^${Cn}]`,t);else{let v=p==="x"?`\\u{${w}}`:p==="p"&&w==="Word"?Cn:_;Fr(r,v,p==="p"||p==="P",t)}return t+_.length}let s=jp.exec(e.slice(t));if(s)return Fr(r,s[0]),t+s[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=ha(e,t+1),o=t+1+a.length,i=Gp.get(a);if(i!==void 0)return Fr(r,i),o;let l=BM.get(a);if(l!==void 0)return _a(r,l,t),o;let c=zM.get(a),d,f=!1;if(c!==void 0)d=c,f=a!=="a"&&a!=="e";else if(/[A-Za-z0-9]/.test(a))d=`\\${a}`;else if(Vp.includes(a)||a==="-")d=`\\${a}`;else d=a;return Fr(r,d,f,t),o},Hp=(e)=>{if(e.length===1)return e[0];return`(?:(?=(?:${e.join("|")}))${qp})`},N_=(e)=>{let t=e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives];return Hp(t)},HM=(e)=>{let t=Bp(`^(?:${e})$`,"u"),r="";for(let n=0;n<26;++n){let s=String.fromCharCode(65+n),a=String.fromCharCode(97+n),o=t.test(s),i=t.test(a);if(o!==i)r+=o?a:s}return r},Qp=(e,t,r,n=!0,s=1)=>{if(s>L_)throw SyntaxError(`Maximum character-class nesting depth of ${L_} exceeded at index ${t}`);let a=t+1,o=e[a]==="^";if(o)++a;let i=a,l=[O_()],c=l[0],d=!1;while(a<e.length){let f=ha(e,a);if(f==="\\"){a=qM(e,a,c);continue}if(f==="]"){if(a===i){Fr(c,"\\]"),++a;continue}if(c.tail===null){if(l.length>1)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);throw SyntaxError(`Empty character class at index ${t}`)}let _=l.some((k)=>k.contains_complex_set);if(o&&l.length>1&&d)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let p=N_(l[0]),w=p;if(l.length>1){let k="";for(let A=1;A<l.length;++A)k+=`(?=${N_(l[A])})`;w=`(?:${k}${p})`}let v=l.length===1&&c.alternatives.length===0,y=c.fragment;if(r&&n){let k=HM(w);if(k.length>0)if(v)y+=k,w=`[${y}]`;else w=Hp([w,`[${k}]`])}return{atom:o?v?`[^${y}]`:`(?:(?!${w})${qp})`:w,end:a+1,negated:o,contains_complex_set:_,contains_nested_negated_complex_set:d}}if(e.startsWith("&&",a)){if(c.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);c=O_(),l.push(c),a+=2;continue}if(f==="["){let _=e.slice(a);if(UM.test(_))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let p=VM.exec(_);if(p){let[,v,y]=p,b=RM.get(y);if(b===void 0)throw SyntaxError(`Unsupported POSIX character class "${y}" at index ${a}`);if(r&&v&&(y==="lower"||y==="upper"))throw SyntaxError(`Unsupported negated POSIX ${y} class inside an inline case-insensitive group`);if(v)_a(c,`[^${b}]`,a);else Fr(c,b,!0,a);a+=p[0].length;continue}if(jM.test(_))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let w=Qp(e,a,r,!1,s+1);_a(c,w.atom,a,w.contains_complex_set),d||=w.contains_nested_negated_complex_set||w.negated&&w.contains_complex_set,a=w.end;continue}if(f==="-"){let _=e[a+1]==="]"||e.startsWith("&&",a+1);if(c.tail==="set"&&!_)Ki(a);if(c.tail===null||c.tail==="range"||c.tail==="complete_range"||_)Fr(c,"\\-");else c.fragment+="-",c.tail="range";++a;continue}Fr(c,f==="^"&&c.fragment.length===0?"\\^":f),a+=f.length}throw SyntaxError(`${l.length>1?"Unterminated character-class intersection":"Unterminated character class"} at index ${t}`)},QM=(e)=>{let t="",r=-1,n=!1,s=!1,a=[],o=(i)=>{r=t.length,t+=i,n=!1};for(let i=0;i<e.length;){let l=ha(e,i);if(l==="\\"){let c=Up.exec(e.slice(i));if(c){let[v,y,b]=c,k=v;if(y==="x"){let A=`\\u{${b}}`;k=s?I_(b)??A:A}else if(b==="Word")k=y==="p"?nr:$p;o(k),i+=v.length;continue}let d=jp.exec(e.slice(i));if(d){let v=d[0],y=s&&v[1]!=="c"?I_(v.slice(2))??v:v;o(y),i+=v.length;continue}if(i+1>=e.length){t+=l;break}let f=ha(e,i+1);if(i+=1+f.length,f==="G")continue;let _=Gp.get(f);if(_!==void 0){o(_);continue}let p=DM.get(f),w;if(p!==void 0)w=p;else if(/[A-Za-z0-9]/.test(f))w=`\\${f}`;else if(Vp.includes(f))w=`\\${f}`;else w=f;o(w);continue}switch(l){case"[":{let c=Qp(e,i,s);o(c.atom),i=c.end;continue}case"]":o("\\]"),++i;continue;case".":o("[^\\n]"),++i;continue;case"^":o(OM),++i;continue;case"$":o(NM),++i;continue;case"(":{let c=e.startsWith("(?i:",i),d=c?"(?i:":$M.exec(e.slice(i))?.[0]??"(",f=c?"(?:":d==="(?>"?"(?:":d;if(a.push([t.length,s]),c)s=!0;t+=f,n=!1,i+=d.length;continue}case")":t+=l,[r,s]=a.pop()??[-1,!1],n=!1,++i;continue;case"|":t+=l,r=-1,n=!1,++i;continue;case"{":{let c=GM.exec(e.slice(i));if(!c||r<0){o("\\{"),++i;continue}let d=c[1].startsWith(",")?`0${c[1]}`:c[1];i+=c[0].length;let f=e[i];if(f==="+"||f==="*")t=`${t.slice(0,r)}(?:${t.slice(r)}{${d}})${f}`,++i;else t+=`{${d}}`;n=!0;continue}case"}":o("\\}"),++i;continue;case"+":if(n){++i;continue}t+=l,n=!0,++i;continue;case"*":case"?":t+=l,n=!0,++i;continue;default:o(s&&Wp(l)?`[${l.toLowerCase()}${l.toUpperCase()}]`:l),i+=l.length;continue}}return t},XM=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),YM=(e,t,r)=>{let n=[],s=0;while(s<e.length){if(n.push(e[s]),(t.get(e[s])??r)!==r){++s;continue}while(++s<e.length&&(t.get(e[s])??r)===r)if(t.get(n.at(-1))!==r)n[n.length-1]+=e[s]}return n},KM=(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,JM=(e)=>Number.isInteger(e)||typeof e==="bigint",ZM=(e)=>{let t=0;for(let r of e)++t;return t},ex=(e)=>Xp(e.toLowerCase()),Rt=(...e)=>Array.prototype.concat.apply([],e),Ji=(e)=>new Map(Object.entries(e)),tx=(e,t)=>{let r=[],n=0;for(let s of e.matchAll(t)){let a=s[0];if(n<s.index)r.push(e.slice(n,s.index));if(a.length>0)r.push(a);n=s.index+a.length}if(n<e.length)r.push(e.slice(n));return r},Xp=(e)=>e.replace(/\p{M}/gu,""),D_=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!=="object")return`${t} must be a valid object`;for(let n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},rx=(e)=>e.match(/\S+/g)||[],nx=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},_s=nx,sx=class extends _s{constructor(e){super();this.config=e}_call(e){return this.normalize(e)}},mr=sx,ax=class extends mr{tokenize_chinese_chars(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r],s=n.charCodeAt(0);if(KM(s))t.push(" "),t.push(n),t.push(" ");else t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case"\t":case`
|
|
12
|
+
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let r of e){let n=r.charCodeAt(0);if(n===0||n===65533||this.is_control(r))continue;if(/^\s$/.test(r))t.push(" ");else t.push(r)}return t.join("")}normalize(e){if(this.config.clean_text)e=this.clean_text(e);if(this.config.handle_chinese_chars)e=this.tokenize_chinese_chars(e);if(this.config.lowercase){if(e=e.toLowerCase(),this.config.strip_accents!==!1)e=this.strip_accents(e)}else if(this.config.strip_accents)e=this.strip_accents(e);return e}},ox=ax,ix=class extends mr{constructor(e){super(e);this.charsmap=e.precompiled_charsmap??null}normalize(e){if(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("~");else e=e.normalize("NFKC");return e}},lx=ix,cx=class extends mr{constructor(e){super(e);this.normalizers=(e.normalizers??[]).map((t)=>Yp(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},ux=cx,dx=class extends mr{constructor(e){super(e);this.pattern=Ea(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??"")}},fx=dx,hx=class extends mr{constructor(){super(...arguments);this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Aa=hx,_x=class extends Aa{constructor(){super(...arguments);this.form="NFC"}},px=_x,mx=class extends Aa{constructor(){super(...arguments);this.form="NFD"}},gx=mx,wx=class extends Aa{constructor(){super(...arguments);this.form="NFKC"}},vx=wx,yx=class extends Aa{constructor(){super(...arguments);this.form="NFKD"}},bx=yx,Mx=class extends mr{normalize(e){if(this.config.strip_left&&this.config.strip_right)e=e.trim();else{if(this.config.strip_left)e=e.trimStart();if(this.config.strip_right)e=e.trimEnd()}return e}},xx=Mx,kx=class extends mr{normalize(e){return Xp(e)}},Tx=kx,Ex=class extends mr{normalize(e){return e.toLowerCase()}},Ax=Ex,Cx=class extends mr{normalize(e){return e=this.config.prepend+e,e}},Sx=Cx;function Px(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new ox(e);case"Precompiled":return new lx(e);case"Sequence":return new ux(e);case"Replace":return new fx(e);case"NFC":return new px(e);case"NFD":return new gx(e);case"NFKC":return new vx(e);case"NFKD":return new bx(e);case"Strip":return new xx(e);case"StripAccents":return new Tx(e);case"Lowercase":return new Ax(e);case"Prepend":return new Sx(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var Yp=Px,Fx=class extends _s{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)}},jt=Fx,Kp=(()=>{let e=[...Array.from({length:94},(s,a)=>a+33),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(s,a)=>a+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(s,a)=>a+"®".charCodeAt(0))],t=e.slice(),r=0;for(let s=0;s<256;++s)if(!e.includes(s))e.push(s),t.push(256+r),r+=1;let n=t.map((s)=>String.fromCharCode(s));return Object.fromEntries(e.map((s,a)=>[s,n[a]]))})(),Ix=(e)=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),Lx=Ix(Kp),pa="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Ox=class extends jt{constructor(e){super();this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Kp,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){if(this.add_prefix_space&&!e.startsWith(" "))e=" "+e;return(this.use_regex?e.match(this.pattern)||[]:[e]).map((n)=>Array.from(this.text_encoder.encode(n),(s)=>this.byte_encoder[s]).join(""))}},Nx=Ox,Dx=class extends jt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},zx=Dx,Bx=class extends jt{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){let{section_index:r=void 0}=t??{},n=e.replaceAll(" ",this.str_rep);if(!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0))n=this.str_rep+n;return[n]}},Rx=Bx,$x=class extends jt{constructor(e){super();this.config=e,this.pattern=Ea(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){if(this.pattern===null)return[];if(this.config.invert)return(e.match(this.pattern)||[]).filter((t)=>t);else if(this.config.behavior?.toLowerCase()==="removed")return e.split(this.pattern).filter((t)=>t);else return tx(e,this.pattern)}},Gx=$x,Vx=class extends jt{constructor(e){super();this.config=e,this.pattern=new RegExp(`[^${pa}]+|[${pa}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Ux=Vx,jx=class extends jt{constructor(e){super();this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Wx=jx,qx=class extends jt{constructor(){super();this.pattern=new RegExp(`[^\\s${pa}]+|[${pa}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Hx=qx,Qx=class extends jt{constructor(e){super();this.config=e,this.pattern=Ea(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){if(this.pattern===null)return[e];return[e.replaceAll(this.pattern,this.config.content??"")]}},Xx=Qx,Yx=class extends jt{constructor(e){super();this.tokenizers=(e.pretokenizers??[]).map((t)=>Jp(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},Kx=Yx,Jx=class extends jt{pre_tokenize_text(e){return rx(e)}},Zx=Jx,e1=class extends jt{constructor(e){super();this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},t1=e1;function r1(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new Hx;case"Sequence":return new Kx(e);case"Whitespace":return new zx;case"WhitespaceSplit":return new Zx;case"Metaspace":return new Rx(e);case"ByteLevel":return new Nx(e);case"Split":return new Gx(e);case"Punctuation":return new Ux(e);case"Digits":return new Wx(e);case"Replace":return new Xx(e);case"FixedLength":return new t1(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}var Jp=r1,n1=class extends _s{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);if(this.fuse_unk)t=YM(t,this.tokens_to_ids,this.unk_token_id);return t}},Ca=n1,s1=class extends Ca{constructor(e){super(e);this.max_input_chars_per_word=100,this.tokens_to_ids=Ji(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=Array(this.tokens_to_ids.size);for(let[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){let t=[];for(let r of e){let n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0,o=[];while(a<n.length){let i=n.length,l=null;while(a<i){let c=n.slice(a,i).join("");if(a>0)c=this.config.continuing_subword_prefix+c;if(this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){s=!0;break}o.push(l),a=i}if(s)t.push(this.unk_token);else t.push(...o)}return t}},z_=s1,B_=class e{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new e(!1,new Map)}},a1=class{constructor(){this.root=B_.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let n=t.children.get(r);if(n===void 0)n=B_.default(),t.children.set(r,n);t=n}t.is_leaf=!0}*common_prefix_search(e,t=0){let r=this.root;if(r===void 0)return;let n="";for(let s=t;s<e.length;++s){let a=e[s];if(n+=a,r=r.children.get(a),r===void 0)return;if(r.is_leaf)yield n}}},o1=a1,wi=class e{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},i1=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},()=>[]);let n=new wi(this.bos_token_id??0,0,0,0,0),s=new wi(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(e,t,r,n){let s=this.nodes.length,a=new wi(n,s,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;while(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]){let d=c.backtrace_score+o.score;if(l===null||d>i)l=c.clone(),i=d}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}let r=[],s=this.begin_nodes[e][0].prev;if(s===null)return[];let a=s.clone();while(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)}},l1=i1;function c1(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)if(e[n]<t)t=e[n],r=n;return[t,r]}var u1=class extends Ca{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=Array(r),this.scores=Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=c1(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new o1,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,r=1,n=0;while(n<t.length){let s=!1,a=this.trie.common_prefix_search(t,n);for(let o of a){let i=this.tokens_to_ids.get(o),l=this.scores[i],c=ZM(o);if(e.insert(n,c,l,i),!s&&c===1)s=!0}if(!s)e.insert(n,1,this.unk_score,this.unk_token_id);n+=1}}tokenize(e){let t=new l1(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let n=this.tokenize(r);t.push(...n)}return t}},R_=u1,d1=class{constructor(e=(r,n)=>r>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let r=this._smallest();if(this._comparator(t,this._heap[r]))this._heap[r]=t,this._sift_up_from(r)}return this.size}pop(){let e=this.peek(),t=this.size-1;if(t>0)this._swap(0,t);return this._heap.pop(),this._sift_down(),e}replace(e){let 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){let 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){while(e>0&&this._greater(e,this._parent(e)))this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;while(this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e)){let 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}},f1=d1,h1=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);if(this.cache.set(e,t),this.cache.size>this.capacity)this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},_1=h1,p1=class extends Ca{constructor(e){super(e);this.tokens_to_ids=Ji(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let t=Array.isArray(e.merges[0]);if(this.merges=t?e.merges:e.merges.map((r)=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback)this.text_encoder=new TextEncoder;this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new _1(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);if(this.end_of_word_suffix)r[r.length-1]+=this.end_of_word_suffix;let n=[];if(r.length>1){let s=new f1((i,l)=>i.score<l.score),a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(s,o),o=l}while(!s.is_empty()){let i=s.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let c={...i.prev};if(i.prev.deleted=!0,i.prev=c,c.prev)c.prev.next=c;else a=c}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};if(l.prev)l.prev.next=l,this.add_node(s,l.prev);else a=l;if(l.next)l.next.prev=l,this.add_node(s,l)}for(let i=a;i!==null;i=i.next)n.push(i.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;if(e.length<this.max_length_to_cache)this.cache.put(e,n);return n}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));if(r!==void 0)t.score=r+t.bias,e.push(t)}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){let a=Array.from(this.text_encoder.encode(s)).map((o)=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);if(a.every((o)=>this.tokens_to_ids.has(o)))t.push(...a);else if(this.unk_token!=null)t.push(this.unk_token)}else if(this.unk_token!=null)t.push(this.unk_token)}return t}},$_=p1,m1=class extends Ca{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=Ji(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=Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(e){return e}},g1=m1;function w1(e,t){switch(e.type){case"WordPiece":return new z_(e);case"Unigram":return new R_(e,t.eos_token);case"BPE":return new $_(e);default:if(e.vocab)if(Array.isArray(e.vocab))return new R_(e,t.eos_token);else if(Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token"))if(Object.hasOwn(e,"merges"))return new $_(e);else return new z_(e);else return new g1(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 Error(`Unknown TokenizerModel type: ${e?.type}`)}}var v1=w1,y1=class extends _s{constructor(e){super();this.config=e}_call(e,...t){return this.post_process(e,...t)}},ps=y1,b1=class extends ps{post_process(e,t=null,r=!0){let n=t===null?this.config.single:this.config.pair,s=[],a=[];for(let o of n)if("SpecialToken"in o){if(r)s.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)}else if("Sequence"in o){if(o.Sequence.id==="A")s=Rt(s,e),a=Rt(a,Array(e.length).fill(o.Sequence.type_id));else if(o.Sequence.id==="B")s=Rt(s,t),a=Rt(a,Array(t.length).fill(o.Sequence.type_id))}return{tokens:s,token_type_ids:a}}},M1=b1,x1=class extends ps{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},k1=x1,T1=class extends ps{constructor(e){super(e);this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){if(r)e=Rt([this.cls[0]],e,[this.sep[0]]);let n=Array(e.length).fill(0);if(t){let s=[],a=r?[this.sep[0]]:[];e=Rt(e,s,t,a),n=Rt(n,Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},E1=T1,A1=class extends ps{constructor(e){super(e);this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){if(r)e=Rt([this.cls[0]],e,[this.sep[0]]);let n=Array(e.length).fill(0);if(t){let s=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Rt(e,s,t,a),n=Rt(n,Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},C1=A1,S1=class extends ps{constructor(e){super(e);this.processors=(e.processors??[]).map((t)=>Zp(t))}post_process(e,t=null,r=!0){let n={tokens:e,tokens_pair:t};for(let s of this.processors)n=s.post_process(n.tokens,n.tokens_pair,r);return n}},P1=S1;function F1(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new M1(e);case"ByteLevel":return new k1(e);case"BertProcessing":return new E1(e);case"RobertaProcessing":return new C1(e);case"Sequence":return new P1(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var Zp=F1,I1=class extends _s{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("")}},Wt=I1,L1=class extends Wt{constructor(e){super(e);this.byte_decoder=Lx,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map((n)=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let n of e)if(this.added_tokens.find((s)=>s.content===n)!==void 0){if(r.length>0)t.push(this.convert_tokens_to_string(r)),r=[];t.push(n)}else r.push(n);if(r.length>0)t.push(this.convert_tokens_to_string(r));return t}},O1=L1,N1=class extends Wt{constructor(e){super(e);this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){let n=this.config.prefix;if(n&&t.startsWith(n))t=t.replace(n,"");else t=" "+t}if(this.cleanup)t=Yi(t);return t})}},D1=N1,z1=class extends Wt{constructor(e){super(e);this.replacement=e.replacement??"▁"}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");if(r==0&&n.startsWith(" "))n=n.substring(1);t.push(n)}return t}},B1=z1,R1=class extends Wt{constructor(e){super(e);this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},$1=R1,G1=class extends Wt{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"";let t=[e[0]];for(let s=1;s<e.length;++s)if(e[s]!==t.at(-1))t.push(e[s]);let n=t.filter((s)=>s!==this.pad_token).join("");if(this.cleanup)n=Yi(n).replaceAll(this.word_delimiter_token," ").trim();return n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},V1=G1,U1=class extends Wt{constructor(e){super(e);this.decoders=(e.decoders??[]).map((t)=>em(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},j1=U1,W1=class extends Wt{constructor(e){super(e);this.pattern=Ea(this.config.pattern)}decode_chain(e){let t=this.config.content??"",r=this.pattern;return r===null?e:e.map((n)=>n.replaceAll(r,t))}},q1=W1,H1=class extends Wt{decode_chain(e){return[e.join("")]}},Q1=H1,X1=class extends Wt{constructor(e){super(e);this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map((t)=>{let r=0;for(let s=0;s<this.start;++s)if(t[s]===this.content){r=s+1;continue}else break;let n=t.length;for(let s=0;s<this.stop;++s){let a=t.length-s-1;if(t[a]===this.content){n=a;continue}else break}return t.slice(r,n)})}},Y1=X1,K1=class extends Wt{constructor(e){super(e);this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let n of e){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let a=parseInt(n.slice(3,5),16);if(!isNaN(a))s=a}if(s!==null)r.push(s);else{if(r.length>0){let a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},J1=K1;function Z1(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new O1(e);case"WordPiece":return new D1(e);case"Metaspace":return new B1(e);case"BPEDecoder":return new $1(e);case"CTC":return new V1(e);case"Sequence":return new j1(e);case"Replace":return new q1(e);case"Fuse":return new Q1(e);case"Strip":return new Y1(e);case"ByteFallback":return new J1(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var em=Z1,ek=class{constructor(e,t){let r=D_(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw Error(r);let n=D_(t,"Config");if(n)throw Error(n);this.tokenizer=e,this.config=t,this.normalizer=Yp(this.tokenizer.normalizer),this.pre_tokenizer=Jp(this.tokenizer.pre_tokenizer),this.model=v1(this.tokenizer.model,this.config),this.post_processor=Zp(this.tokenizer.post_processor),this.decoder=em(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let s=[],a=[];this.added_tokens_map=new Map;for(let o of this.tokenizer.added_tokens){let i=new FM(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);if(this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else s.push(i.content)}if((this.config.additional_special_tokens??[]).forEach((o)=>{if(!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 F_(s),this.splitter_normalized=new F_(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=s.map((l)=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:s,attention_mask:Array(o.length).fill(1)};if(n&&a)i.token_type_ids=a;return i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!JM(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map((s)=>this.model.vocab[Number(s)]??this.model.unk_token);if(t.skip_special_tokens)r=r.filter((s)=>!this.special_tokens.includes(s));let n=this.decoder?this.decoder(r):r.join(" ");if(this.decoder&&this.decoder.end_of_word_suffix){if(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens)n=n.trim()}if(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)n=Yi(n);return n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((r,n)=>{let s=this.added_tokens_map.get(r);if(s){if(s.lstrip&&n>0)t[n-1]=t[n-1].trimEnd();if(s.rstrip&&n<t.length-1)t[n+1]=t[n+1].trimStart()}}),t.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0)r=r.trim().split(/\s+/).join(" ");if(this.do_lowercase_and_remove_accent)r=ex(r);if(this.normalizer!==null)r=this.normalizer(r);if(r.length===0)return[];let s=this.splitter_normalized.split(r);return s.forEach((a,o)=>{let i=this.added_tokens_map.get(a);if(i){if(i.lstrip&&o>0)s[o-1]=s[o-1].trimEnd();if(i.rstrip&&o<s.length-1)s[o+1]=s[o+1].trimStart()}}),s.flatMap((a)=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];let o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:n}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){let n=this.encode_text(e),s=this.encode_text(t||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Rt(n??[],s??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let r=0;r<this.model.vocab.length;++r){let n=this.model.vocab[r];if(e||!this.added_tokens_map.has(n))t.set(n,r)}return t}},tk=ek,rk=Object.defineProperty,nk=(e,t,r)=>(t in e)?rk(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,sk=(e,t,r)=>(nk(e,typeof t!=="symbol"?t+"":t,r),r),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",ExponentiationBinaryOperator:"ExponentiationBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),St=class{constructor(e,t){this.value=e,this.type=t}};function G_(e){return/\w/.test(e)}function Jr(e){return/[0-9]/.test(e)}function V_(e){return/\s/.test(e)}var ak=[["{%",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.ExponentiationBinaryOperator],["*",z.MultiplicativeBinaryOperator],["//",z.MultiplicativeBinaryOperator],["/",z.MultiplicativeBinaryOperator],["%",z.MultiplicativeBinaryOperator],["=",z.Equals]],ok=new Map([["n",`
|
|
13
|
+
`],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function ik(e,t={}){if(e.endsWith(`
|
|
14
|
+
`))e=e.slice(0,-1);if(t.lstrip_blocks)e=e.replace(/^[ \t]*({[#%-])/gm,"$1");if(t.trim_blocks)e=e.replace(/([#%-]})\n/g,"$1");return e.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(r,n,s,a,o)=>(s?"":n)+(a?"":o))}function lk(e,t={}){let r=[],n=ik(e,t),s=0,a=0,o=(c)=>{let d="";while(c(n[s])){if(n[s]==="\\"){if(++s,s>=n.length)throw SyntaxError("Unexpected end of input");let f=n[s++],_=ok.get(f);if(_===void 0)throw SyntaxError(`Unexpected escaped character: ${f}`);d+=_;continue}if(d+=n[s++],s>=n.length)throw SyntaxError("Unexpected end of input")}return d},i=()=>{let c=r.at(-1);if(c&&c.type===z.Text){if(c.value=c.value.trimEnd(),c.value==="")r.pop()}},l=()=>{while(s<n.length&&V_(n[s]))++s};e:while(s<n.length){let c=r.at(-1)?.type;if(c===void 0||c===z.CloseStatement||c===z.CloseExpression||c===z.Comment){let f="";while(s<n.length&&!(n[s]==="{"&&(n[s+1]==="%"||n[s+1]==="{"||n[s+1]==="#")))f+=n[s++];if(f.length>0){r.push(new St(f,z.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;let f=n[s]==="-";if(f)++s;let _="";while(n[s]!=="#"||n[s+1]!=="}"){if(s+2>=n.length)throw SyntaxError("Missing end of comment tag");_+=n[s++]}let p=_.endsWith("-");if(p)_=_.slice(0,-1);if(f)i();if(r.push(new St(_,z.Comment)),s+=2,p)l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new St("{%",z.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new St("{{",z.OpenExpression)),a=0,s+=3;continue}if(o(V_),n.slice(s,s+3)==="-%}"){r.push(new St("%}",z.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new St("}}",z.CloseExpression)),s+=3,l();continue}let d=n[s];if(d==="-"||d==="+"){let f=r.at(-1)?.type;if(f===z.Text||f===void 0)throw SyntaxError(`Unexpected character: ${d}`);switch(f){case z.Identifier:case z.NumericLiteral:case z.StringLiteral:case z.CloseParen:case z.CloseSquareBracket:break;default:{++s;let _=o(Jr);if(_.length>0&&n[s]==="."&&Jr(n[s+1])){++s;let p=o(Jr);_=`${_}.${p}`}r.push(new St(`${d}${_}`,_.length>0?z.NumericLiteral:z.UnaryOperator));continue}}}for(let[f,_]of ak){if(f==="}}"&&a>0)continue;if(n.slice(s,s+f.length)===f){if(r.push(new St(f,_)),_===z.OpenExpression)a=0;else if(_===z.OpenCurlyBracket)++a;else if(_===z.CloseCurlyBracket)--a;s+=f.length;continue e}}if(d==="'"||d==='"'){++s;let f=o((_)=>_!==d);r.push(new St(f,z.StringLiteral)),++s;continue}if(Jr(d)){let f=o(Jr);if(r.at(-1)?.type!==z.Dot&&n[s]==="."&&Jr(n[s+1])){++s;let _=o(Jr);f=`${f}.${_}`}r.push(new St(f,z.NumericLiteral));continue}if(G_(d)){let f=o(G_);r.push(new St(f,z.Identifier));continue}throw SyntaxError(`Unexpected character: ${d}`)}return r}var Pt=class{type="Statement"},ck=class extends Pt{constructor(e){super();this.body=e}type="Program"},uk=class extends Pt{constructor(e,t,r){super();this.test=e,this.body=t,this.alternate=r}type="If"},dk=class extends Pt{constructor(e,t,r,n){super();this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},fk=class extends Pt{type="Break"},hk=class extends Pt{type="Continue"},_k=class extends Pt{constructor(e,t,r){super();this.assignee=e,this.value=t,this.body=r}type="Set"},pk=class extends Pt{constructor(e,t,r){super();this.name=e,this.args=t,this.body=r}type="Macro"},mk=class extends Pt{constructor(e){super();this.value=e}type="Comment"},wt=class extends Pt{type="Expression"},gk=class extends wt{constructor(e,t,r){super();this.object=e,this.property=t,this.computed=r}type="MemberExpression"},U_=class extends wt{constructor(e,t){super();this.callee=e,this.args=t}type="CallExpression"},Er=class extends wt{constructor(e){super();this.value=e}type="Identifier"},Sn=class extends wt{constructor(e){super();this.value=e}type="Literal"},wk=class extends Sn{type="IntegerLiteral"},vk=class extends Sn{type="FloatLiteral"},j_=class extends Sn{type="StringLiteral"},yk=class extends Sn{type="ArrayLiteral"},W_=class extends Sn{type="TupleLiteral"},bk=class extends Sn{type="ObjectLiteral"},pn=class extends wt{constructor(e,t,r){super();this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},Mk=class extends wt{constructor(e,t){super();this.operand=e,this.filter=t}type="FilterExpression"},xk=class extends Pt{constructor(e,t){super();this.filter=e,this.body=t}type="FilterStatement"},kk=class extends wt{constructor(e,t){super();this.lhs=e,this.test=t}type="SelectExpression"},Tk=class extends wt{constructor(e,t,r){super();this.operand=e,this.negate=t,this.test=r}type="TestExpression"},q_=class extends wt{constructor(e,t){super();this.operator=e,this.argument=t}type="UnaryExpression"},Ek=class extends wt{constructor(e=void 0,t=void 0,r=void 0){super();this.start=e,this.stop=t,this.step=r}type="SliceExpression"},vi=class extends wt{constructor(e,t){super();this.key=e,this.value=t}type="KeywordArgumentExpression"},Ak=class extends wt{constructor(e){super();this.argument=e}type="SpreadExpression"},Ck=class extends wt{constructor(e){super();this.argument=e}type="KeywordSpreadExpression"},Sk=class extends Pt{constructor(e,t,r){super();this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},Pk=class extends wt{constructor(e,t,r){super();this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function Fk(e){let t=new ck([]),r=0;function n(L,O){let V=e[r++];if(!V||V.type!==L)throw Error(`Parser Error: ${O}. ${V.type} !== ${L}.`);return V}function s(L){if(!l(L))throw SyntaxError(`Expected ${L}`);++r}function a(){switch(e[r].type){case z.Comment:return new mk(e[r++].value);case z.Text:return c();case z.OpenStatement:return d();case z.OpenExpression:return f();default:throw SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...L){return r+L.length<=e.length&&L.every((O,V)=>O===e[r+V].type)}function i(...L){return e[r]?.type===z.OpenStatement&&e[r+1]?.type===z.Identifier&&L.includes(e[r+1]?.value)}function l(...L){return r+L.length<=e.length&&L.every((O,V)=>e[r+V].type==="Identifier"&&O===e[r+V].value)}function c(){return new j_(n(z.Text,"Expected text token").value)}function d(){if(n(z.OpenStatement,"Expected opening statement token"),e[r].type!==z.Identifier)throw SyntaxError(`Unknown statement, got ${e[r].type}`);let L=e[r].value,O;switch(L){case"set":++r,O=_();break;case"if":++r,O=p(),n(z.OpenStatement,"Expected {% token"),s("endif"),n(z.CloseStatement,"Expected %} token");break;case"macro":++r,O=w(),n(z.OpenStatement,"Expected {% token"),s("endmacro"),n(z.CloseStatement,"Expected %} token");break;case"for":++r,O=y(),n(z.OpenStatement,"Expected {% token"),s("endfor"),n(z.CloseStatement,"Expected %} token");break;case"call":{++r;let V=null;if(o(z.OpenParen))V=q("parameters");let de=se();if(de.type!=="Identifier")throw SyntaxError("Expected identifier following call statement");let te=q("call");n(z.CloseStatement,"Expected closing statement token");let We=[];while(!i("endcall"))We.push(a());n(z.OpenStatement,"Expected '{%'"),s("endcall"),n(z.CloseStatement,"Expected closing statement token");let Fe=new U_(de,te);O=new Sk(Fe,V,We);break}case"break":++r,n(z.CloseStatement,"Expected closing statement token"),O=new fk;break;case"continue":++r,n(z.CloseStatement,"Expected closing statement token"),O=new hk;break;case"filter":{++r;let V=se();if(V instanceof Er&&o(z.OpenParen))V=R(V);n(z.CloseStatement,"Expected closing statement token");let de=[];while(!i("endfilter"))de.push(a());n(z.OpenStatement,"Expected '{%'"),s("endfilter"),n(z.CloseStatement,"Expected '%}'"),O=new xk(V,de);break}default:throw SyntaxError(`Unknown statement type: ${L}`)}return O}function f(){n(z.OpenExpression,"Expected opening expression token");let L=b();return n(z.CloseExpression,"Expected closing expression token"),L}function _(){let L=v(),O=null,V=[];if(o(z.Equals))++r,O=v();else{n(z.CloseStatement,"Expected %} token");while(!i("endset"))V.push(a());n(z.OpenStatement,"Expected {% token"),s("endset")}return n(z.CloseStatement,"Expected closing statement token"),new _k(L,O,V)}function p(){let L=b();n(z.CloseStatement,"Expected closing statement token");let O=[],V=[];while(!i("elif","else","endif"))O.push(a());if(i("elif")){++r,++r;let de=p();V.push(de)}else if(i("else")){++r,++r,n(z.CloseStatement,"Expected closing statement token");while(!i("endif"))V.push(a())}return new uk(L,O,V)}function w(){let L=se();if(L.type!=="Identifier")throw SyntaxError("Expected identifier following macro statement");let O=q("parameters");n(z.CloseStatement,"Expected closing statement token");let V=[];while(!i("endmacro"))V.push(a());return new pk(L,O,V)}function v(L=!1){let O=L?se:b,V=[O()],de=o(z.Comma);while(de)if(++r,V.push(O()),!o(z.Comma))break;return de?new W_(V):V[0]}function y(){let L=v(!0);if(!(L instanceof Er||L instanceof W_))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw SyntaxError("Expected `in` keyword following loop variable");++r;let O=b();n(z.CloseStatement,"Expected closing statement token");let V=[];while(!i("endfor","else"))V.push(a());let de=[];if(i("else")){++r,++r,n(z.CloseStatement,"Expected closing statement token");while(!i("endfor"))de.push(a())}return new dk(L,O,V,de)}function b(){return k()}function k(){let L=A();if(l("if")){++r;let O=A();if(l("else")){++r;let V=k();return new Pk(O,L,V)}else return new kk(L,O)}return L}function A(){let L=E();while(l("or")){let O=e[r];++r;let V=E();L=new pn(O,L,V)}return L}function E(){let L=C();while(l("and")){let O=e[r];++r;let V=C();L=new pn(O,L,V)}return L}function C(){let L;while(l("not")){let O=e[r];++r;let V=C();L=new q_(O,V)}return L??N()}function N(){let L=M();while(!0){let O;if(l("not","in"))O=new St("not in",z.Identifier),r+=2;else if(l("in"))O=e[r++];else if(o(z.ComparisonBinaryOperator))O=e[r++];else break;let V=M();L=new pn(O,L,V)}return L}function M(){let L=B();while(o(z.AdditiveBinaryOperator)){let O=e[r];++r;let V=B();L=new pn(O,L,V)}return L}function G(){let L=H(se());if(o(z.OpenParen))return R(L);return L}function R(L){let O=new U_(L,q("call"));if(O=H(O),o(z.OpenParen))O=R(O);return O}function q(L){n(z.OpenParen,"Expected opening parenthesis for arguments list");let O=X(L);return n(z.CloseParen,"Expected closing parenthesis for arguments list"),O}function X(L){let O=[],V=new Set,de=!1,te=!1;while(!o(z.CloseParen)){let We=o(z.ExponentiationBinaryOperator),Fe=o(z.MultiplicativeBinaryOperator)&&e[r].value==="*";if(L==="parameters"&&(We||Fe))throw SyntaxError("Argument unpacking is not allowed in parameter declarations");if(We){if(++r,O.push(new Ck(b())),o(z.Comma))++r;if(!o(z.CloseParen))throw SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let be;if(Fe){if(te)throw SyntaxError("Only one `*` argument unpacking is allowed");te=!0,++r;let Ge=b();be=new Ak(Ge)}else{if(be=b(),o(z.Equals)){if(++r,!(be instanceof Er))throw SyntaxError(L==="parameters"?"Expected identifier for parameter declaration":"Expected identifier for keyword argument");let Ge=b();be=new vi(be,Ge)}if(L==="parameters"){if(!(be instanceof Er||be instanceof vi))throw SyntaxError("Expected identifier for parameter declaration");let Ge=be instanceof Er?be.value:be.key.value;if(V.has(Ge))throw SyntaxError(`Duplicate parameter name: ${Ge}`);V.add(Ge)}if(be instanceof vi)de=!0;else if(de)throw SyntaxError(L==="call"?"Positional arguments must come before keyword arguments":"Non-default argument follows default argument");else if(te)throw SyntaxError("Positional arguments must not follow `*` argument unpacking")}if(O.push(be),o(z.Comma))++r}return O}function Q(){let L=[],O=!1;while(!o(z.CloseSquareBracket))if(o(z.Colon))L.push(void 0),++r,O=!0;else if(L.push(b()),o(z.Colon))++r,O=!0;if(L.length===0)throw SyntaxError("Expected at least one argument for member/slice expression");if(O){if(L.length>3)throw SyntaxError("Expected 0-3 arguments for slice expression");return new Ek(...L)}return L[0]}function H(L){while(o(z.Dot)||o(z.OpenSquareBracket)){let O=e[r];++r;let V,de=O.type===z.OpenSquareBracket;if(de)V=Q(),n(z.CloseSquareBracket,"Expected closing square bracket");else if(V=se(),V.type!=="Identifier"&&V.type!=="IntegerLiteral")throw SyntaxError("Expected identifier or integer following dot operator");L=new gk(L,V,de)}return L}function B(){let L=P();while(o(z.MultiplicativeBinaryOperator)){let O=e[r++],V=P();L=new pn(O,L,V)}return L}function P(){let L=Y();while(o(z.ExponentiationBinaryOperator)){let O=e[r++],V=Y();L=new pn(O,L,V)}return L}function Y(){let L=ue();while(l("is")){++r;let O=l("not");if(O)++r;let V=se();if(!(V instanceof Er))throw SyntaxError("Expected identifier for the test");L=new Tk(L,O,V)}return L}function ue(){let L=Z();while(o(z.Pipe)){++r;let O=se();if(!(O instanceof Er))throw SyntaxError("Expected identifier for the filter");if(o(z.OpenParen))O=R(O);L=new Mk(L,O)}return L}function Z(){let L=e[r];if(L&&(L.type===z.UnaryOperator||L.type===z.AdditiveBinaryOperator)&&(L.value==="-"||L.value==="+")){let O=e[r++],V=Z();return new q_(O,V)}return G()}function se(){let L=e[r++];switch(L.type){case z.NumericLiteral:{let O=L.value;return O.includes(".")?new vk(Number(O)):new wk(Number(O))}case z.StringLiteral:{let O=L.value;while(o(z.StringLiteral))O+=e[r++].value;return new j_(O)}case z.Identifier:return new Er(L.value);case z.OpenParen:{let O=v();return n(z.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),O}case z.OpenSquareBracket:{let O=[];while(!o(z.CloseSquareBracket))if(O.push(b()),o(z.Comma))++r;return++r,new yk(O)}case z.OpenCurlyBracket:{let O=new Map;while(!o(z.CloseCurlyBracket)){let V=b();n(z.Colon,"Expected colon between key and value in object literal");let de=b();if(O.set(V,de),o(z.Comma))++r}return++r,new bk(O)}default:throw SyntaxError(`Unexpected token: ${L.type}`)}}while(r<e.length)t.body.push(a());return t}function Ik(e,t,r=1){if(t===void 0)t=e,e=0;if(r===0)throw Error("range() step must not be zero");let n=[];if(r>0)for(let s=e;s<t;s+=r)n.push(s);else for(let s=e;s>t;s+=r)n.push(s);return n}function H_(e,t,r,n=1){let s=Math.sign(n);if(s>=0)t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length);else 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);let a=[];for(let o=t;s*o<s*r;o+=n)a.push(e[o]);return a}function Lk(e){return e.replace(/\b\w/g,(t)=>t.toUpperCase())}function Ok(e){return Nk(new Date,e)}function Nk(e,t){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),s=(a)=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,(a)=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return s(e.getMonth()+1);case"%d":return s(e.getDate());case"%b":return n.format(e);case"%B":return r.format(e);case"%H":return s(e.getHours());case"%M":return s(e.getMinutes());case"%%":return"%";default:return a}})}function Dk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zk(e,t,r,n){if(n===0)return e;let s=n==null||n<0?1/0:n,a=t.length===0?new RegExp("(?=)","gu"):new RegExp(Dk(t),"gu");return e.replaceAll(a,(o)=>{if(s>0)return--s,r;return o})}var Q_=class extends Error{},X_=class extends Error{},Bk=new Map,qt=class{type="RuntimeValue";value;get builtins(){return Bk}constructor(e=void 0){this.value=e}__bool__(){return new ae(!!this.value)}toString(){return String(this.value)}},ie=class extends qt{type="IntegerValue"},Ce=class extends qt{type="FloatValue";toString(){if(Object.is(this.value,-0))return"-0.0";return this.value%1===0?this.value.toFixed(1):this.value.toString()}},J=class extends qt{type="StringValue";_builtins;get builtins(){return this._builtins??=new Map([["upper",new ze(()=>new J(this.value.toUpperCase()))],["lower",new ze(()=>new J(this.value.toLowerCase()))],["strip",new ze(()=>new J(this.value.trim()))],["title",new ze(()=>new J(Lk(this.value)))],["capitalize",new ze(()=>new J(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ie(this.value.length)],["rstrip",new ze(()=>new J(this.value.trimEnd()))],["lstrip",new ze(()=>new J(this.value.trimStart()))],["startswith",new ze((e)=>{if(e.length===0)throw Error("startswith() requires at least one argument");let t=e[0];if(t instanceof J)return new ae(this.value.startsWith(t.value));else if(t instanceof ge){for(let r of t.value){if(!(r instanceof J))throw Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new ae(!0)}return new ae(!1)}throw Error("startswith() argument must be a string or tuple of strings")})],["endswith",new ze((e)=>{if(e.length===0)throw Error("endswith() requires at least one argument");let t=e[0];if(t instanceof J)return new ae(this.value.endsWith(t.value));else if(t instanceof ge){for(let r of t.value){if(!(r instanceof J))throw Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new ae(!0)}return new ae(!1)}throw Error("endswith() argument must be a string or tuple of strings")})],["split",new ze((e)=>{let t=e[0]??new Re;if(!(t instanceof J||t instanceof Re))throw Error("sep argument must be a string or null");let r=e[1]??new ie(-1);if(!(r instanceof ie))throw Error("maxsplit argument must be a number");let n=[];if(t instanceof Re){let s=this.value.trimStart();for(let{0:a,index:o}of s.matchAll(/\S+/g)){if(r.value!==-1&&n.length>=r.value&&o!==void 0){n.push(a+s.slice(o+a.length));break}n.push(a)}}else{if(t.value==="")throw Error("empty separator");if(n=this.value.split(t.value),r.value!==-1&&n.length>r.value)n.push(n.splice(r.value).join(t.value))}return new ge(n.map((s)=>new J(s)))})],["replace",new ze((e)=>{if(e.length<2)throw Error("replace() requires at least two arguments");let t=e[0],r=e[1];if(!(t instanceof J&&r instanceof J))throw Error("replace() arguments must be strings");let n;if(e.length>2)if(e[2].type==="KeywordArgumentsValue")n=e[2].value.get("count")??new Re;else n=e[2];else n=new Re;if(!(n instanceof ie||n instanceof Re))throw Error("replace() count argument must be a number or null");return new J(zk(this.value,t.value,r.value,n.value))})]])}},ae=class extends qt{type="BooleanValue"},Rk=/[\x7f-\uffff]/g;function Y_(e){return e.replace(Rk,(t)=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Ir(e,t={},r=0,n=!0){let{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t,l,c;if(o)[l,c]=o;else if(s)l=",",c=": ";else l=", ",c=": ";switch(e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let d=JSON.stringify(e.value);if(a)d=Y_(d);return d}case"ArrayValue":case"NamespaceValue":case"ObjectValue":{let d=s?" ".repeat(s):"",f=`
|
|
15
|
+
`+d.repeat(r),_=f+d;if(e.type==="ArrayValue"){let p=e.value.map((w)=>Ir(w,t,r+1,n));return s?`[${_}${p.join(`${l}${_}`)}${f}]`:`[${p.join(l)}]`}else{let p=Array.from(e.value.entries());if(i)p=p.sort(([v],[y])=>v.localeCompare(y));let w=p.map(([v,y])=>{let b=JSON.stringify(v);if(a)b=Y_(b);let k=`${b}${c}${Ir(y,t,r+1,n)}`;return s?`${_}${k}`:k});return s?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var ut=class extends qt{type="ObjectValue";_builtins;__bool__(){return new ae(this.value.size>0)}get builtins(){return this._builtins??=new Map([["get",new ze(([e,t])=>{if(!(e instanceof J))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Re})],["items",new ze(()=>this.items())],["keys",new ze(()=>this.keys())],["values",new ze(()=>this.values())],["dictsort",new ze((e)=>{let t=new Map,r=e.filter((i)=>{if(i instanceof tn)return t=i.value,!1;return!0}),n=r.at(0)??t.get("case_sensitive")??new ae(!1);if(!(n instanceof ae))throw Error("case_sensitive must be a boolean");let s=r.at(1)??t.get("by")??new J("key");if(!(s instanceof J))throw Error("by must be a string");if(!["key","value"].includes(s.value))throw Error("by must be either 'key' or 'value'");let a=r.at(2)??t.get("reverse")??new ae(!1);if(!(a instanceof ae))throw Error("reverse must be a boolean");let o=Array.from(this.value.entries()).map(([i,l])=>new ge([new J(i),l])).sort((i,l)=>{let c=s.value==="key"?0:1,d=i.value[c],f=l.value[c],_=Ii(d,f,n.value);return a.value?-_:_});return new ge(o)})]])}items(){return new ge(Array.from(this.value.entries()).map(([e,t])=>new ge([new J(e),t])))}keys(){return new ge(Array.from(this.value.keys()).map((e)=>new J(e)))}values(){return new ge(Array.from(this.value.values()))}toString(){return Ir(this,{},0,!1)}},tn=class extends ut{type="KeywordArgumentsValue"},Zi=class extends qt{type="NamespaceValue";toString(){return Ir(this,{},0,!1)}},ge=class extends qt{type="ArrayValue";_builtins;get builtins(){return this._builtins??=new Map([["length",new ie(this.value.length)]])}__bool__(){return new ae(this.value.length>0)}toString(){return Ir(this,{},0,!1)}},K_=class extends ge{type="TupleValue"},ze=class extends qt{type="FunctionValue"},Re=class extends qt{type="NullValue"},De=class extends qt{type="UndefinedValue"};function $k(e){let t;if(e instanceof ge)t=e.value;else if(e instanceof J)t=Array.from(e.value,(s)=>new J(s));if(!t||t.length!==2)throw Error("namespace expected an object or an iterable of [key, value] pairs");let[r,n]=t;if(!(r instanceof J))throw Error("namespace keys must be strings");return[r,n]}var tm=class{constructor(e){this.parent=e}variables=new Map([["namespace",new ze((e)=>{let t=e.slice(),r;if(t.at(-1)instanceof tn)r=t.pop();if(t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let n=new Map;if(t.length===1){let s=t[0];if(s instanceof ut)for(let[a,o]of s.value)n.set(a,o);else if(s instanceof ge)for(let a of s.value){let[o,i]=$k(a);n.set(o.value,i)}else throw Error(`'${s.type}' object is not iterable`)}if(r)for(let[s,a]of r.value)n.set(s,a);return new Zi(n)})]]);tests=tm.TESTS;set(e,t){return this.declareVariable(e,ia(t))}declareVariable(e,t){if(this.variables.has(e))throw 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 Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new De}catch{return new De}}},Cr=tm;sk(Cr,"TESTS",new Map([["boolean",(e)=>e.type==="BooleanValue"],["callable",(e)=>e instanceof ze],["odd",(e)=>{if(!(e instanceof ie))throw Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",(e)=>{if(!(e instanceof ie))throw 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 ie||e instanceof Ce],["integer",(e)=>e instanceof ie],["iterable",(e)=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",(e)=>e instanceof ut],["sequence",(e)=>e instanceof ge||e instanceof ut||e instanceof J],["lower",(e)=>{let t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",(e)=>{let t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",(e)=>e.type==="NullValue"],["defined",(e)=>e.type!=="UndefinedValue"],["undefined",(e)=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));function Gk(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",(t)=>{throw Error(t)}),e.set("range",Ik),e.set("strftime_now",Ok),e.set("True",!0),e.set("False",!1),e.set("None",null)}function oa(e){return e instanceof ut||e instanceof Zi}function ma(e){return e instanceof ie||e instanceof Ce||e instanceof ae}function ga(e){return e instanceof ae?Number(e.value):e.value}function J_(e,t){let r=t.split("."),n=e;for(let s of r)if(oa(n))n=n.value.get(s)??new De;else if(n instanceof ge){let a=parseInt(s,10);if(!isNaN(a)&&a>=0&&a<n.value.length)n=n.value[a];else return new De}else return new De;return n}function Ii(e,t,r=!1){if(e instanceof Re&&t instanceof Re)return 0;if(e instanceof Re||t instanceof Re)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof De&&t instanceof De)return 0;if(e instanceof De||t instanceof De)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(ma(e)&&ma(t)){let n=ga(e),s=ga(t);return n<s?-1:n>s?1:0}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let n=e.value,s=t.value;if(!r)n=n.toLowerCase(),s=s.toLowerCase();return n<s?-1:n>s?1:0}default:throw Error(`Cannot compare type: ${e.type}`)}}function Li(e){if(e.type==="Identifier")return{name:e.value};let t=e;return{name:t.key.value,defaultValue:t.value}}function Z_(e){return e==="kwargs"||e==="varargs"}function ep(e,t){let r=new Set,n=new Set,s=(d)=>{if(Z_(d))r.add(d)},a=(d)=>{if(d.type==="Identifier")s(d.value);else if(d.type==="TupleLiteral")for(let f of d.value)a(f)},o=(d)=>{s(Li(d).name)},i=(d)=>{for(let f of d){let _=Li(f);if(_.defaultValue)c(_.defaultValue)}},l=(d)=>{if(d.type==="CallExpression")c(d.args)},c=(d)=>{if(Array.isArray(d)){for(let f of d)c(f);return}if(d instanceof Map){for(let[f,_]of d)c(f),c(_);return}if(!(d instanceof Pt))return;switch(d.type){case"For":{let f=d;if(a(f.loopvar),f.iterable.type==="SelectExpression"){let _=f.iterable;c(_.lhs),c(f.body),c(f.defaultBlock),c(_.test);return}c(f.iterable),c(f.body),c(f.defaultBlock);return}case"Set":{let f=d;a(f.assignee),c(f.value),c(f.body);return}case"Macro":{let f=d;for(let _ of f.args)o(_);i(f.args),c(f.body);return}case"CallStatement":{let f=d;c(f.call);for(let _ of f.callerArgs??[])o(_);i(f.callerArgs??[]),c(f.body);return}case"FilterStatement":{let f=d;c(f.body),l(f.filter);return}case"Identifier":{let f=d.value;if(Z_(f)&&!r.has(f))n.add(f);return}case"MemberExpression":{let f=d;if(c(f.object),f.computed)c(f.property);return}case"FilterExpression":{let f=d;c(f.operand),l(f.filter);return}case"TestExpression":c(d.operand);return;case"SelectExpression":{let f=d;c(f.test),c(f.lhs);return}case"KeywordArgumentExpression":c(d.value);return;default:for(let f of Object.values(d))c(f)}};for(let d of e)o(d);return c(t),n}var Vk=class{global;constructor(e){this.global=e??new Cr}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let 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)}let n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ae(r.value==n.value);case"!=":return new ae(r.value!=n.value)}if(r instanceof De||n instanceof De){if(n instanceof De&&["in","not in"].includes(e.operator.value))return new ae(e.operator.value==="not in");throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else if(r instanceof Re||n instanceof Re)throw Error("Cannot perform operation on null values");else if(e.operator.value==="~")return new J(r.value.toString()+n.value.toString());else if(e.operator.value==="**"&&ma(r)&&ma(n)){let s=ga(r),a=ga(n);if(s===0&&a<0)throw Error("0.0 cannot be raised to a negative power");let o=s**a;if(!Number.isFinite(o))throw Error("Exponentiation result is not a finite real number");return r instanceof Ce||n instanceof Ce||a<0?new Ce(o):new ie(o)}else if((r instanceof ie||r instanceof Ce)&&(n instanceof ie||n instanceof Ce)){let s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{let o=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof Ce||n instanceof Ce?new Ce(o):new ie(o)}case"/":return new Ce(s/a);case"//":{let o=Math.floor(s/a);return r instanceof Ce||n instanceof Ce?new Ce(o):new ie(o)}case"%":{let o=s%a;return r instanceof Ce||n instanceof Ce?new Ce(o):new ie(o)}case"<":return new ae(s<a);case">":return new ae(s>a);case">=":return new ae(s>=a);case"<=":return new ae(s<=a)}}else if(r instanceof ge&&n instanceof ge)switch(e.operator.value){case"+":return new ge(r.value.concat(n.value))}else if(n instanceof ge){let s=n.value.find((a)=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ae(s);case"not in":return new ae(!s)}}if(r instanceof J||n instanceof J)switch(e.operator.value){case"+":return new J(r.value.toString()+n.value.toString())}if(r instanceof J&&n instanceof J)switch(e.operator.value){case"in":return new ae(n.value.includes(r.value));case"not in":return new ae(!n.value.includes(r.value))}if(r instanceof J&&n instanceof ut)switch(e.operator.value){case"in":return new ae(n.value.has(r.value));case"not in":return new ae(!n.value.has(r.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(e,t){let r=[],n=new Map,s=(a,o)=>{if(n.has(a))throw Error(`Got multiple values for keyword argument '${a}'`);n.set(a,o)};for(let a of e)if(a.type==="SpreadExpression"){let o=a,i=this.evaluate(o.argument,t);if(!(i instanceof ge))throw Error(`Cannot unpack non-iterable type: ${i.type}`);for(let l of i.value)r.push(l)}else if(a.type!=="KeywordArgumentExpression"&&a.type!=="KeywordSpreadExpression")r.push(this.evaluate(a,t));for(let a of e)if(a.type==="KeywordArgumentExpression"){let o=a;s(o.key.value,this.evaluate(o.value,t))}else if(a.type==="KeywordSpreadExpression"){let o=a,i=this.evaluate(o.argument,t);if(!(i instanceof ut))throw Error(`Argument after ** must be a mapping, not ${i.type}`);for(let[l,c]of i.value)s(l,c)}return[r,n]}applyFilter(e,t,r){if(t.type==="Identifier"){let n=t;if(n.value==="safe")return e;if(n.value==="tojson")return new J(Ir(e,{}));if(e instanceof ge)switch(n.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new ie(e.value.length);case"reverse":return new ge(e.value.slice().reverse());case"sort":return new ge(e.value.slice().sort((s,a)=>Ii(s,a,!1)));case"join":return new J(e.value.map((s)=>s.value).join(""));case"string":return new J(Ir(e,{},0,!1));case"unique":{let s=new Set,a=[];for(let o of e.value)if(!s.has(o.value))s.add(o.value),a.push(o);return new ge(a)}default:throw Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof J)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let s=e.builtins.get(n.value);if(s instanceof ze)return s.value([],r);else if(s instanceof ie)return s;else throw Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new J(e.value.trim());case"indent":return new J(e.value.split(`
|
|
16
|
+
`).map((s,a)=>a===0||s.length===0?s:" "+s).join(`
|
|
17
|
+
`));case"join":case"string":return e;case"int":{let s=parseInt(e.value,10);return new ie(isNaN(s)?0:s)}case"float":{let s=parseFloat(e.value);return new Ce(isNaN(s)?0:s)}default:throw Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof ie||e instanceof Ce)switch(n.value){case"abs":return e instanceof ie?new ie(Math.abs(e.value)):new Ce(Math.abs(e.value));case"int":return new ie(Math.floor(e.value));case"float":return new Ce(e.value);case"string":return new J(e.toString());default:throw Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof ut)switch(n.value){case"items":return new ge(Array.from(e.value.entries()).map(([s,a])=>new ge([new J(s),a])));case"length":return new ie(e.value.size);default:{let s=e.builtins.get(n.value);if(s){if(s instanceof ze)return s.value([],r);return s}throw Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof ae)switch(n.value){case"bool":return new ae(e.value);case"int":return new ie(e.value?1:0);case"float":return new Ce(e.value?1:0);case"string":return new J(e.value?"true":"false");default:throw Error(`Unknown BooleanValue filter: ${n.value}`)}throw Error(`Cannot apply filter "${n.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){let n=t;if(n.callee.type!=="Identifier")throw Error(`Unknown filter: ${n.callee.type}`);let s=n.callee.value;if(s==="tojson"){let[,a]=this.evaluateArguments(n.args,r),o=a.get("indent")??new Re;if(!(o instanceof ie||o instanceof Re))throw Error("If set, indent must be a number");let i=a.get("ensure_ascii")??new ae(!1);if(!(i instanceof ae))throw Error("If set, ensure_ascii must be a boolean");let l=a.get("sort_keys")??new ae(!1);if(!(l instanceof ae))throw Error("If set, sort_keys must be a boolean");let c=a.get("separators")??new Re,d=null;if(c instanceof ge||c instanceof K_){if(c.value.length!==2)throw Error("separators must be a tuple of two strings");let[f,_]=c.value;if(!(f instanceof J)||!(_ instanceof J))throw Error("separators must be a tuple of two strings");d=[f.value,_.value]}else if(!(c instanceof Re))throw Error("If set, separators must be a tuple of two strings");return new J(Ir(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(s==="join"){let a;if(e instanceof J)a=Array.from(e.value);else if(e instanceof ge)a=e.value.map((c)=>c.value);else throw Error(`Cannot apply filter "${s}" to type: ${e.type}`);let[o,i]=this.evaluateArguments(n.args,r),l=o.at(0)??i.get("separator")??new J("");if(!(l instanceof J))throw Error("separator must be a string");return new J(a.join(l.value))}else if(s==="int"||s==="float"){let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("default")??(s==="int"?new ie(0):new Ce(0));if(e instanceof J){let l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new ie(l):new Ce(l)}else if(e instanceof ie||e instanceof Ce)return e;else if(e instanceof ae)return s==="int"?new ie(e.value?1:0):new Ce(e.value?1:0);else throw Error(`Cannot apply filter "${s}" to type: ${e.type}`)}else if(s==="default"){let[a,o]=this.evaluateArguments(n.args,r),i=a[0]??new J(""),l=a[1]??o.get("boolean")??new ae(!1);if(!(l instanceof ae))throw Error("`default` filter flag must be a boolean");if(e instanceof De||l.value&&!e.__bool__().value)return i;return e}if(e instanceof ge){switch(s){case"sort":{let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new ae(!1);if(!(i instanceof ae))throw Error("reverse must be a boolean");let l=a.at(1)??o.get("case_sensitive")??new ae(!1);if(!(l instanceof ae))throw Error("case_sensitive must be a boolean");let c=a.at(2)??o.get("attribute")??new Re;if(!(c instanceof J||c instanceof ie||c instanceof Re))throw Error("attribute must be a string, integer, or null");let d=(f)=>{if(c instanceof Re)return f;let _=c instanceof ie?String(c.value):c.value;return J_(f,_)};return new ge(e.value.slice().sort((f,_)=>{let p=d(f),w=d(_),v=Ii(p,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{let a=s==="selectattr";if(e.value.some((f)=>!oa(f)))throw Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some((f)=>f.type!=="StringLiteral"))throw Error(`arguments of \`${s}\` must be strings`);let[o,i,l]=n.args.map((f)=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let d=e.value.filter((f)=>{let _=f.value.get(o.value),p=_?c(_,l):!1;return a?p:!p});return new ge(d)}case"map":{let[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){let o=a.get("attribute");if(!(o instanceof J))throw Error("attribute must be a string");let i=a.get("default"),l=e.value.map((c)=>{if(!oa(c))throw Error("items in map must be an object");let d=J_(c,o.value);return d instanceof De?i??new De:d});return new ge(l)}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof J){switch(s){case"indent":{let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new ie(4);if(!(i instanceof ie))throw Error("width must be a number");let l=a.at(1)??o.get("first")??new ae(!1),c=a.at(2)??o.get("blank")??new ae(!1),d=e.value.split(`
|
|
18
|
+
`),f=" ".repeat(i.value),_=d.map((p,w)=>!l.value&&w===0||!c.value&&p.length===0?p:f+p);return new J(_.join(`
|
|
19
|
+
`))}case"replace":{let a=e.builtins.get("replace");if(!(a instanceof ze))throw Error("replace filter not available");let[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new tn(i)],r)}}throw Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof ut){let a=e.builtins.get(s);if(a&&a instanceof ze){let[o,i]=this.evaluateArguments(n.args,r);if(i.size>0)o.push(new tn(i));return a.value(o,r)}throw Error(`Unknown ObjectValue filter: ${s}`)}else throw Error(`Cannot apply filter "${s}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){let r=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw Error(`Unknown test: ${e.test.value}`);let s=n(r);return new ae(e.negate?!s:s)}evaluateSelectExpression(e,t){if(!this.evaluate(e.test,t).__bool__().value)return new De;return this.evaluate(e.lhs,t)}evaluateUnaryExpression(e,t){let r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ae(!r.value);case"+":case"-":{let n=e.operator.value==="-"?-1:1;if(r instanceof ie||r instanceof Ce||r instanceof ae){let s=r instanceof ae?r.value?1:0:r.value,a=n*s;return r instanceof Ce?new Ce(a):new ie(a)}throw SyntaxError(`Unknown operator "${e.operator.value}" for ${r.type}`)}default:throw 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(let n of e){let s=this.evaluate(n,t);if(s.type!=="NullValue"&&s.type!=="UndefinedValue")r+=s.toString()}return new J(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[r,n]=this.evaluateArguments(e.args,t);if(n.size>0)r.push(new tn(n));let s=this.evaluate(e.callee,t);if(s.type!=="FunctionValue")throw Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof ge||e instanceof J))throw Error("Slice object must be an array or string");let n=this.evaluate(t.start,r),s=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(n instanceof ie||n instanceof De))throw Error("Slice start must be numeric or undefined");if(!(s instanceof ie||s instanceof De))throw Error("Slice stop must be numeric or undefined");if(!(a instanceof ie||a instanceof De))throw Error("Slice step must be numeric or undefined");if(e instanceof ge)return new ge(H_(e.value,n.value,s.value,a.value));else return new J(H_(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){let r=this.evaluate(e.object,t),n;if(e.computed)if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);else n=this.evaluate(e.property,t);else if(e.property.type==="IntegerLiteral")n=new ie(e.property.value);else n=new J(e.property.value);let s;if(oa(r)){if(!(n instanceof J))throw Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??(r instanceof ut?r.builtins.get(n.value):void 0)}else if(r instanceof ge||r instanceof J)if(n instanceof ie){if(s=r.value.at(n.value),r instanceof J)s=new J(r.value.at(n.value))}else if(n instanceof J)s=r.builtins.get(n.value);else throw Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof J))throw Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof qt?s:new De}evaluateSet(e,t){let r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){let n=e.assignee.value;t.setVariable(n,r)}else if(e.assignee.type==="TupleLiteral"){let n=e.assignee;if(!(r instanceof ge))throw Error(`Cannot unpack non-iterable type in set: ${r.type}`);let s=r.value;if(s.length!==n.value.length)throw Error(`Too ${n.value.length>s.length?"few":"many"} items to unpack in set`);for(let a=0;a<n.value.length;++a){let o=n.value[a];if(o.type!=="Identifier")throw Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,s[a])}}else if(e.assignee.type==="MemberExpression"){let n=e.assignee,s=this.evaluate(n.object,t);if(!(s instanceof Zi))throw Error("cannot assign attribute on non-namespace object");if(n.property.type!=="Identifier")throw Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Re}evaluateIf(e,t){let r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let r=new Cr(t),n,s;if(e.iterable.type==="SelectExpression"){let c=e.iterable;s=this.evaluate(c.lhs,r),n=c.test}else s=this.evaluate(e.iterable,r);if(!(s instanceof ge||s instanceof ut))throw Error(`Expected iterable or object type in for loop: got ${s.type}`);if(s instanceof ut)s=s.keys();let a=[],o=[];for(let c=0;c<s.value.length;++c){let d=new Cr(r),f=s.value[c],_;if(e.loopvar.type==="Identifier")_=(p)=>p.setVariable(e.loopvar.value,f);else if(e.loopvar.type==="TupleLiteral"){let p=e.loopvar;if(f.type!=="ArrayValue")throw Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(p.value.length!==w.value.length)throw Error(`Too ${p.value.length>w.value.length?"few":"many"} items to unpack`);_=(v)=>{for(let y=0;y<p.value.length;++y){if(p.value[y].type!=="Identifier")throw Error(`Cannot unpack non-identifier type: ${p.value[y].type}`);v.setVariable(p.value[y].value,w.value[y])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);if(n){if(_(d),!this.evaluate(n,d).__bool__().value)continue}a.push(f),o.push(_)}let i="",l=!0;for(let c=0;c<a.length;++c){let d=new Map([["index",new ie(c+1)],["index0",new ie(c)],["revindex",new ie(a.length-c)],["revindex0",new ie(a.length-c-1)],["first",new ae(c===0)],["last",new ae(c===a.length-1)],["length",new ie(a.length)],["previtem",c>0?a[c-1]:new De],["nextitem",c<a.length-1?a[c+1]:new De]]);r.setVariable("loop",new ut(d)),o[c](r);try{let f=this.evaluateBlock(e.body,r);i+=f.value}catch(f){if(f instanceof X_)continue;if(f instanceof Q_)break;throw f}l=!1}if(l){let c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new J(i)}bindMacroArguments(e,t,r,n,s){let a=n.slice(),o=new Map;if(a.at(-1)instanceof tn)o=new Map(a.pop().value);let i=[];for(let l=0;l<t.length;++l){let{name:c,defaultValue:d}=Li(t[l]),f=a[l];if(f===void 0&&o.has(c))f=o.get(c),o.delete(c);if(f===void 0&&d!==void 0)i.push([c,d]);s.setVariable(c,f??new De)}if(r.has("kwargs"))s.setVariable("kwargs",new ut(o));else if(o.size>0)throw Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(r.has("varargs"))s.setVariable("varargs",new ge(a.slice(t.length)));else if(a.length>t.length)throw Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(let[l,c]of i)s.setVariable(l,this.evaluate(c,s))}evaluateMacro(e,t){let r=ep(e.args,e.body);return t.setVariable(e.name.value,new ze((n,s)=>{let a=new Cr(s);return this.bindMacroArguments(`'${e.name.value}'`,e.args,r,n,a),this.evaluateBlock(e.body,a)})),new Re}evaluateCallStatement(e,t){let r=e.callerArgs??[],n=ep(r,e.body),s=new ze((c)=>{let d=new Cr(t);return this.bindMacroArguments("None",r,n,c,d),this.evaluateBlock(e.body,d)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new tn(o));let i=this.evaluate(e.call.callee,t);if(i.type!=="FunctionValue")throw Error(`Cannot call something that is not a function: got ${i.type}`);let l=new Cr(t);return l.setVariable("caller",s),i.value(a,l)}evaluateFilterStatement(e,t){let r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new De;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 Q_;case"Continue":throw new X_;case"IntegerLiteral":return new ie(e.value);case"FloatLiteral":return new Ce(e.value);case"StringLiteral":return new J(e.value);case"ArrayLiteral":return new ge(e.value.map((r)=>this.evaluate(r,t)));case"TupleLiteral":return new K_(e.value.map((r)=>this.evaluate(r,t)));case"ObjectLiteral":{let r=new Map;for(let[n,s]of e.value){let a=this.evaluate(n,t);if(!(a instanceof J))throw Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new ut(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Re;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function ia(e){switch(typeof e){case"number":return Number.isInteger(e)?new ie(e):new Ce(e);case"string":return new J(e);case"boolean":return new ae(e);case"undefined":return new De;case"object":if(e===null)return new Re;else if(Array.isArray(e))return new ge(e.map(ia));else return new ut(new Map(Object.entries(e).map(([t,r])=>[t,ia(r)])));case"function":return new ze((t,r)=>{let n=e(...t.map((s)=>s.value))??null;return ia(n)});default:throw Error(`Cannot convert to runtime value: ${e}`)}}var Je=`
|
|
20
|
+
`,Uk="{%- ",jk=" -%}",Ve=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function rm(e){switch(e.operator.type){case"ExponentiationBinaryOperator":return Ve.EXPONENTIATION;case"MultiplicativeBinaryOperator":return Ve.MULTIPLICATIVE;case"AdditiveBinaryOperator":return Ve.ADDITIVE;case"ComparisonBinaryOperator":return Ve.COMPARISON;case"Identifier":if(e.operator.value==="and")return Ve.LOGICAL_AND;if(e.operator.value==="in"||e.operator.value==="not in")return Ve.COMPARISON;return Ve.LOGICAL_OR}return Ve.LOGICAL_OR}function nm(e){switch(e.type){case"SelectExpression":case"Ternary":return Ve.CONDITIONAL;case"BinaryExpression":return rm(e);case"UnaryExpression":return e.operator.value==="not"?Ve.LOGICAL_NOT:Ve.UNARY_SIGN;case"TestExpression":return Ve.TEST;case"FilterExpression":return Ve.FILTER;default:return Ve.ATOM}}function Dt(e,t){let r=$e(e);return nm(e)<t?`(${r})`:r}function Wk(e,t="\t"){let r=typeof t==="number"?" ".repeat(t):t;return $t(e.body,0,r).replace(/\n$/,"")}function nt(...e){return Uk+e.join(" ")+jk}function $t(e,t,r){return e.map((n)=>qk(n,t,r)).join(Je)}function wa(e){return e.map((t)=>$e(t)).join(", ")}function qk(e,t,r){let n=r.repeat(t);switch(e.type){case"Program":return $t(e.body,t,r);case"If":return Hk(e,t,r);case"For":return Qk(e,t,r);case"Set":return Xk(e,t,r);case"Macro":return Yk(e,t,r);case"Break":return n+nt("break");case"Continue":return n+nt("continue");case"CallStatement":return Kk(e,t,r);case"FilterStatement":return Jk(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+$e(e)+" -}}"}}function Hk(e,t,r){let n=r.repeat(t),s=[],a=e;while(a)if(s.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If")a=a.alternate[0];else break;let o=n+nt("if",$e(s[0].test))+Je+$t(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=Je+n+nt("elif",$e(s[i].test))+Je+$t(s[i].body,t+1,r);if(a&&a.alternate.length>0)o+=Je+n+nt("else")+Je+$t(a.alternate,t+1,r);return o+=Je+n+nt("endif"),o}function Qk(e,t,r){let n=r.repeat(t),s="";if(e.iterable.type==="SelectExpression"){let o=e.iterable;s=`${$e(o.lhs)} if ${$e(o.test)}`}else s=$e(e.iterable);let a=n+nt("for",$e(e.loopvar),"in",s)+Je+$t(e.body,t+1,r);if(e.defaultBlock.length>0)a+=Je+n+nt("else")+Je+$t(e.defaultBlock,t+1,r);return a+=Je+n+nt("endfor"),a}function Xk(e,t,r){let n=r.repeat(t),s=$e(e.assignee),a=e.value?$e(e.value):"",o=n+nt("set",`${s}${e.value?" = "+a:""}`);if(e.body.length===0)return o;return o+Je+$t(e.body,t+1,r)+Je+n+nt("endset")}function Yk(e,t,r){let n=r.repeat(t),s=wa(e.args);return n+nt("macro",`${e.name.value}(${s})`)+Je+$t(e.body,t+1,r)+Je+n+nt("endmacro")}function Kk(e,t,r){let n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${wa(e.callerArgs)})`:"",a=$e(e.call),o=n+nt(`call${s}`,a)+Je;return o+=$t(e.body,t+1,r)+Je,o+=n+nt("endcall"),o}function Jk(e,t,r){let n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:$e(e.filter),a=n+nt("filter",s)+Je;return a+=$t(e.body,t+1,r)+Je,a+=n+nt("endfilter"),a}function $e(e){switch(e.type){case"SpreadExpression":return`*${$e(e.argument)}`;case"KeywordSpreadExpression":return`**${$e(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":{let t=e.value;if(Object.is(t,-0))return"-0.0";return t%1===0?t.toFixed(1):t.toString()}case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{let t=e,r=rm(t),n=Dt(t.left,r),s=Dt(t.right,r+1);return`${n} ${t.operator.value} ${s}`}case"UnaryExpression":{let t=e,r=t.argument.type==="UnaryExpression"?nm(t):Ve.ATOM;return t.operator.value+(t.operator.value==="not"?" ":"")+Dt(t.argument,r)}case"CallExpression":{let t=e,r=wa(t.args);return`${$e(t.callee)}(${r})`}case"MemberExpression":{let t=e,r=Dt(t.object,Ve.ATOM),n=$e(t.property);if(!t.computed&&t.property.type!=="Identifier"&&t.property.type!=="IntegerLiteral")n=`(${n})`;return t.computed?`${r}[${n}]`:`${r}.${n}`}case"FilterExpression":{let t=e,r=Dt(t.operand,Ve.FILTER);if(t.filter.type==="CallExpression")return`${r} | ${$e(t.filter)}`;return`${r} | ${t.filter.value}`}case"SelectExpression":{let t=e;return`${Dt(t.lhs,Ve.LOGICAL_OR)} if ${Dt(t.test,Ve.LOGICAL_OR)}`}case"TestExpression":{let t=e;return`${Dt(t.operand,Ve.TEST)} is${t.negate?" not":""} ${t.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let t=wa(e.value),r=e.type==="ArrayLiteral"?"[]":"()";return`${r[0]}${t}${r[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([r,n])=>`${$e(r)}: ${$e(n)}`).join(", ")}}`;case"SliceExpression":{let t=e,r=t.start?$e(t.start):"",n=t.stop?$e(t.stop):"",s=t.step?`:${$e(t.step)}`:"";return`${r}:${n}${s}`}case"KeywordArgumentExpression":{let t=e;return`${t.key.value}=${$e(t.value)}`}case"Ternary":{let t=e;return`${Dt(t.trueExpr,Ve.LOGICAL_OR)} if ${Dt(t.condition,Ve.LOGICAL_OR)} else ${Dt(t.falseExpr,Ve.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var Zk=class{parsed;constructor(e){let t=lk(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Fk(t)}render(e){let t=new Cr;if(Gk(t),e)for(let[s,a]of Object.entries(e))t.set(s,a);return new Vk(t).run(this.parsed).value}format(e){return Wk(this.parsed,e?.indent||"\t")}},eT={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"},va=class e{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=kt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=kt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();let n=kt.createReadStream(t);this.body=new ReadableStream({start(s){n.on("data",(a)=>s.enqueue(a)),n.on("end",()=>s.close()),n.on("error",(a)=>s.error(a))},cancel(){n.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",eT[t]??"application/octet-stream")}clone(){let t=new e(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 kt.promises.readFile(this.filePath)).buffer}async blob(){let t=await kt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await kt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Sa=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===void 0||e===null)if(pe.IS_CRYPTO_AVAILABLE){let o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;if(Number.isSafeInteger(e))e=Math.abs(e);let t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,n=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))n.push(o&4294967295);if(!n.length)n.push(0);t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let s=1,a=0;for(let o=Math.max(624,n.length);o>0;--o,++s,++a){if(s>=624)t[0]=t[623],s=1;if(a>=n.length)a=0;t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1664525))+n[a]+a>>>0}for(let o=623;o>0;--o,++s){if(s>=624)t[0]=t[623],s=1;t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1566083941))-s>>>0}t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let n=this.random()*2*Math.PI,s=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*s,this._gauss_next=Math.sin(n)*s}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){let r=32-Math.clz32(t+1),n=this._int32()>>>32-r;while(n>t)n=this._int32()>>>32-r;let s=e[t];e[t]=e[n],e[n]=s}}choices(e,t){return e[sm(this._random_fn,t)]}};function sm(e,t){let r=0;for(let s=0;s<t.length;++s)r+=t[s];let n=e()*r;for(let s=0;s<t.length;++s)if(n-=t[s],n<0)return s;return t.length-1}var er=new Sa,el=Object.freeze({Random:Sa,seed:er.seed.bind(er),random:er.random.bind(er),gauss:er.gauss.bind(er),shuffle:er.shuffle.bind(er),choices:er.choices.bind(er)}),tT=(e)=>sm(el.random,e),rT=new Sa,am=class{constructor(e){this.path=e}async match(e){let t=rr.join(this.path,e),r=new va(t);if(r.exists)return r;else return}async put(e,t,r=void 0){let n=rr.join(this.path,e),s=pe.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=rT._int32().toString(36),o=n+`.tmp.${s}.${a}`;try{let i=t.headers.get("Content-Length"),l=parseInt(i??"0"),c=0;await kt.promises.mkdir(rr.dirname(n),{recursive:!0});let d=kt.createWriteStream(o),f=t.body.getReader();while(!0){let{done:_,value:p}=await f.read();if(_)break;await new Promise((v,y)=>{d.write(p,(b)=>{if(b){y(b);return}v()})}),c+=p.length;let w=l?c/l*100:0;r?.({progress:w,loaded:c,total:l})}await new Promise((_,p)=>{d.close((w)=>w?p(w):_())}),await kt.promises.rename(o,n)}catch(i){try{await kt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=rr.join(this.path,e);try{return await kt.promises.unlink(t),!0}catch(r){return!1}}},nT={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"},tp=100,sT=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Zs(...e){return e=e.map((t,r)=>{if(r)t=t.replace(new RegExp("^/"),"");if(r!==e.length-1)t=t.replace(new RegExp("/$"),"");return t}),e.join("/")}function rn(e,t=null,r=null){let n;try{n=new URL(e)}catch(s){return!1}if(t&&!t.includes(n.protocol))return!1;if(r&&!r.includes(n.hostname))return!1;return!0}function aT(e){if(!sT.test(e))return!1;if(e.includes("..")||e.includes("--"))return!1;if(e.endsWith(".git")||e.endsWith(".ipynb"))return!1;return!0}function tl(e,t={},...r){return JSON.stringify([e,t.revision??"main",t.cache_dir??null,t.local_files_only??!1,...r])}var Oi=class extends Error{constructor(e,{status:t=null}={}){super(e);this.name="ModelFileNotFoundError",this.status=t}},oT=new Set([401,403,404]);function om(e,t,r){if(!r)return null;let s=`${nT[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;if(oT.has(e))throw new Oi(s,{status:e});throw Error(s)}async function iT(e,t,r){let n=e.headers.get("Content-Length"),s=n?parseInt(n,10):r??0;if(n===null&&!r)ce.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),o=0,i=e.body.getReader();async function l(){let{done:c,value:d}=await i.read();if(c)return;let f=o+d.length;if(f>s){s=f;let p=new Uint8Array(s);p.set(a),a=p}a.set(d,o),o=f;let _=o/s*100;return t({progress:_,loaded:o,total:s}),l()}return await l(),a}function rp(e){return rn(e,["blob:"])}function Ni(e,{allowUnresolved:t=!1}={}){let r;if(typeof location<"u"&&location.href)r=location.href;else if(typeof import.meta<"u"&&import.meta.url)r=import.meta.url;else return e;try{return new URL(e,r).href}catch(n){if(!t)throw n;return e}}var im="SHA-256",lT="experimental_transformers-hash-cache",np=(e)=>({algorithm:im,value:e}),sp=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(lT),this.#t);static isAvailable=()=>typeof navigator<"u"&&("crossOriginStorage"in navigator);match=async(e)=>{let t=await this._getFileHash(e);if(!t)return;try{let n=await(await navigator.crossOriginStorage.requestFileHandle(np(t))).getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,t)=>{let r=await this._getFileHash(e);if(r){let n=await t.blob();await this._storeBlobInCOS(n,r)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(np(t),{create:!0,origins:"*"})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let r=[];for await(let a of t)r.push(a);let n=new Blob(r),s=await this._getBlobHash(n);await this._storeBlobInCOS(n,s);try{await(await this._getHashCache()).put(e,new Response(s))}catch{}}catch{}};delete=async(e)=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async(e)=>{try{let t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();let n=await this._getLfsFileHash(e);if(n)return await t.put(e,new Response(n)),n;return null}catch{return null}};_getLfsFileHash=async(e)=>{if(!e.includes("/resolve/"))return null;let t=e.replace("/resolve/","/raw/");try{let n=(await fetch(t).then((s)=>s.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async(e)=>{let t=await e.arrayBuffer(),r=await crypto.subtle.digest(im,t);return Array.from(new Uint8Array(r)).map((s)=>s.toString(16).padStart(2,"0")).join("")}};async function rl(e=null){let t=null;if(ve.useCustomCache){if(!ve.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ve.customCache.match||!ve.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=ve.customCache}if(!t&&ve.experimental_useCrossOriginStorage&&sp.isAvailable())t=new sp;if(!t&&ve.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ve.cacheKey)}catch(r){ce.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ve.useFSCache){if(!pe.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new am(e??ve.cacheDir)}return t}async function cT(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch(n){continue}return}var uT=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){if(this.#e.has(e))this.#e.delete(e);if(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()}},dT=100,yi=new uT(dT);function lm(e,t){let r=yi.get(e);if(r!==void 0)return r;let n=t().then((s)=>s,(s)=>(yi.delete(e),Promise.reject(s)));return yi.put(e,n),n}async function fT(e){if(!rn(e,["http:","https:"]))return null;let t=cm(e);return t.set("Range","bytes=0-0"),ve.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function ms(e,t,r={}){let n=tl(e,r,t);return lm(n,()=>hT(e,t,r))}async function hT(e,t,r){let n=await rl(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=um(e,t,r,n),l=await dm(n,s,o);if(l!==void 0&&typeof l!=="string"){let 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(ve.allowLocalModels){if(!rn(s,["http:","https:"]))try{let d=await cs(s);if(typeof d!=="string"&&d.status!==404){let f=d.headers.get("content-length"),_=d.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch(d){}}if(ve.allowRemoteModels&&!r.local_files_only&&i){let c=await fT(a);if(c&&c.status>=200&&c.status<300){let d,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let p=_.match(/bytes \d+-\d+\/(\d+)/);if(p)d=parseInt(p[1],10)}}else if(c.status===200)try{await c.body?.cancel()}catch(_){}if(d===void 0){let _=c.headers.get("content-length");d=_?parseInt(_,10):void 0}return{exists:!0,size:d,contentType:f||void 0,fromCache:!1}}if(c&&c.status!==404&&c.status!==416)om(c.status,a,!0)}return{exists:!1,fromCache:!1}}async function cs(e){if(ve.useFS&&!rn(e,["http:","https:","blob:"]))return new va(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e);else return ve.fetch(e,{headers:cm(e)})}function cm(e){let t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){let n=!!process.env?.TESTING_REMOTELY,s=ve.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),rn(e,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;if(o)r.set("Authorization",`Bearer ${o}`)}}return r}function um(e,t,r={},n=null){let s=r.revision??"main",a=Zs(e,t),o=aT(e),i=o?Zs(ve.localModelPath,a):a,l=Zs(ve.remoteHost,ve.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),c=n instanceof am?s==="main"?a:Zs(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function dm(e,t,r){if(!e)return;return await cT(e,t,r)}async function _T(e,t,r,n,s,a,o={}){if(await r.match(n)!==void 0)return;if(typeof Cache<"u"&&r instanceof Cache&&!rn(Ni(n,{allowUnresolved:!0}),["http:","https:"]))return;if(!a){let i=o.progress_callback?(l)=>Pr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}else if(typeof s!=="string"){let i=new Headers(s.headers);i.set("content-length",a.byteLength.toString()),await r.put(n,new Response(a,{headers:i})).catch((l)=>{ce.warn(`Unable to add response to browser cache: ${l}.`)})}}async function pT(e,t,r=!0,n={},s=!1,a=null){let{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=um(e,t,n,a),f,_=!1,p;p=await dm(a,i,c);let w=p!==void 0;if(w)f=c;else{if(ve.allowLocalModels){if(!rn(o,["http:","https:"]))try{p=await cs(i),f=i}catch(k){ce.warn(`Unable to load from local path "${i}": "${k}"`)}else if(n.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!ve.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=="string"&&p.status===404){if(n.local_files_only||!ve.allowRemoteModels)if(r)throw new Oi(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);else return null;if(!d)throw new Oi(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await cs(l),p.status!==200)return om(p.status,l,r);f=c}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200}Pr(n.progress_callback,{status:"download",name:e,file:t});let v;if(pe.IS_NODE_ENV&&s);else{let b;if(typeof p!=="string")if(!n.progress_callback)b=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))b=new Uint8Array(await p.arrayBuffer()),Pr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:b.length,total:b.length});else{let k,A=p.headers.get("content-length");if(A)k=parseInt(A,10);else try{let E=await ms(e,t,n);if(E.size)k=E.size}catch(E){}b=await iT(p,(E)=>{Pr(n.progress_callback,{status:"progress",name:e,file:t,...E})},k)}v=b}if(_&&f&&typeof p!=="string")await _T(e,t,a,f,p,v,n);if(pe.IS_NODE_ENV&&s&&n.progress_callback&&typeof p!=="string"){let b=parseInt(p.headers.get("content-length"),10)||0;Pr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:b,total:b})}if(Pr(n.progress_callback,{status:"done",name:e,file:t}),v){if(!pe.IS_NODE_ENV&&s)throw Error("Cannot return path in a browser environment.");return v}if(p instanceof va)return p.filePath;let y=await a?.match(f);if(y instanceof va)return y.filePath;else if(y instanceof Response)return new Uint8Array(await y.arrayBuffer());else if(typeof y==="string")return y;throw Error("Unable to get model file path or buffer.")}var bi=new Map;async function ya(e,t,r=!0,n={},s=!1){if(!ve.allowLocalModels){if(n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");else if(!ve.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let a=tl(e,n,t,r,s),{progress_callback:o}=n,i=o instanceof da?o.loads:bi,l=i.get(a);if(!l){if(Pr(o,{status:"initiate",name:e,file:t}),l=rl(n.cache_dir).then((c)=>pT(e,t,r,n,s,c)),i===bi)l=l.finally(()=>bi.delete(a));i.set(a,l)}return await l}async function nl(e,t,r=!0,n={}){let s=await ya(e,t,r,n,!1);if(s===null)return null;return new TextDecoder("utf-8").decode(s)}async function ar(e,t,r=!0,n={}){let s=await nl(e,t,r,n);if(s===null)return{};return JSON.parse(s)}function mT(e,[t,r,n],[s,a],o="bilinear",i=!1){let l=a/n,c=s/r,d=new e.constructor(s*a*t),f=r*n,_=s*a;for(let p=0;p<s;++p)for(let w=0;w<a;++w){let v=p*a+w,y=(w+0.5)/l-0.5,b=(p+0.5)/c-0.5,k=Math.floor(y),A=Math.floor(b),E=Math.min(k+1,n-1),C=Math.min(A+1,r-1);k=Math.max(k,0),A=Math.max(A,0);let N=y-k,M=b-A,G=(1-N)*(1-M),R=N*(1-M),q=(1-N)*M,X=N*M,Q=A*n,H=C*n,B=Q+k,P=Q+E,Y=H+k,ue=H+E;for(let Z=0;Z<t;++Z){let se=Z*f;d[Z*_+v]=G*e[se+B]+R*e[se+P]+q*e[se+Y]+X*e[se+ue]}}return d}function gT(e,t,r){let n=Array(r.length),s=Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)s[i]=l,n[i]=t[r[i]],l*=n[i];let a=r.map((i,l)=>s[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);o[l]=e[i]}return[o,n]}function st(e){let t=qe(e)[0],r=e.map((a)=>Math.exp(a-t)),n=r.reduce((a,o)=>a+o,0);return r.map((a)=>a/n)}function wT(e){let t=qe(e)[0],r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);let n=Math.log(r);return e.map((a)=>a-t-n)}function Di(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)if(e[n]<t)t=e[n],r=n;return[t,r]}function qe(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)if(e[n]>t)t=e[n],r=n;return[t,r]}function fm(e){return e>0&&(e&e-1)===0}var hm=class{constructor(e){if(this.size=e|0,this.size<=1||!fm(this.size))throw 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){let n=Math.PI*r/this.size;this.table[r]=Math.cos(n),this.table[r+1]=-Math.sin(n)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let n=0;n<this._width;n+=2){let s=this._width-n-2;this._bitrev[r]|=(r>>>n&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let r=t||Array(e.length>>>1);for(let n=0;n<e.length;n+=2)r[n>>>1]=e[n];return r}toComplexArray(e,t){let r=t||this.createComplexArray();for(let n=0;n<r.length;n+=2)r[n]=e[n>>>1],r[n+1]=0;return r}transform(e,t){if(e===t)throw Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw 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){let n=this._csize,a=1<<this._width,o=n/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){let f=c[l];this._singleTransform2(t,e,i,f,a)}else for(i=0,l=0;i<n;i+=o,++l){let f=c[l];this._singleTransform4(t,e,i,f,a,r)}let d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;let f=o>>>2;for(i=0;i<n;i+=o){let _=i+f-1;for(let p=i,w=0;p<_;p+=2,w+=a){let v=p,y=v+f,b=y+f,k=b+f,A=e[v],E=e[v+1],C=e[y],N=e[y+1],M=e[b],G=e[b+1],R=e[k],q=e[k+1],X=d[w],Q=r*d[w+1],H=C*X-N*Q,B=C*Q+N*X,P=d[2*w],Y=r*d[2*w+1],ue=M*P-G*Y,Z=M*Y+G*P,se=d[3*w],L=r*d[3*w+1],O=R*se-q*L,V=R*L+q*se,de=A+ue,te=E+Z,We=A-ue,Fe=E-Z,be=H+O,Ge=B+V,Oe=r*(H-O),Me=r*(B-V);e[v]=de+be,e[v+1]=te+Ge,e[y]=We+Me,e[y+1]=Fe-Oe,e[b]=de-be,e[b+1]=te-Ge,e[k]=We-Me,e[k+1]=Fe+Oe}}}}_singleTransform2(e,t,r,n,s){let a=e[n],o=e[n+1],i=e[n+s],l=e[n+s+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,n,s,a){let o=s*2,i=s*3,l=e[n],c=e[n+1],d=e[n+s],f=e[n+s+1],_=e[n+o],p=e[n+o+1],w=e[n+i],v=e[n+i+1],y=l+_,b=c+p,k=l-_,A=c-p,E=d+w,C=f+v,N=a*(d-w),M=a*(f-v);t[r]=y+E,t[r+1]=b+C,t[r+2]=k+M,t[r+3]=A-N,t[r+4]=y-E,t[r+5]=b-C,t[r+6]=k-M,t[r+7]=A+N}_realTransform4(e,t,r){let n=this._csize,a=1<<this._width,o=n/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){let _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<n;i+=o,++l){let _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,r)}let d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;let _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<n;i+=o)for(let v=0,y=0;v<=w;v+=2,y+=a){let b=i+v,k=b+p,A=k+p,E=A+p,C=e[b],N=e[b+1],M=e[k],G=e[k+1],R=e[A],q=e[A+1],X=e[E],Q=e[E+1],H=C,B=N,P=d[y],Y=r*d[y+1],ue=M*P-G*Y,Z=M*Y+G*P,se=d[2*y],L=r*d[2*y+1],O=R*se-q*L,V=R*L+q*se,de=d[3*y],te=r*d[3*y+1],We=X*de-Q*te,Fe=X*te+Q*de,be=H+O,Ge=B+V,Oe=H-O,Me=B-V,Ye=ue+We,Xt=Z+Fe,xe=r*(ue-We),Ie=r*(Z-Fe);if(e[b]=be+Ye,e[b+1]=Ge+Xt,e[k]=Oe+Ie,e[k+1]=Me-xe,v===0){e[A]=be-Ye,e[A+1]=Ge-Xt;continue}if(v===w)continue;let sn=i+p-v,Wn=i+_-v;e[sn]=Oe-r*Ie,e[sn+1]=-Me-r*xe,e[Wn]=be-r*Ye,e[Wn+1]=-Ge+r*Xt}}let f=n>>>1;for(let _=2;_<f;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,t,r,n,s){let a=e[n],o=e[n+s];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,n,s,a){let o=s*2,i=s*3,l=e[n],c=e[n+s],d=e[n+o],f=e[n+i],_=l+d,p=l-d,w=c+f,v=a*(c-f);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}},vT=class{constructor(e){let t=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=t;let s=new Float64Array(r),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){let d=(c+1-e)**2/2,f=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),p=2*c;s[p]=f*Math.cos(_),s[p+1]=f*Math.sin(_),a[p]=s[p],a[p+1]=-s[p+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new hm(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){let n=this._buffer1,s=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(r)for(let d=0;d<l.length;d+=2){let f=d+1,_=d>>1,p=t[_];n[d]=p*l[d],n[f]=p*l[f]}else for(let d=0;d<l.length;d+=2){let f=d+1;n[d]=t[d]*l[d]-t[f]*l[f],n[f]=t[d]*l[f]+t[f]*l[d]}this._f.transform(a,n);for(let d=0;d<i.length;d+=2){let f=d+1;s[d]=a[d]*i[d]-a[f]*i[f],s[f]=a[d]*i[f]+a[f]*i[d]}this._f.inverseTransform(o,s);for(let d=0;d<o.length;d+=2){let f=o[d+c],_=o[d+c+1],p=l[d],w=l[d+1];e[d]=f*p-_*w,e[d+1]=f*w+_*p}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},yT=class{constructor(e){if(this.fft_length=e,this.isPowerOfTwo=fm(e),this.isPowerOfTwo)this.fft=new hm(e),this.outputBufferSize=2*e;else this.fft=new vT(e),this.outputBufferSize=this.fft.bufferSize}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function bT(e,t){if(t%2===0||t<=0)throw Error("Window size must be a positive odd number");let r=new e.constructor(e.length),n=new e.constructor(t),s=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-s;i<=s;++i){let l=a+i;if(l<0)l=Math.abs(l);else if(l>=e.length)l=2*(e.length-1)-l;n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function as(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}function MT(e){let t=Math.round(e);return Math.abs(e)%1===0.5?t%2===0?t:t-1:t}function xT(e){let t=e.length,r=e[0].length,n=[t+1,r+1],s=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));s[0][0]=0;let a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let d=1;d<n[1];++d)for(let f=1;f<n[0];++f){let _=s[f-1][d-1],p=s[f-1][d],w=s[f][d-1],v,y;if(_<p&&_<w)v=_,y=0;else if(p<_&&p<w)v=p,y=1;else v=w,y=2;s[f][d]=e[f-1][d-1]+v,a[f][d]=y}for(let d=0;d<n[1];++d)a[0][d]=2;for(let d=0;d<n[0];++d)a[d][0]=1;let o=t,i=r,l=[],c=[];while(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 Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var kT=function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0,d=(l&32768)<<16,f=(l&31744)>>10,_=l&1023;if(f===31)c=d|2139095040|_<<13;else if(f===0)if(_===0)c=d;else{let p=113;while((_&1024)===0)_<<=1,--p;_&=-1025,c=d|p<<23|_<<13}else c=d|f+112<<23|_<<13;o[0]=c,e[l]=i[0]}}let r=t.length,n=e,s=new Float32Array(r);for(let a=0;a<r;++a)s[a]=n[t[a]];return s}}(),TT={};async function _m(e){let t=e.split("/").pop(),r;try{if(r=await rl(),r){let s=await r.match(e);if(s)return s}}catch(s){ce.warn(`Failed to load ${t} from cache:`,s)}let n=await ve.fetch(e);if(!n.ok)throw Error(`Failed to fetch ${t}: ${n.status} ${n.statusText}`);if(r)try{await r.put(e,n.clone())}catch(s){ce.warn(`Failed to cache ${t}:`,s)}return n}async function ET(e){let t=await _m(e);if(!t||typeof t==="string")return null;try{return await t.arrayBuffer()}catch(r){return ce.warn("Failed to read WASM binary:",r),null}}async function AT(e){if(pe.IS_SERVICE_WORKER_ENV||pe.IS_CHROME_AVAILABLE)return e;let t=await _m(e);if(!t||typeof t==="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return ce.warn("Failed to read WASM factory:",r),null}}var CT=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 pm(e){if(e<=zt.DEBUG)return 0;else if(e<=zt.INFO)return 2;else if(e<=zt.WARNING)return 3;else if(e<=zt.ERROR)return 3;else return 4}var ST={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},xt=[],zi,kn,ap=Symbol.for("onnxruntime");if(ap in globalThis)kn=globalThis[ap];else if(pe.IS_NODE_ENV){switch(kn=TT,process.platform){case"win32":xt.push("dml");break;case"linux":if(process.arch==="x64")xt.push("cuda");break;case"darwin":xt.push("coreml");break}xt.push("webgpu"),xt.push("cpu"),zi=["cpu"]}else{if(kn=_i,pe.IS_WEBNN_AVAILABLE)xt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn");if(pe.IS_WEBGPU_AVAILABLE)xt.push("webgpu");xt.push("wasm"),zi=["wasm"]}function PT(){return[...xt]}var FT=kn.InferenceSession;function IT(e=null){if(!e)return zi;switch(e){case"auto":return xt;case"gpu":return xt.filter((t)=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(xt.includes(e))return[CT[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${xt.join(", ")}.`)}var op=Promise.resolve(),mn=null;async function LT(){if(mn)return mn;if(!(ve.useWasmCache&&typeof Ke?.wasm?.wasmPaths==="object"&&Ke?.wasm?.wasmPaths?.wasm&&Ke?.wasm?.wasmPaths?.mjs)){if(pe.IS_DENO_WEB_RUNTIME)throw Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return mn=Promise.resolve(),mn}return mn=(async()=>{let t=Ke.wasm.wasmPaths,r=!1;if(await Promise.all([t.wasm&&!rp(t.wasm)?(async()=>{try{let n=await ET(Ni(t.wasm));if(n)Ke.wasm.wasmBinary=n,r=!0}catch(n){ce.warn("Failed to pre-load WASM binary:",n)}})():Promise.resolve(),t.mjs&&!rp(t.mjs)?(async()=>{try{let n=await AT(Ni(t.mjs));if(n)Ke.wasm.wasmPaths.mjs=n}catch(n){ce.warn("Failed to pre-load WASM factory:",n)}})():Promise.resolve()]),!r)Ke.wasm.wasmPaths.mjs=t.mjs})(),mn}async function mm(e,t,r){await LT();let n=pm(ve.logLevel??zt.WARNING),s=()=>FT.create(e,{logSeverityLevel:n,...t}),a=await(pe.IS_WEB_ENV?op=op.then(s):s());return a.config=r,a}var ip=Promise.resolve();async function gm(e,t){let r=()=>e.run(t);return pe.IS_WEB_ENV?ip=ip.then(r):r()}function wm(e){return e instanceof kn.Tensor}var Ke=kn?.env;function sl(){return Ke?.wasm?.proxy}if(Ke){let e=function(t){let r=pm(t);Ke.logLevel=ST[r]};if(Ke.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Ke.versions?.web&&!Ke.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ke.versions.web}/dist/`,r=".asyncify";if(pe.IS_SAFARI_BELOW_26&&!pe.IS_WEBGPU_AVAILABLE)r="";Ke.wasm.wasmPaths={mjs:`${t}ort-wasm-simd-threaded${r}.mjs`,wasm:`${t}ort-wasm-simd-threaded${r}.wasm`}}Ke.wasm.proxy=!1}if(Ke.webgpu)Ke.webgpu.powerPreference="high-performance";e(ve.logLevel??zt.WARNING),ve.backends.onnx={...Ke,setLogLevel:e,getSupportedDevices:PT}}var Ar=async(e,t,r)=>{let n=await mm(new Uint8Array(e),t);return async(s)=>{let a=sl(),o=Object.fromEntries(Object.entries(s).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await gm(n,o);if(Array.isArray(r))return r.map((l)=>new U(i[l]));else return new U(i[r])}},Tn=class{static session_options={};static get nearest_interpolate_4d(){if(!this._nearest_interpolate_4d)this._nearest_interpolate_4d=Ar([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");return this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){if(!this._bilinear_interpolate_4d)this._bilinear_interpolate_4d=Ar([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");return this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){if(!this._bicubic_interpolate_4d)this._bicubic_interpolate_4d=Ar([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");return this._bicubic_interpolate_4d}static get matmul(){if(!this._matmul)this._matmul=Ar([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");return this._matmul}static get stft(){if(!this._stft)this._stft=Ar([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");return this._stft}static get rfft(){if(!this._rfft)this._rfft=Ar([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,"y");return this._rfft}static get top_k(){if(!this._top_k)this._top_k=Ar([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"]);return this._top_k}static get slice(){if(!this._slice)this._slice=Ar([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");return this._slice}},OT=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"}),Mi=pe.IS_NODE_ENV?"cpu":"wasm";function vm(e,t,{warn:r}={}){if(!e)return Mi;if(typeof e==="string")return e;if(e.hasOwnProperty(t))return e[t];if(r)r(`device not specified for "${t}". Using the default device (${Mi}).`);return Mi}var NT=function(){let e;return async function(){if(e===void 0)if(!pe.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch(t){e=!1}return e}}(),Qe=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"}),lp=Qe.fp32,cp=Object.freeze({[OT.wasm]:Qe.q8}),ba=Object.freeze({[Qe.fp32]:"",[Qe.fp16]:"_fp16",[Qe.int8]:"_int8",[Qe.uint8]:"_uint8",[Qe.q8]:"_quantized",[Qe.q4]:"_q4",[Qe.q2]:"_q2",[Qe.q1]:"_q1",[Qe.q4f16]:"_q4f16",[Qe.q2f16]:"_q2f16",[Qe.q1f16]:"_q1f16",[Qe.bnb4]:"_bnb4"});function ym(e,t,r,{configDtype:n=null,warn:s}={}){let a,o=!1;if(e&&typeof e!=="string")if(e.hasOwnProperty(t))a=e[t];else a=null,o=!0;else a=e;let i;if(a===Qe.auto){if(n){let l=typeof n==="string"?n:n?.[t];if(l&&l!==Qe.auto&&Qe.hasOwnProperty(l))return l}i=cp[r]??lp}else if(a&&Qe.hasOwnProperty(a))i=a;else i=cp[r]??lp;if(o&&s)s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`);return i}var us=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),U=class e{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){if(wm(t[0]))this.ort_tensor=t[0];else this.ort_tensor=new gi(t[0],t[1],t[2]);return new Proxy(this,{get:(r,n)=>{if(typeof n==="string"){let s=Number(n);if(Number.isInteger(s))return r._getitem(s)}return r[n]},set:(r,n,s)=>r[n]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[t,...r]=this.dims;if(r.length>0){let n=r.reduce((s,a)=>s*a);for(let s=0;s<t;++s)yield this._subarray(s,n,r)}else yield*this.data}_getitem(t){let[r,...n]=this.dims;if(t=tr(t,r),n.length>0){let s=n.reduce((a,o)=>a*o);return this._subarray(t,s,n)}else return new e(this.type,[this.data[t]],n)}_subarray(t,r,n){let s=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(s,a):this.data.slice(s,a);return new e(this.type,o,n)}item(){let t=this.data;if(t.length!==1)throw Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return DT(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let 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){let r=this.data;for(let n=0;n<r.length;++n)r[n]=t(r[n],n,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]*=t;return this}div(t){return this.clone().div_(t)}div_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]/=t;return this}add(t){return this.clone().add_(t)}add_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]-=t;return this}remainder(t){return this.clone().remainder_(t)}remainder_(t){let r=this.data,s=r instanceof BigInt64Array||r instanceof BigUint64Array?BigInt(t):Number(t);if((s===0||s===0n)&&(this.type.includes("int")||this.type==="bool"))throw RangeError("Division by zero");if(s<0&&(this.type.startsWith("uint")||this.type==="bool"))throw RangeError("Negative divisors are not supported for unsigned or boolean tensors");for(let a=0;a<r.length;++a){let o=r[a]%s,i=o<0&&s>0||o>0&&s<0;r[a]=i?o+s:o}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let r=[],n=[];for(let d=0;d<this.dims.length;++d){let f=t[d];if(f===null||f===void 0)n.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof f==="number")f=tr(f,this.dims[d],d),n.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[_,p]=f;if(_=_===null?0:tr(_,this.dims[d],d,!1),p=p===null?this.dims[d]:tr(p,this.dims[d],d,!1),_>p)throw Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(p,this.dims[d])];n.push(w),r.push(w[1]-w[0])}else throw Error(`Invalid slice: ${f}`)}let s=n.map(([d,f])=>f-d),a=s.reduce((d,f)=>d*f),o=this.data,i=new o.constructor(a),l=this.stride(),c=!0;for(let d=1;d<s.length;++d)if(n[d][0]!==0||n[d][1]!==this.dims[d]){c=!1;break}if(c){let d=n[0][0]*l[0],f=n[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,f));else if(Array.isArray(o)){let _=o.slice(d,f);for(let p=0;p<_.length;++p)i[p]=_[p]}else throw Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let f=0;for(let _=s.length-1,p=d;_>=0;--_){let w=s[_];f+=(p%w+n[_][0])*l[_],p=Math.floor(p/w)}i[d]=o[f]}return new e(this.type,i,r)}permute(...t){return zT(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,n=!1){if(t==="fro")t=2;else if(typeof t==="string")throw Error(`Unsupported norm: ${t}`);let s=this.data,a=s instanceof BigInt64Array||s instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a)o=(f,_)=>f+_,i=0n;else o=(f,_)=>f+_**t,i=0;if(r===null){let f=s.reduce(o,i);if(t!==1)f=f**(1/t);return new e(this.type,[f],[])}let[l,c,d]=is(o,this,r,n);if(t!==1)for(let f=0;f<c.length;++f)c[f]=c[f]**(1/t);return new e(l,c,d)}normalize_(t=2,r=1){r=tr(r,this.dims.length);let n=this.norm(t,r,!0),s=this.data,a=n.data;for(let o=0;o<s.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*d,d*=this.dims[l]}c=Math.floor(c/f)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return xi(this.dims)}squeeze(t=null){return new e(this.type,this.data,up(this.dims,t))}squeeze_(t=null){return this.dims=up(this.dims,t),this}unsqueeze(t){return new e(this.type,this.data,dp(this.dims,t))}unsqueeze_(t){return this.dims=dp(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;s<t.length;++s)if(t[s]===-1){if(r!==-1)throw Error("Only one dimension can be inferred");r=s}let n=this.data;if(r!==-1){let s=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=n.length/s}return new e(this.type,n,t)}neg_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){let r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]>t?1:0;return new e("bool",r,this.dims)}lt(t){let r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]<t?1:0;return new e("bool",r,this.dims)}clamp_(t,r){let n=this.data;for(let s=0;s<n.length;++s)n[s]=Math.min(Math.max(n[s],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){let 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 al(this,t,r)}min(t=null,r=!1){if(t===null){let o=Di(this.data)[0];return new e(this.type,[o],[])}let[n,s,a]=is((o,i)=>Math.min(o,i),this,t,r,1/0);return new e(n,s,a)}max(t=null,r=!1){if(t===null){let o=qe(this.data)[0];return new e(this.type,[o],[])}let[n,s,a]=is((o,i)=>Math.max(o,i),this,t,r,-1/0);return new e(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let n=Di(this.data)[1];return new e("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let n=qe(this.data)[1];return new e("int64",[BigInt(n)],[])}repeat(...t){if(t.length<this.dims.length)throw 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();let d=t.length-this.dims.length,f=Array(d).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),f)}let r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((d,f)=>d*t[f]),a=s.reduce((d,f)=>d*f,1),o=this.data,i=new o.constructor(a),l=xi(n),c=xi(s);for(let d=0;d<a;++d){let f=d,_=0;for(let p=0;p<s.length;++p){let w=Math.floor(f/c[p]);f=f%c[p];let v=w%n[p];_+=v*l[p]}i[d]=o[_]}return new e(this.type,i,s)}tile(...t){if(t.length<this.dims.length){let 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(!us.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let r,n=["int64","uint64"].includes(this.type),s=["int64","uint64"].includes(t);if(n&&!s)r=Number;else if(!n&&s)if(["float16","float32","float64"].includes(this.type))r=(a)=>BigInt(Math.floor(a));else r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new e(t,kT(this.data),this.dims);return new e(t,us[t].from(this.data,r),this.dims)}};function DT(e,t){let r=e.length,n=t.length===0?1:t.reduce((a,o)=>a*o);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let a=t.length-1;a>=0;a--)s=s.reduce((o,i)=>{let l=o[o.length-1];if(l.length<t[a])l.push(i);else o.push([i]);return o},[[]]);return s[0]}function zT(e,t){let[r,n]=gT(e.data,e.dims,t);return new U(e.type,r,n)}function bm(e,[t,r],n="bilinear",s=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=mT(e.data,[a,o,i],[t,r],n,s);return new U(e.type,l,[a,t,r])}async function Gt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw Error("`interpolate_4d` requires a `size` argument.");let n;if(t.length===2)n=[...e.dims.slice(0,2),...t];else if(t.length===3)n=[e.dims[0],...t];else if(t.length===4)n=t;else throw Error("`size` must be of length 2, 3, or 4.");let s;if(r==="nearest")s=await Tn.nearest_interpolate_4d;else if(r==="bilinear")s=await Tn.bilinear_interpolate_4d;else if(r==="bicubic")s=await Tn.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${r}`);let a=new U("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await s({x:e,s:a})}async function BT(e,t){return await(await Tn.matmul)({a:e,b:t})}async function Pn(e,t){let r=await Tn.top_k;if(t==null)t=e.dims.at(-1);else t=Math.min(t,e.dims.at(-1));return await r({x:e,k:new U("int64",[BigInt(t)],[1])})}var ea=(e)=>new U("int64",e,[e.length]);async function Mm(e,t,r,n,s){return await(await Tn.slice)({x:e,s:ea(t),e:ea(r),a:ea(n),t:ea(s??Array(n.length).fill(1))})}function RT(e,t){let r=e.data,n=t.data,s=[e.dims[0],e.dims[2]],a=new r.constructor(s[0]*s[1]),[o,i,l]=e.dims,c=0;for(let d=0;d<o;++d){let f=d*l*i;for(let _=0;_<l;++_){let p=0,w=0,v=d*i,y=f+_;for(let k=0;k<i;++k){let A=Number(n[v+k]);w+=A,p+=r[y+k*l]*A}let b=p/w;a[c++]=b}}return new U(e.type,a,s)}function up(e,t){if(e=e.slice(),t===null)e=e.filter((r)=>r!==1);else if(typeof t==="number"){if(e[t]===1)e.splice(t,1)}else if(Array.isArray(t))e=e.filter((r,n)=>r!==1||!t.includes(n));return e}function dp(e,t){return t=tr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function tr(e,t,r=null,n=!0){if(e<-t||e>=t)if(n)throw Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);else return e<-t?0:t;if(e<0)e=(e%t+t)%t;return e}function Ne(e,t=0){t=tr(t,e[0].dims.length);let r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);let n=r.reduce((o,i)=>o*i,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let o=0;for(let i of e){let l=i.data;s.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){let{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let f=0;for(let _=c.length-1,p=d,w=1;_>=0;--_){let v=c[_],y=p%v;if(_===t)y+=o;f+=y*w,w*=r[_],p=Math.floor(p/v)}s[f]=l[d]}o+=c[t]}}return new U(a,s,r)}function _r(e,t=0){return Ne(e.map((r)=>r.unsqueeze(t)),t)}function is(e,t,r,n=!1,s=null){let{data:a,dims:o}=t;r=tr(r,o.length);let i=o.slice();i[r]=1;let l=new a.constructor(a.length/o[r]);if(s!==null)l.fill(s);for(let c=0;c<a.length;++c){let d=0;for(let f=o.length-1,_=c,p=1;f>=0;--f){let w=o[f];if(f!==r){let v=_%w;d+=v*p,p*=i[f]}_=Math.floor(_/w)}l[d]=e(l[d],a[c],c,d)}if(!n)i.splice(r,1);return[t.type,l,i]}function $T(e,t=null,r=1,n=!1){let{data:s,dims:a}=e;if(t===null){let p=s.reduce((b,k)=>b+k,0)/s.length,w=Math.sqrt(s.reduce((b,k)=>b+(k-p)**2,0)/(s.length-r)),v=new U(e.type,[p],[]);return[new U(e.type,[w],[]),v]}t=tr(t,a.length);let o=al(e,t,n),i=o.data,[l,c,d]=is((_,p,w,v)=>_+(p-i[v])**2,e,t,n);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return[new U(l,c,d),o]}function al(e,t=null,r=!1){let{dims:n,data:s}=e;if(t===null){let l=s.reduce((c,d)=>c+d,0);return new U(e.type,[l/s.length],[])}t=tr(t,n.length);let[a,o,i]=is((l,c)=>l+c,e,t,r);if(n[t]!==1)for(let l=0;l<o.length;++l)o[l]/=n[t];return new U(a,o,i)}function xi(e){let t=Array(e.length);for(let r=e.length-1,n=1;r>=0;--r)t[r]=n,n*=e[r];return t}function ol(e,t,r,n){let s=e.reduce((a,o)=>a*o,1);return new U(r,new n(s).fill(t),e)}function dt(e,t){let r,n;if(typeof t==="number")r="float32",n=Float32Array;else if(typeof t==="bigint")r="int64",n=BigInt64Array;else if(typeof t==="boolean")r="bool",n=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return ol(e,t,r,n)}function Bi(e,t){return dt(e.dims,t)}function gt(e){return ol(e,1n,"int64",BigInt64Array)}function il(e){return gt(e.dims)}function xm(e){return ol(e,0n,"int64",BigInt64Array)}function ll(e){return xm(e.dims)}function GT(e){let t=e.reduce((r,n)=>r*n,1);return new U("float32",Float32Array.from({length:t},()=>el.gauss()),e)}function VT(e,t){if(e.dims.length!==2)throw Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw Error("The precision must be either 'binary' or 'ubinary'");let r=t==="binary",n=r?"int8":"uint8",s=r?Int8Array:Uint8Array,a=e.data,o=new s(a.length/8);for(let i=0;i<a.length;++i){let l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;if(o[c]|=l<<7-d,r&&d===0)o[c]-=128}return new U(n,o,[e.dims[0],e.dims[1]/8])}async function km(e){if(!e)throw Error("modelId is required for get_tokenizer_files");if((await ms(e,"tokenizer_config.json",{})).exists)return["tokenizer.json","tokenizer_config.json"];return[]}async function Tm(e,t){let r=await km(e);return await Promise.all(r.map((n)=>ar(e,n,!0,t)))}function cl(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var UT=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function jT(e,t,r,n){for(let s of Object.keys(e)){let a=t-e[s].length,o=r(s),i=Array(a).fill(o);e[s]=n==="right"?Bt(e[s],i):Bt(i,e[s])}}function WT(e,t){for(let r of Object.keys(e))e[r].length=t}function Zr(e,...t){for(let r of t){if(!Object.hasOwn(e,r))continue;let n=e[r];if(!n)continue;if(typeof n==="object")if(n.__type==="AddedToken")return n.content;else throw Error(`Unknown token: ${n}`);else return n}return null}function qT(e){let t=[];for(let r of e.get_added_tokens_decoder().values())if(r.special)t.push(r);return t}var le=class extends mt{return_token_type_ids=!1;padding_side="right";constructor(e,t){super();if(this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new tk(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Zr(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Zr(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Zr(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Zr(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Zr(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Zr(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)){let n=Object.create(null);for(let{name:s,template:a}of this.chat_template){if(typeof s!=="string"||typeof a!=="string")throw Error('Chat template must be a list of objects with "name" and "template" properties');n[s]=a}this.chat_template=n}this._compiled_template_cache=new Map;let r=qT(this._tokenizer);this.all_special_ids=r.map((n)=>n.id),this.all_special_tokens=r.map((n)=>n.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){let o=await Tm(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){if(typeof e==="string")return this._tokenizer.token_to_id(e);else return e.map((t)=>this._tokenizer.token_to_id(t))}_call(e,t={}){let{text_pair:r=null,add_special_tokens:n=!0,padding:s=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:i=null}=t,l=t.return_tensor??!0,c=Array.isArray(e),d;if(c){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(!Array.isArray(r))throw Error("text_pair must also be an array");else if(e.length!==r.length)throw Error("text and text_pair must have the same length");d=e.map((_,p)=>this._encode_plus(_,{text_pair:r[p],add_special_tokens:n,return_token_type_ids:a}))}else d=e.map((_)=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e===null||e===void 0)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:n,return_token_type_ids:a})]}if(i===null)i=this.model_max_length;else if(o===null){if(s===!0)ce.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;else if(s===!1)ce.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}if(s===!0)i=Math.min(qe(d.map((_)=>_.input_ids.length))[0],i??1/0);if(i=Math.min(i,this.model_max_length??1/0),s||o){for(let _=0;_<d.length;++_)if(d[_].input_ids.length===i)continue;else if(d[_].input_ids.length>i){if(o)WT(d[_],i)}else if(s)jT(d[_],i,(p)=>p==="input_ids"?this.pad_token_id:0,this.padding_side)}let f={};if(l){if(!(s&&o)){if(d.some((p)=>{for(let 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.")}let _=[d.length,d[0].input_ids.length];for(let p of Object.keys(d[0]))f[p]=new U("int64",BigInt64Array.from(d.flatMap((w)=>w[p]).map(BigInt)),_)}else{for(let _ of Object.keys(d[0]))f[_]=d.map((p)=>p[_]);if(!c)for(let _ of Object.keys(f))f[_]=f[_][0]}return f}_encode_text(e){if(e===null)return null;return this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{ids:s,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:s,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n}).ids}batch_decode(e,t={}){if(e instanceof U)e=e.tolist();return e.map((r)=>this.decode(r,t))}decode(e,t={}){if(e instanceof U)e=cl(e);if(!Array.isArray(e)||e.length===0||!EM(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"){let r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,t={}){let{tools:r=null,documents:n=null,chat_template:s=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:d=!0,return_dict:f=!0,tokenizer_kwargs:_={},...p}=t;if(s=this.get_chat_template({chat_template:s,tools:r}),typeof s!=="string")throw Error(`chat_template must be a string, but got ${typeof s}`);let w=this._compiled_template_cache.get(s);if(w===void 0)w=new Zk(s),this._compiled_template_cache.set(s,w);let v=Object.create(null);for(let b of UT){let k=Zr(this.config,b);if(k)v[b]=k}let y=w.render({messages:e,add_generation_prompt:a,tools:r,documents:n,...v,...p});if(o){let b=this._call(y,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:d,..._});return f?b:b.input_ids}return y}};function ul(e,t,r,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw 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 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 Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let{src_lang:s,tgt_lang:a}=n;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(s!==void 0){if(!e.language_codes.includes(s))throw Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);let o=e._tokenizer.post_processor?.config;if(o&&"single"in o){for(let i of o.single)if("SpecialToken"in i&&e.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=e.lang_to_token(s);break}}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var Em={};hs(Em,{AlbertTokenizer:()=>HT,AutoTokenizer:()=>Te,BartTokenizer:()=>QT,BertTokenizer:()=>XT,BlenderbotSmallTokenizer:()=>YT,BlenderbotTokenizer:()=>KT,BloomTokenizer:()=>JT,CLIPTokenizer:()=>eE,CamembertTokenizer:()=>ZT,CodeGenTokenizer:()=>rE,CodeLlamaTokenizer:()=>tE,CohereAsrTokenizer:()=>sE,CohereTokenizer:()=>nE,ConvBertTokenizer:()=>aE,DebertaTokenizer:()=>iE,DebertaV2Tokenizer:()=>oE,DistilBertTokenizer:()=>lE,ElectraTokenizer:()=>cE,EsmTokenizer:()=>uE,FalconTokenizer:()=>dE,GPT2Tokenizer:()=>_E,GPTNeoXTokenizer:()=>hE,GemmaTokenizer:()=>fE,HerbertTokenizer:()=>pE,LlamaTokenizer:()=>mE,M2M100Tokenizer:()=>gE,MBart50Tokenizer:()=>vE,MBartTokenizer:()=>Am,MPNetTokenizer:()=>ME,MarianTokenizer:()=>wE,MgpstrTokenizer:()=>yE,MobileBertTokenizer:()=>bE,NllbTokenizer:()=>xE,NougatTokenizer:()=>kE,PreTrainedTokenizer:()=>le,Qwen2Tokenizer:()=>TE,RoFormerTokenizer:()=>AE,RobertaTokenizer:()=>EE,SiglipTokenizer:()=>CE,SpeechT5Tokenizer:()=>SE,SqueezeBertTokenizer:()=>PE,T5Tokenizer:()=>FE,TokenizersBackend:()=>le,VitsTokenizer:()=>LE,Wav2Vec2CTCTokenizer:()=>OE,WhisperTokenizer:()=>RE,XLMRobertaTokenizer:()=>$E,XLMTokenizer:()=>GE});var HT=class extends le{return_token_type_ids=!0},QT=class extends le{},XT=class extends le{return_token_type_ids=!0},YT=class extends le{},KT=class extends le{},JT=class extends le{},ZT=class extends le{},eE=class extends le{},tE=class extends le{},rE=class extends le{},nE=class extends le{},sE=class extends le{},aE=class extends le{return_token_type_ids=!0},oE=class extends le{return_token_type_ids=!0},iE=class extends le{return_token_type_ids=!0},lE=class extends le{},cE=class extends le{return_token_type_ids=!0},uE=class extends le{},dE=class extends le{},fE=class extends le{},hE=class extends le{},_E=class extends le{},pE=class extends le{return_token_type_ids=!0},mE=class extends le{padding_side="left"},gE=class extends le{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 ul(this,e,t,r)}},wE=class extends le{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)),ce.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;let[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);else if(r.length===2){let[n,s]=r;if(!this.supported_language_codes.includes(n))ce.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`);return Bt([n],super._encode_text(s))}}},Am=class extends le{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 ul(this,e,t,r)}},vE=class extends Am{},yE=class extends le{},bE=class extends le{return_token_type_ids=!0},ME=class extends le{},xE=class extends le{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 ul(this,e,t,r)}},kE=class extends le{},TE=class extends le{},EE=class extends le{},AE=class extends le{return_token_type_ids=!0},CE=class extends le{},SE=class extends le{},PE=class extends le{return_token_type_ids=!0},FE=class extends le{},IE=class extends Wt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},LE=class extends le{constructor(e,t){super(e,t);this._tokenizer.decoder=new IE({type:"VitsDecoder"})}},OE=class extends le{},Cm=[["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"]],la=new Map(Cm),NE=new Map([...Cm.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 DE(e){e=e.toLowerCase();let t=NE.get(e);if(t===void 0){let r=e.match(/^<\|([a-z]{2})\|>$/);if(r)e=r[1];if(la.has(e))t=e;else{let s=e.length===2?la.keys():la.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var zE="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",fp=new RegExp(`^[${zE}]+$`,"gu"),BE=0.1,RE=class extends le{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}let l=[],c=i(),d=0,f=this.timestamp_begin,p=f+1500,w=[],v=[],y=!1,b=null,k=new Set(this.all_special_ids);for(let C of e){let N=C.tokens,M=o?C.token_timestamps:null,G=null,R=f;if("stride"in C){let[Q,H,B]=C.stride;if(d-=H,b=Q-B,H)R=H/n+f;if(B)for(let P=N.length-1;P>=0;--P){let Y=Number(N[P]);if(Y>=f){if(G!==null&&(Y-f)*n<b)break;G=Y}}}let q=[],X=[];for(let Q=0;Q<N.length;++Q){let H=Number(N[Q]);if(k.has(H)){let B=this.decode([H]),P=la.get(B.slice(2,-2));if(P!==void 0){if(a!==null&&P!==a&&!t){w.push(q);let Y=this.findLongestCommonSequence(w)[0],ue=this.decode(Y);c.text=ue,l.push(c),w=[],q=[],c=i()}a=c.language=P}}else if(H>=f&&H<=p){let B=(H-f)*n+d,P=as(B,2);if(G!==null&&H>=G)y=!0;else if(y||w.length>0&&H<R)y=!1;else if(c.timestamp[0]===null)c.timestamp[0]=P;else if(P===c.timestamp[0]);else{if(c.timestamp[1]=P,w.push(q),o)v.push(X);let[Y,ue]=this.findLongestCommonSequence(w,v),Z=this.decode(Y);if(c.text=Z,o){if(c.words=this.collateWordTimestamps(Y,ue,a),c.words.length>0&&c.timestamp[1]!==null){for(let se of c.words)if(se.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=se.timestamp[0])se.timestamp[1]=c.timestamp[1]}}l.push(c),w=[],q=[],v=[],X=[],c=i()}}else if(q.push(H),o){let B=as(M[Q]+d,2),P;if(Q+1<M.length){P=as(M[Q+1]+d,2);let Y=this.decode([H]);if(fp.test(Y))P=as(Math.min(B+n,P),2)}else P=null;X.push([B,P])}}if("stride"in C){let[Q,H,B]=C.stride;d+=Q-B}if(q.length>0){if(w.push(q),o)v.push(X)}else if(w.every((Q)=>Q.length===0))c=i(),w=[],q=[],v=[],X=[]}if(w.length>0){if(s&&t)throw 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.");let[C,N]=this.findLongestCommonSequence(w,v),M=this.decode(C);if(c.text=M,o)c.words=this.collateWordTimestamps(C,N,a);l.push(c)}let A=Object.create(null),E=l.map((C)=>C.text).join("");if(t||r){for(let C=0;C<l.length;++C){let N=l[C];if(!t)delete N.timestamp;if(!r)delete N.language}if(o){let C=[];for(let N of l)for(let M of N.words)C.push(M);A={chunks:C}}else A={chunks:l}}return[E,A]}findLongestCommonSequence(e,t=null){let r=e[0],n=r.length,s=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){let c=e[l],d=0,f=[n,n,0,0],_=c.length;for(let A=1;A<n+_;++A){let E=Math.max(0,n-A),C=Math.min(n,n+_-A),N=r.slice(E,C),M=Math.max(0,A-n),G=Math.min(_,A),R=c.slice(M,G);if(N.length!==R.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let q;if(a)q=N.filter((H,B)=>H===R[B]&&i[E+B][0]-BE<=t[l][M+B][0]).length;else q=N.filter((H,B)=>H===R[B]).length;let X=A/1e4,Q=q/A+X;if(q>1&&Q>d)d=Q,f=[E,C,M,G]}let[p,w,v,y]=f,b=Math.floor((w+p)/2),k=Math.floor((y+v)/2);if(a&&d===0&&n>0){let A=i[n-1][0],E=t[l].findIndex((C)=>C[0]>=A);k=E===-1?c.length:E}if(s.push(...r.slice(0,b)),r=c.slice(k),n=r.length,a)o.push(...i.slice(0,b)),i=t[l].slice(k)}if(s.push(...r),a)return o.push(...i),[s,o];else return[s,[]]}collateWordTimestamps(e,t,r){let[n,s,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<n.length;++i){let l=a[i];o.push({text:n[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,n=`"'.。,,!!??::”)]}、`){t=t??"english";let s,a,o;if(["chinese","japanese","thai","lao","myanmar"].includes(t))[s,a,o]=this.splitTokensOnUnicode(e);else[s,a,o]=this.splitTokensOnSpaces(e);return this.mergePunctuations(s,a,o,r,n)}decode(e,t){let r;if(t?.decode_with_timestamps){if(e instanceof U)e=cl(e);r=this.decodeWithTimestamps(e,t)}else r=super.decode(e,t);return r}decodeWithTimestamps(e,t){let r=t?.time_precision??0.02,n=this.all_special_ids.at(-1)+1,s=[[]];for(let a of e)if(a=Number(a),a>=n){let o=((a-n)*r).toFixed(2);s.push(`<|${o}|>`),s.push([])}else s[s.length-1].push(a);return s=s.map((a)=>typeof a==="string"?a:super.decode(a,t)),s.join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),r="�",n=[],s=[],a=[],o=[],i=[],l=0;for(let c=0;c<e.length;++c){let d=e[c];o.push(d),i.push(c);let f=this.decode(o,{decode_with_timestamps:!0});if(!f.includes("�")||t[l+f.indexOf("�")]==="�")n.push(f),s.push(o),a.push(i),o=[],i=[],l+=f.length}return[n,s,a]}splitTokensOnSpaces(e){let[t,r,n]=this.splitTokensOnUnicode(e),s=[],a=[],o=[];for(let i=0;i<t.length;++i){let l=t[i],c=r[i],d=n[i],f=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=fp.test(p);if(f||_||w||s.length===0)s.push(l),a.push(c),o.push(d);else{let v=s.length-1;s[v]+=l,a[v].push(...c),o[v].push(...d)}}return[s,a,o]}mergePunctuations(e,t,r,n,s){let a=structuredClone(e),o=structuredClone(t),i=structuredClone(r),l=a.length-2,c=a.length-1;while(l>=0){if(a[l].startsWith(" ")&&n.includes(a[l].trim()))a[c]=a[l]+a[c],o[c]=Bt(o[l],o[c]),i[c]=Bt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[];else c=l;--l}l=0,c=1;while(c<a.length){if(!a[l].endsWith(" ")&&s.includes(a[c]))a[l]+=a[c],o[l]=Bt(o[l],o[c]),i[l]=Bt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[];else l=c;++c}return[a.filter((d)=>d),o.filter((d)=>d.length>0),i.filter((d)=>d.length>0)]}},$E=class extends le{},GE=class extends le{return_token_type_ids=!0;constructor(e,t){super(e,t);ce.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Te=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){let[o,i]=await Tm(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",c=Em[l];if(!c)ce.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=le;return new c(o,i)}},Pa="https://github.com/huggingface/transformers.js/issues/new/choose",Sm="preprocessor_config.json",ds="preprocessor_config.json",Pm="processor_config.json",Fm="chat_template.jinja",Ee=class extends mt{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 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 Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(let r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){let[r,n,s]=await Promise.all([this.uses_processor_config?ar(e,Pm,!0,t):{},Promise.all(this.classes.filter((a)=>(a in this)).map(async(a)=>{let o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?nl(e,Fm,!0,t):null]);return new this(r,n,s)}},Ri={};hs(Ri,{ChatterboxProcessor:()=>w2,CohereAsrProcessor:()=>y2,EmbeddingGemma2Processor:()=>E2,EmbeddingGemma2VideoProcessor:()=>Um,Florence2Processor:()=>kA,Gemma3Processor:()=>TA,Gemma3nProcessor:()=>EA,Gemma4Processor:()=>Vm,Glm46VProcessor:()=>AA,GraniteSpeechProcessor:()=>CA,GroundingDinoProcessor:()=>PA,Idefics3Processor:()=>vp,JinaCLIPProcessor:()=>NA,Lfm2VlProcessor:()=>DA,Lfm3VlProcessor:()=>zA,LlavaProcessor:()=>BA,MgpstrProcessor:()=>RA,MoonshineProcessor:()=>$A,OwlViTProcessor:()=>GA,PaliGemmaProcessor:()=>UA,Phi3VProcessor:()=>WA,PixtralProcessor:()=>qA,Processor:()=>Ee,PyAnnoteProcessor:()=>HA,Qwen2VLProcessor:()=>wl,Qwen2_5_VLProcessor:()=>lg,Qwen3VLProcessor:()=>QA,Sam2Processor:()=>ug,Sam2VideoProcessor:()=>XA,SamProcessor:()=>cg,SmolVLMProcessor:()=>vp,SpeechT5Processor:()=>YA,UltravoxProcessor:()=>KA,VLChatProcessor:()=>OA,VoxtralProcessor:()=>tC,VoxtralRealtimeProcessor:()=>sC,Wav2Vec2Processor:()=>aC,Wav2Vec2ProcessorWithLM:()=>oC,WhisperProcessor:()=>iC});var ft=class extends mt{constructor(e){super();this.config=e}static async from_pretrained(e,t={}){let r=await ar(e,Sm,!0,t);return new this(r)}};function at(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw 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 \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var dl={};hs(dl,{ASTFeatureExtractor:()=>s2,ChatterboxFeatureExtractor:()=>a2,ClapFeatureExtractor:()=>o2,CohereAsrFeatureExtractor:()=>l2,DacFeatureExtractor:()=>zm,EncodecFeatureExtractor:()=>Nm,FeatureExtractor:()=>ft,Gemma3nAudioFeatureExtractor:()=>Bm,Gemma4AudioFeatureExtractor:()=>Rm,GraniteSpeechFeatureExtractor:()=>c2,MoonshineFeatureExtractor:()=>u2,ParakeetFeatureExtractor:()=>Dm,PyAnnoteFeatureExtractor:()=>$m,SeamlessM4TFeatureExtractor:()=>d2,SnacFeatureExtractor:()=>f2,SpeechT5FeatureExtractor:()=>h2,VoxtralRealtimeFeatureExtractor:()=>m2,Wav2Vec2FeatureExtractor:()=>_2,WeSpeakerFeatureExtractor:()=>p2,WhisperFeatureExtractor:()=>g2});var VE=()=>{},UE={fromWeb:VE},jE=()=>{},WE=jE;async function Im(e,t){if(pe.IS_BROWSER_ENV){if(pe.IS_WEBWORKER_ENV)throw Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(r)}else if(pe.IS_FS_AVAILABLE){let r=t.stream(),n=UE.fromWeb(r),s=kt.createWriteStream(e);await WE(n,s)}else throw Error("Unable to save because filesystem is disabled in this environment.")}async function qE(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.");let r=await(await cs(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});if(typeof t>"u")ce.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);let s=await n.decodeAudioData(r),a;if(s.numberOfChannels===2){let o=Math.sqrt(2),i=s.getChannelData(0),l=s.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<s.length;++c)a[c]=o*(i[c]+l[c])/2}else a=s.getChannelData(0);return a}async function HE(e,t){return await qE(e,t)}function Lm(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);let r=1-t,n=2*Math.PI/(e-1),s=new Float64Array(e);for(let a=0;a<e;++a)s[a]=t-r*Math.cos(a*n);return s}function hp(e){return Lm(e,0.5)}function QE(e){return Lm(e,0.54)}var XE={htk:(e)=>2595*Math.log10(1+e/700),kaldi:(e)=>1127*Math.log(1+e/700),slaney:(e,t=1000,r=15,n=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*n:3*e/200};function ki(e,t="htk"){let r=XE[t];if(!r)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e==="number"?r(e):e.map((n)=>r(n))}var YE={htk:(e)=>700*(10**(e/2595)-1),kaldi:(e)=>700*(Math.exp(e/1127)-1),slaney:(e,t=1000,r=15,n=Math.log(6.4)/27)=>e>=r?t*Math.exp(n*(e-r)):200*e/3};function KE(e,t="htk"){let r=YE[t];if(!r)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e==="number"?r(e):e.map((n)=>r(n))}function JE(e,t){let r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),n=Array.from({length:e.length},()=>Array(t.length));for(let o=0;o<e.length;++o){let i=n[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}let s=t.length-2,a=Array.from({length:s},()=>Array(e.length));for(let o=0;o<e.length;++o){let i=n[o];for(let l=0;l<s;++l){let 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 _p(e,t,r){let n=(t-e)/(r-1);return Float64Array.from({length:r},(s,a)=>e+n*a)}function sr(e,t,r,n,s,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw Error('norm must be one of null or "slaney"');if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(r>n)throw Error(`Require min_frequency: ${r} <= max_frequency: ${n}`);let l=ki(r,o),c=ki(n,o),d=_p(l,c,t+2),f=KE(d,o),_;if(i){let w=s/((e-1)*2);_=ki(Float64Array.from({length:e},(v,y)=>y*w),o),f=d}else _=_p(0,Math.floor(s/2),e);let p=JE(_,f);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){let v=p[w],y=2/(f[w+2]-f[w]);for(let b=0;b<e;++b)v[b]*=y}return p}function ZE(e,t,r){let n=new e.constructor(e.length+t+r),s=e.length-1;for(let a=0;a<e.length;++a)n[t+a]=e[a];for(let a=1;a<=t;++a)n[t-a]=e[fa(a,s)];for(let a=1;a<=r;++a)n[s+t+a]=e[fa(s-a,s)];return n}function Om(e,t,r,n,s){if(r<=0)throw Error("reference must be greater than zero");if(n<=0)throw Error("min_value must be greater than zero");r=Math.max(n,r);let a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(n,e[o])-a);if(s!==null){if(s<=0)throw Error("db_range must be greater than zero");let o=qe(e)[0]-s;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function e2(e,t=1,r=0.00001,n=null){return Om(e,20,t,r,n)}function t2(e,t=1,r=0.0000000001,n=null){return Om(e,10,t,r,n)}async function or(e,t,r,n,{fft_length:s=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:f=null,mel_floor:_=0.0000000001,log_mel:p=null,max_log_mel:w=null,reference:v=1,min_value:y=0.0000000001,db_range:b=null,remove_dc_offset:k=null,min_num_frames:A=null,max_num_frames:E=null,do_pad:C=!0,transpose:N=!1,mel_offset:M=0,mel_floor_mode:G="clamp"}={}){let R=t.length;if(s===null)s=r;if(r>s)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(R!==r)throw Error(`Length of the window (${R}) must equal frame_length (${r})`);if(n<=0)throw Error("hop_length must be greater than zero");if(a===null&&f!==null)throw 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 Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let O=Math.floor(r/2);switch(i){case"reflect":{e=ZE(e,O,O);break}case"constant":{let V=new e.constructor(e.length+2*O);V.set(e,O),e=V;break}case"semicausal":{let V=new e.constructor(e.length+O);V.set(e,O),e=V;break}default:throw Error(`pad_mode="${i}" not implemented yet.`)}}let q=Math.floor(1+Math.floor((e.length-r)/n));if(A!==null&&q<A)q=A;let X=l?Math.floor(s/2)+1:s,Q=q,H=q;if(E!==null)if(E>q){if(C)H=E}else H=Q=E;let B=new yT(s),P=new Float64Array(s),Y=new Float64Array(B.outputBufferSize),ue=new Float32Array(X*H);for(let O=0;O<Q;++O){let V=O*n,de=Math.min(e.length-V,r);if(de!==r)P.fill(0,0,r);for(let te=0;te<de;++te)P[te]=e[V+te];if(k){let te=0;for(let Fe=0;Fe<de;++Fe)te+=P[Fe];let We=te/de;for(let Fe=0;Fe<de;++Fe)P[Fe]-=We}if(c!==null){for(let te=de-1;te>=1;--te)P[te]-=c*P[te-1];P[0]*=1-c}for(let te=0;te<t.length;++te)P[te]*=t[te];B.realTransform(Y,P);for(let te=0;te<X;++te){let We=te<<1;ue[te*H+O]=Y[We]**2+Y[We+1]**2}}if(a!==null&&a!==2){let O=a/2;for(let V=0;V<ue.length;++V)ue[V]**=O}let Z=f.length,se=await BT(new U("float32",f.flat(),[Z,X]),new U("float32",ue,[X,H]));if(N)se=se.transpose(1,0);let L=se.data;if(G==="add")for(let O=0;O<L.length;++O)L[O]=M+L[O]+_;else for(let O=0;O<L.length;++O)L[O]=M+Math.max(_,L[O]);if(a!==null&&p!==null){let O=Math.min(L.length,Q*Z);switch(p){case"log":for(let V=0;V<O;++V)L[V]=Math.log(L[V]);break;case"log10":for(let V=0;V<O;++V)L[V]=Math.log10(L[V]);break;case"log10_max_norm":{for(let te=0;te<O;++te)L[te]=Math.log10(L[te]);let de=(w??qe(L)[0])-8;for(let te=0;te<O;++te)L[te]=(Math.max(L[te],de)+4)/4;break}case"dB":if(a===1)e2(L,v,y,b);else if(a===2)t2(L,v,y,b);else throw Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return se}function gr(e,t,{periodic:r=!0,frame_length:n=null,center:s=!0}={}){let a=r?e+1:e,o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=hp(a);break;case"hamming":o=QE(a);break;case"povey":o=hp(a).map((c)=>Math.pow(c,0.85));break;default:throw Error(`Unknown window type ${t}.`)}if(r)o=o.subarray(0,e);if(n===null||e===n)return o;if(e>n)throw Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);let i=new Float64Array(n),l=s?Math.floor((n-e)/2):0;return i.set(o,l),i}function r2(e,t){let r=e.reduce((a,o)=>a+o.length,0),n=new ArrayBuffer(44),s=new DataView(n);return ta(s,0,"RIFF"),s.setUint32(4,36+r*4,!0),ta(s,8,"WAVE"),ta(s,12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,1,!0),s.setUint32(24,t,!0),s.setUint32(28,t*4,!0),s.setUint16(32,4,!0),s.setUint16(34,32,!0),ta(s,36,"data"),s.setUint32(40,r*4,!0),new Blob([n,...e.map((a)=>a.buffer instanceof ArrayBuffer?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a.slice())],{type:"audio/wav"})}function ta(e,t,r){for(let n=0;n<r.length;++n)e.setUint8(t+n,r.charCodeAt(n))}var n2=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];let e=this.audio.reduce((n,s)=>n+s.length,0),t=new Float32Array(e),r=0;for(let n of this.audio)t.set(n,r),r+=n.length;return t}else return this.audio}toBlob(){let e=this.audio;if(e instanceof Float32Array)e=[e];return r2(e,this.sampling_rate)}async save(e){return Im(e,this.toBlob())}},s2=class extends ft{constructor(e){super(e);let t=this.config.sampling_rate,r=sr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=gr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return or(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){at(e,"ASTFeatureExtractor");let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,n=t.data;for(let s=0;s<n.length;++s)n[s]=(n[s]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},Nm=class extends ft{async _call(e){if(at(e,"EncodecFeatureExtractor"),e instanceof Float64Array)e=new Float32Array(e);let t=this.config.feature_size;if(e.length%t!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let r=[1,t,e.length/t];return{input_values:new U("float32",e,r)}}},a2=class extends ft{async _call(e){if(at(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array)e=new Float32Array(e);let t=[1,e.length];return{input_values:new U("float32",e,t)}}},o2=class extends ft{constructor(e){super(e);this.mel_filters=sr(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=sr(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=gr(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,n){let s,a=!1,o=e.length-t;if(o>0)if(r==="rand_trunc"){a=!0;let i=Math.floor(el.random()*(o+1));e=e.subarray(i,i+t),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${r}" not implemented`);else{if(o<0){let i=new Float64Array(t);if(i.set(e),n==="repeat")for(let l=e.length;l<t;l+=e.length)i.set(e.subarray(0,Math.min(e.length,t-l)),l);else if(n==="repeatpad")for(let l=e.length;l<-o;l+=e.length)i.set(e,l);e=i}if(r==="fusion")throw Error(`Truncation strategy "${r}" not implemented`);s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return s.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return or(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return at(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},i2=0.00001,Dm=class extends ft{constructor(e){super(e);this.config.mel_filters??=sr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let t=gr(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await or(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:0.00000005960464477539063})}async _call(e){at(e,"ParakeetFeatureExtractor");let t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,r*t.dims[1]);let[s,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d<r;++d){let f=d*a;for(let _=0;_<a;++_){let p=n[f+_];o[_]+=p,i[_]+=p*p}}let l=r>1?r-1:1;for(let d=0;d<a;++d){let f=o[d]/r,_=(i[d]-r*f*f)/l,w=1/(Math.sqrt(_)+i2);for(let v=0;v<r;++v){let y=v*a+d;n[y]=(n[y]-f)*w}}let c=new BigInt64Array(s);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new U("int64",c,[1,s])}}},l2=class extends Dm{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let r=new Sa(e.length);for(let n=0;n<e.length;++n)e[n]+=t*r.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,n=this.config.min_energy_window_samples??1600,s=this.config.sampling_rate,a=Math.max(1,Math.round(t*s)),o=Math.max(1,Math.round(r*s));if(e.length<=a)return[e];let i=[],l=0,c=e.length;while(l<c){if(l+a>=c){i.push(e.slice(l,c));break}let d=Math.max(l,l+a-o),f=Math.min(l+a,c),_;if(f<=d)_=l+a;else _=this._find_split_point_energy(e,d,f,n);_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_}return i}_find_split_point_energy(e,t,r,n){let s=r-t;if(s<=n)return Math.floor((t+r)/2);let a=1/0,o=t,i=s-n;for(let l=0;l<=i;l+=n){let c=0;for(let d=0;d<n;++d){let f=e[t+l+d];c+=f*f}if(c=Math.sqrt(c/n),c<a)a=c,o=t+l}return o}async _call(e){at(e,"CohereAsrFeatureExtractor");let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},zm=class extends Nm{},Bm=class extends ft{constructor(e){super(e);let{fft_length:t,feature_size:r,min_frequency:n,max_frequency:s,sampling_rate:a,frame_length:o}=this.config,i=sr(Math.floor(1+t/2),r,n,s,a,null,"htk",!1);this.mel_filters=i,this.window=gr(o,"hann")}async _extract_fbank_features(e,t){return or(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=480000,truncation:r=!0,padding:n=!0,pad_to_multiple_of:s=128}={}){if(at(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t)e=e.slice(0,t);if(n&&e.length%s!==0){let i=s-e.length%s,l=new Float64Array(e.length+i);if(l.set(e),this.config.padding_value!==0)l.fill(this.config.padding_value,e.length);e=l}let a=await this._extract_fbank_features(e,this.config.max_length),o=dt([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},Rm=class extends Bm{async _extract_fbank_features(e,t){let{frame_length:r,hop_length:n,fft_length:s}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/n)+1;return or(e,this.window,r,n,{fft_length:s,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){at(e,"Gemma4AudioFeatureExtractor");let r=e.length,n=await super._call(e,t),{input_features:s}=n,[,a,o]=s.dims,{frame_length:i,hop_length:l}=this.config,c=Math.floor(i/2),d=i+1,f=new Uint8Array(r+c+(t.pad_to_multiple_of??128));f.fill(1,c,c+r);let _=new Uint8Array(a);for(let w=0;w<a;++w)_[w]=f[w*l+d-1]?1:0;let p=s.data;for(let w=0;w<a;++w)if(!_[w])p.fill(0,w*o,(w+1)*o);return n.input_features_mask=new U("bool",_,[1,a]),n}},c2=class extends ft{constructor(e){super(e);let{n_fft:t,win_length:r,n_mels:n,sample_rate:s}=e.melspec_kwargs;this.mel_filters=sr(Math.floor(1+t/2),n,0,s/2,s,null,"htk");let a=gr(r,"hann");this.window=new Float64Array(t);let o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){at(e,"GraniteSpeechFeatureExtractor");let{n_fft:t,hop_length:r,n_mels:n}=this.config.melspec_kwargs,s=Math.floor(e.length/r)+1,a=s-s%2;return{input_features:(await or(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}},u2=class extends ft{async _call(e){if(at(e,"MoonshineFeatureExtractor"),e instanceof Float64Array)e=new Float32Array(e);let t=[1,e.length];return{input_values:new U("float32",e,t)}}},$m=class extends ft{async _call(e){if(at(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array)e=new Float32Array(e);let t=[1,1,e.length];return{input_values:new U("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let r=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(let s of e.tolist()){let a=[],o=-1;for(let i=0;i<s.length;++i){let l=st(s[i]),[c,d]=qe(l),[f,_]=[i,i+1];if(d!==o)o=d,a.push({id:d,start:f,end:_,score:c});else a.at(-1).end=_,a.at(-1).score+=c}n.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return n}},d2=class extends ft{constructor(e){super(e);let t=this.config.sampling_rate,r=sr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=gr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map((r)=>r*32768),or(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:s=!0}={}){at(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[p,w]=a.dims,v=a.data;for(let y=0;y<w;++y){let b=0;for(let C=0;C<p;++C)b+=v[C*w+y];let k=b/p,A=0;for(let C=0;C<p;++C)A+=(v[C*w+y]-k)**2;A/=p-1;let E=Math.sqrt(A+0.0000001);for(let C=0;C<p;++C){let N=C*w+y;v[N]=(v[N]-k)/E}}}let o;if(t){let[p,w]=a.dims,v=a.data,y=p%r;if(y>0){let b=new Float32Array(w*(p+y));b.set(v),b.fill(this.config.padding_value,v.length);let k=p+y;if(a=new U(a.type,b,[k,w]),s)o=new U("int64",new BigInt64Array(k),[1,k]),o.data.fill(1n,0,p)}}let[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);let f=a.view(1,Math.floor(i/c),l*c),_={input_features:f};if(s){let p=f.dims[1],w=new BigInt64Array(p);if(o){let v=o.data;for(let y=1,b=0;y<i;y+=c,++b)w[b]=v[y]}else w.fill(1n);_.attention_mask=new U("int64",w,[1,p])}return _}},f2=class extends zm{},h2=class extends ft{},_2=class extends ft{_zero_mean_unit_var_norm(e){let r=e.reduce((s,a)=>s+a,0)/e.length,n=e.reduce((s,a)=>s+(a-r)**2,0)/e.length;return e.map((s)=>(s-r)/Math.sqrt(n+0.0000001))}async _call(e){if(at(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array)e=new Float32Array(e);let t=e;if(this.config.do_normalize)t=this._zero_mean_unit_var_norm(t);let r=[1,t.length];return{input_values:new U("float32",t,r),attention_mask:new U("int64",new BigInt64Array(t.length).fill(1n),r)}}},p2=class extends ft{constructor(e){super(e);let t=this.config.sampling_rate,r=sr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=gr(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map((t)=>t*32768),or(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){at(e,"WeSpeakerFeatureExtractor");let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=t.mean(1).data,n=t.data,[s,a,o]=t.dims;for(let i=0;i<s;++i){let l=i*a*o,c=i*o;for(let d=0;d<a;++d){let f=l+d*o;for(let _=0;_<o;++_)n[f+_]-=r[c+_]}}}return{input_features:t}}},m2=class extends ft{constructor(e){super(e);this.config.mel_filters??=sr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8000,this.config.sampling_rate,"slaney","slaney"),this.window=gr(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:r,hop_length:n,mel_filters:s,global_log_mel_max:a}=this.config,o=t?Math.floor(e.length/n):Math.floor((e.length-r)/n);return await or(e,this.window,r,n,{power:2,mel_filters:s,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return at(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}};var g2=class extends ft{constructor(e){super(e);this.config.mel_filters??=sr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8000,this.config.sampling_rate,"slaney","slaney"),this.window=gr(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await or(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){at(e,"WhisperFeatureExtractor");let r,n=t??this.config.n_samples;if(e.length>n){if(e.length>this.config.n_samples)ce.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`.");r=e.slice(0,n)}else r=new Float32Array(n),r.set(e);return{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Ft=class{static async from_pretrained(e,t={}){let r=await ar(e,Sm,!0,t),n=r.feature_extractor_type,s=dl[n];if(!s)throw Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Pa}.`);return new s(r)}},w2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e,t=null){let r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},v2=new Set(["ja","zh"]),y2=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let 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"){let r=e.filter((a)=>a&&a.trim());if(r.length===0)return"";let n=v2.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map((a)=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}},$i={},en,Gm,Sr;if(pe.IS_WEB_ENV)en=(e,t)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Sr=self.createImageBitmap,Gm=self.ImageData;else if($i)Sr=async(e)=>{let r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new Vt(new Uint8ClampedArray(n),s.width,s.height,s.channels);if(r!==void 0&&r!==s.channels)a.convert(r);return a};else throw Error("Unable to load image processing library.");var b2={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},M2=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Vt=class e{constructor(t,r,n,s){this.data=t,this.width=r,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;else if(typeof t==="string"||t instanceof URL)return await this.fromURL(t);else if(t instanceof Blob)return await this.fromBlob(t);else if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);else throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!pe.IS_WEB_ENV)throw Error("fromCanvas() is only supported in browser environments.");let n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(t){let r=await cs(t);if(r.status!==200)throw Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);let n=await r.blob();return this.fromBlob(n)}static async fromBlob(t){if(pe.IS_WEB_ENV){let r=await Sr(t),n=en(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=$i(await t.arrayBuffer());return await Sr(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.permute(1,2,0);else if(r==="HWC");else throw Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r<this.data.length;r+=this.channels){let s=this.data[r],a=this.data[r+1],o=this.data[r+2];t[n++]=Math.round(0.2989*s+0.587*a+0.114*o)}break;default:throw 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;let t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r];break;case 4:for(let r=0,n=0;r<this.data.length;r+=4)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2];break;default:throw 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;let t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=255;break;case 3:for(let r=0,n=0;r<this.data.length;r+=3)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2],t[n++]=255;break;default:throw 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 Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${t.channels}`);let r=this.data,n=t.data,s=this.width*this.height;if(this.channels===3){let a=new Uint8ClampedArray(s*4);for(let o=0,i=0,l=0;o<s;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=n[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<s;++a)r[4*a+3]=n[a];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:n=2}={}){if(this.width===t&&this.height===r)return this;let s=b2[n]??n,a=S_(t),o=S_(r);if(a&&o)return this;else if(a)t=r/this.height*this.width;else if(o)r=t/this.width*this.height;if(pe.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=en(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new e(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(s){case"box":case"hamming":if(s==="box"||s==="hamming")ce.warn(`Resampling method ${s} is not yet supported. Using bilinear instead.`),s="bilinear";case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:s});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw Error(`Resampling method ${s} is not supported.`)}return await Sr(i)}}async pad([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.max(n,0),s=Math.max(s,0),t===0&&r===0&&n===0&&s===0)return this;if(pe.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+n+s,c=en(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new e(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{let a=this.toSharp().extend({left:t,right:r,top:n,bottom:s});return await Sr(a)}}async crop([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.min(n,this.width-1),s=Math.min(s,this.height-1),t===0&&r===0&&n===this.width-1&&s===this.height-1)return this;let a=n-t+1,o=s-r+1;if(pe.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=en(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new e(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{let i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await Sr(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;let n=(this.width-t)/2,s=(this.height-r)/2;if(pe.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=en(t,r).getContext("2d"),l=0,c=0,d=0,f=0;if(n>=0)l=n;else d=-n;if(s>=0)c=s;else f=-s;return i.drawImage(o,l,c,t,r,d,f,t,r),new e(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(n>=0&&s>=0)a=a.extract({left:Math.floor(n),top:Math.floor(s),width:t,height:r});else if(n<=0&&s<=0){let o=Math.floor(-s),i=Math.floor(-n);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;if(s<0)o[0]=Math.floor(-s),o[1]=r-this.height-o[0];else i=Math.floor(s);let l=[0,0],c=0;if(n<0)l[0]=Math.floor(-n),l[1]=t-this.width-l[0];else c=Math.floor(n);a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await Sr(a)}}async toBlob(t="image/png",r=1){if(!pe.IS_WEB_ENV)throw Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new U("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t==="HWC");else if(t==="CHW")r=r.permute(2,0,1);else throw Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!pe.IS_WEB_ENV)throw Error("toCanvas() is only supported in browser environments.");let t=this.clone().rgba(),r=en(t.width,t.height),n=new Gm(t.data,t.width,t.height);return r.getContext("2d").putImageData(n,0,0),r}split(){let{data:t,width:r,height:n,channels:s}=this,a=t.constructor,o=t.length/s,i=Array.from({length:s},()=>new a(o));for(let l=0;l<o;++l){let c=s*l;for(let d=0;d<s;++d)i[d][l]=t[c+d]}return i.map((l)=>new e(l,r,n,1))}_update(t,r,n,s=null){if(this.data=t,this.width=r,this.height=n,s!==null)this.channels=s;return this}clone(){return new e(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 Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(pe.IS_WEB_ENV){if(pe.IS_WEBWORKER_ENV)throw Error("Unable to save an image from a Web Worker.");let r=t.split(".").pop().toLowerCase(),n=M2.get(r)??"image/png",s=await this.toBlob(n);return Im(t,s)}else if(pe.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(pe.IS_WEB_ENV)throw Error("toSharp() is only supported in server-side environments.");return $i(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},Qz=Vt.read.bind(Vt);function x2(e,t,r,n,s){let a=n*r**2,o=Math.sqrt(a/(e*t)),i=s*r,l=Math.floor(o*e/i)*i,c=Math.floor(o*t/i)*i;if(l===0&&c===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let d=Math.floor(n/s**2)*i;if(l===0)l=i,c=Math.min(Math.floor(t/e)*i,d);else if(c===0)c=i,l=Math.min(Math.floor(e/t)*i,d);return[l,c]}function k2(e,t,r,n,s,a,o){let i=Math.floor(t/s),l=Math.floor(r/s),c=i*l,d=s*s*n,f=new Float32Array(a*d),_=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)for(let b=0;b<s;++b){let k=(v*s+b)*r*n+y*s*n;for(let A=0;A<s;++A){let E=k+A*n;for(let C=0;C<n;++C)f[_++]=e[E+C]}}let p=new BigInt64Array(a*2).fill(-1n),w=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)p[w++]=BigInt(y),p[w++]=BigInt(v);return{patches:new U("float32",f,[a,d]),positions:new U("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var fl=class extends mt{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??0.00392156862745098,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){if(!Array.isArray(e))e=[e];let{patch_size:t,pooling_kernel_size:r}=this,n=this.max_soft_tokens*r**2,s=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb)i=i.rgb();if(this.do_resize){let[_,p]=x2(i.height,i.width,t,n,r);if(_!==i.height||p!==i.width)i=await i.resize(p,_,{resample:this.resample})}let l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;let{patches:c,positions:d,num_soft_tokens:f}=k2(l,i.height,i.width,i.channels,t,n,r);s.push(c),a.push(d),o.push(f)}return{pixel_values:_r(s,0),image_position_ids:_r(a,0),num_soft_tokens_per_image:o}}},Vm=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;let{audio_token:n,boa_token:s,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=n,this.boa_token=s,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){let[r,n,s]=await Promise.all([ar(e,Pm,!0,t),Te.from_pretrained(e,t),nl(e,Fm,!1,t)]),a={tokenizer:n};if(r.image_processor)a.image_processor=new fl(r.image_processor);if(r.feature_extractor)a.feature_extractor=new Rm(r.feature_extractor);return new this(r,a,s)}_compute_audio_num_tokens(e,t){let r=Math.round(t*20/1000),n=Math.round(t*10/1000),s=Math.floor(r/2),a=Math.floor((e+s-r-1)/n)+1;if(a<=0)return 0;for(let o=0;o<2;++o)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,r=null,n={}){if(typeof e==="string")e=[e];let s;if(t){s=await this.image_processor(t,n);let o=s.num_soft_tokens_per_image,i=0;e=e.map((l)=>l.replaceAll(this.image_token,()=>`
|
|
21
|
+
|
|
22
|
+
${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
|
|
23
|
+
|
|
24
|
+
`))}let a;if(r){let o=Array.isArray(r)?r:[r];a=await this.feature_extractor(o[0],n);let i=this.feature_extractor.config.sampling_rate??16000,l=0;e=e.map((c)=>c.replaceAll(this.audio_token,()=>`
|
|
25
|
+
|
|
26
|
+
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
|
|
27
|
+
|
|
28
|
+
`))}return{...this.tokenizer(e,n),...s,...a}}},Um=class extends mt{constructor(e){super();this.config=e,this.frame_processor=new fl(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??"uniform"}sample_frames(e){let t=e.length,{max_frames:r}=this;if(t<=r)return e;if(this.overflow_strategy==="truncate")return e.slice(0,r);let n=r>1?(t-1)/(r-1):0;return Array.from({length:r},(s,a)=>e[a>0&&a===r-1?t-1:Math.floor(a*n)])}async _call(e){if(!Array.isArray(e))e=[e];let t=e.map((o)=>this.sample_frames(o.frames.map((i)=>i.image))),{pixel_values:r,image_position_ids:n,num_soft_tokens_per_image:s}=await this.frame_processor(t.flat()),a=0;return{pixel_values_videos:r,video_position_ids:n,num_frames_per_video:t.map((o)=>o.length),num_soft_tokens_per_video:t.map((o)=>s[(a+=o.length)-1])}}};function Ti(e,t){if(!Array.isArray(e))return[[e]];if(e.every((r)=>Array.isArray(r)))return e;return t?[e]:e.map((r)=>[r])}function T2(e,t,r){let n=0;if(e=e.map((s)=>s.replaceAll(t,()=>r[n++]??"")),n!==r.length)throw Error(`Found ${n} ${t} tokens in the text, but ${r.length} inputs were passed.`);return e}var E2=class extends Vm{constructor(e,t,r){super(e,t,r);this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new Um(e.video_processor)}async _call(e,t=null,r=null,n=null,s={}){let a=[[this.image_token,t&&Ti(t,!0)],[this.video_token,n&&Ti(n,!1)],[this.audio_token,r&&Ti(r,!1)]];if(e==null){let E=a.filter(([,N])=>N),C=E[0]?.[1].length;if(E.some(([,N])=>N.length!==C))throw Error("Received a different number of samples per modality.");e=Array.from({length:C},(N,M)=>E.flatMap(([G,R])=>Array(R[M].length).fill(G)).join(" "))}else if(typeof e==="string")e=[e];let[o,i,l]=a.map(([,E])=>E?.flat()),c=o&&await this.image_processor(o),d=i&&await this.video_processor(i),f=l&&await this._process_audio(l),{image_token:_,video_token:p,audio_token:w,boi_token:v,eoi_token:y,boa_token:b,eoa_token:k}=this,A={[_]:c?.num_soft_tokens_per_image.map((E)=>v+_.repeat(E)+y),[p]:d?.num_soft_tokens_per_video.map((E,C)=>(v+p.repeat(E)+y).repeat(d.num_frames_per_video[C])),[w]:f?.num_soft_tokens_per_audio.map((E)=>b+w.repeat(E)+k)};for(let[E,C]of Object.entries(A))e=T2(e,E,C??[]);return{...this.tokenizer(e,{padding:!0,...s}),...c,...d,...f}}async _process_audio(e){let t=[];for(let o of e)t.push(await this.feature_extractor(o));let r=Math.max(...t.map((o)=>o.input_features.dims[1])),n=t[0].input_features.dims[2],s=new Float32Array(e.length*r*n),a=new Uint8Array(e.length*r);return t.forEach((o,i)=>{s.set(o.input_features.data,i*r*n),a.set(o.input_features_mask.data,i*r)}),{input_features:new U("float32",s,[e.length,r,n]),input_features_mask:new U("bool",a,[e.length,r]),num_soft_tokens_per_audio:t.map(({input_features_mask:{data:o}})=>{let i=0;for(let l=0;l<o.length;l+=4)i+=Number(o[l]);return i})}}};function pp(e,t,r=0,n=null){let s=e/t,a=MT(s)*t;if(n!==null&&a>n)a=Math.floor(s)*t;if(a<r)a=Math.ceil(s)*t;return a}function mp([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function jm([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function Fa(e,t=0.5,r=null,n=!1){let{logits:s,pred_boxes:a}=e,[o,i,l]=s.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let d=0;d<o;++d){let f=r!==null?r[d]:null,_={boxes:[],classes:[],scores:[]},p=s[d],w=a[d];for(let v=0;v<i;++v){let y=p[v],b=[],k;if(n){k=y.sigmoid().data;for(let A=0;A<k.length;++A)if(k[A]>t)b.push(A)}else{let A=qe(y.data)[1];if(A===l-1)continue;if(k=st(y.data),k[A]<t)continue;b.push(A)}for(let A of b){let E=w[v].data;if(E=jm(E),f!==null)E=E.map((C,N)=>C*f[(N+1)%2]);_.boxes.push(E),_.classes.push(A),_.scores.push(k[A])}}c.push(_)}return c}function Wm(e,t=null){let r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let s=[];for(let a=0;a<n;++a){let o=t!==null?t[a]:null,i=r[a];if(o!==null)i=bm(i,o,"bilinear",!1);let[l,c]=o??i.dims.slice(-2),d=new U("int32",new Int32Array(l*c),[l,c]),f=i[0].data,_=d.data;for(let v=1;v<i.dims[0];++v){let y=i[v].data;for(let b=0;b<y.length;++b)if(y[b]>f[b])f[b]=y[b],_[b]=v}let p=Array(i.dims[0]);for(let v=0;v<_.length;++v){let y=_[v];p[y]=y}let w=p.filter((v)=>v!==void 0);s.push({segmentation:d,labels:w})}return s}function A2(e,t,r,n){let s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){let l=e[i],c=t[i],d=qe(l.data)[1];if(d===n)continue;let _=st(l.data)[d];if(_>r)s.push(c),a.push(_),o.push(d)}return[s,a,o]}function C2(e,t,r,n=0.5,s=0.8){let a=[],o=0,i=0,l=t[r].data;for(let d=0;d<e.length;++d){if(e[d]===r)a.push(d),++o;if(l[d]>=n)++i}let c=o>0&&i>0;if(c)c=o/i>s;return[c,a]}function S2(e,t,r,n,s,a=null,o=null){let[i,l]=o??e[0].dims,c=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=bm(e[v],o,"bilinear",!1);let f=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let y=t[v],b=e[v].data;for(let k=0;k<b.length;++k)if(b[k]*=y,b[k]>_[k])f[k]=v,_[k]=b[k]}let p=0,w=c.data;for(let v=0;v<r.length;++v){let y=r[v],[b,k]=C2(f,e,v,n,s);if(!b)continue;++p;for(let A of k)w[A]=p;d.push({id:p,label_id:y,score:t[v]})}return[c,d]}function hl(e,t,r=28,n=3136,s=1003520,a=1){if(e<r||t<r){let 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 Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>s){let l=Math.sqrt(a*e*t/s);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r)}else if(a*o*i<n){let l=Math.sqrt(n/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function qm(e,t=0.5,r=0.5,n=0.8,s=null,a=null){if(s===null)ce.warn("`label_ids_to_fuse` unset. No instance will be fused."),s=new Set;let o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid(),[c,d,f]=o.dims;if(f-=1,a!==null&&a.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let p=0;p<c;++p){let w=a!==null?a[p]:null,v=o[p],y=l[p],[b,k,A]=A2(v,y,t,f);if(A.length===0){let[N,M]=w??y.dims.slice(-2),G=new U("int32",new Int32Array(N*M).fill(-1),[N,M]);_.push({segmentation:G,segments_info:[]});continue}let[E,C]=S2(b,k,A,r,n,s,w);_.push({segmentation:E,segments_info:C})}return _}function Hm(e,t=0.5,r=null){throw Error("`post_process_instance_segmentation` is not yet implemented.")}var fe=class extends mt{constructor(e){super();if(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??0.00392156862745098,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){let{height:n,width:s}=e,{height:a,width:o}=t,i=Math.min(n,a),l=Math.min(s,o);if(i===n&&l===s)return e;if(n>s)l=Math.floor(s*i/n);else if(s>n)i=Math.floor(n*l/s);return await e.resize(l,i,{resample:r})}async crop_margin(e,t=200){let r=e.clone().grayscale(),n=Di(r.data)[0],a=qe(r.data)[0]-n;if(a===0)return e;let o=t/255,{width:i,height:l}=r,c=0,d=0,f=r.data;for(let _=0;_<r.height;++_){let p=_*r.width;for(let w=0;w<r.width;++w)if((f[p+w]-n)/a<o)i=Math.min(i,w),l=Math.min(l,_),c=Math.max(c,w),d=Math.max(d,_)}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){let[o,i,l]=t,c,d;if(typeof r==="number")c=r,d=r;else if(r==="square")c=d=Math.max(o,i);else c=r.width,d=r.height;if(c!==i||d!==o){let f=new Float32Array(c*d*l);if(Array.isArray(a))for(let w=0;w<f.length;++w)f[w]=a[w%l];else if(a!==0)f.fill(a);let[_,p]=s?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){let v=(w+p)*c,y=w*i;for(let b=0;b<i;++b){let k=(v+b+_)*l,A=(y+b)*l;for(let E=0;E<l;++E)f[k+E]=e[A+E]}}if(n==="symmetric"){if(s)throw Error("`center` padding is not supported when `mode` is set to `symmetric`.");let w=o-1,v=i-1;for(let y=0;y<d;++y){let b=y*c,k=fa(y,w)*i;for(let A=0;A<c;++A){if(y<o&&A<i)continue;let E=(b+A)*l,C=(k+fa(A,v))*l;for(let N=0;N<l;++N)f[E+N]=e[C+N]}}}e=f,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){let[r,n]=e.size,s,a;if(this.do_thumbnail){let{height:o,width:i}=t;s=Math.min(o,i)}else if(Number.isInteger(t))s=t,a=this.config.max_size??s;else if(t!==void 0)s=t.shortest_edge,a=t.longest_edge;if(s!==void 0||a!==void 0){let o=s===void 0?1:Math.max(s/r,s/n),i=r*o,l=n*o,c=a===void 0?1:Math.min(a/i,a/l),d=Math.floor(Number((i*c).toFixed(2))),f=Math.floor(Number((l*c).toFixed(2)));if(this.size_divisibility!==void 0)[d,f]=mp([d,f],this.size_divisibility);return[d,f]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let{width:o,height:i}=t;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/n,c=o/r;if(Math.abs(1-c)<Math.abs(1-l))l=c;else c=l;i=pp(l*n,this.config.ensure_multiple_of),o=pp(c*r,this.config.ensure_multiple_of)}return[o,i]}else if(this.size_divisibility!==void 0)return mp([r,n],this.size_divisibility);else throw Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}async resize(e){let[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:n=null,do_convert_grayscale:s=null,do_flip_channel_order:a=null}={}){if(this.do_crop_margin)e=await this.crop_margin(e);let[o,i]=e.size;if(n??this.do_convert_rgb)e=e.rgb();else if(s)e=e.grayscale();if(this.do_resize)e=await this.resize(e);if(this.do_thumbnail)e=await this.thumbnail(e,this.size,this.resample);if(this.do_center_crop){let _,p;if(Number.isInteger(this.crop_size))_=this.crop_size,p=this.crop_size;else _=this.crop_size.width,p=this.crop_size.height;e=await e.center_crop(_,p)}let l=[e.height,e.width],c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale)this.rescale(c);if(t??this.do_normalize){let _=this.image_mean;if(!Array.isArray(this.image_mean))_=Array(e.channels).fill(_);let p=this.image_std;if(!Array.isArray(this.image_std))p=Array(e.channels).fill(p);if(_.length!==e.channels||p.length!==e.channels)throw 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){let _=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 Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){let p=c[_];c[_]=c[_+2],c[_+2]=p}}let f=new U("float32",c,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:f}}async _call(e,...t){if(!Array.isArray(e))e=[e];let r=await Promise.all(e.map((s)=>this.preprocess(s)));return{pixel_values:_r(r.map((s)=>s.pixel_values),0),original_sizes:r.map((s)=>s.original_size),reshaped_input_sizes:r.map((s)=>s.reshaped_input_size)}}static async from_pretrained(e,t={}){let r=await ar(e,ds,!0,t);return new this(r)}},Ma={};hs(Ma,{BeitFeatureExtractor:()=>P2,BitImageProcessor:()=>F2,CHMv2ImageProcessor:()=>L2,CLIPFeatureExtractor:()=>O2,CLIPImageProcessor:()=>Qm,ChineseCLIPFeatureExtractor:()=>I2,ConvNextFeatureExtractor:()=>N2,ConvNextImageProcessor:()=>Xm,DINOv3ViTImageProcessor:()=>B2,DPTFeatureExtractor:()=>$2,DPTImageProcessor:()=>Jm,DeiTFeatureExtractor:()=>D2,DeiTImageProcessor:()=>Ym,DetrFeatureExtractor:()=>z2,DetrImageProcessor:()=>Km,DonutFeatureExtractor:()=>R2,DonutImageProcessor:()=>_l,EfficientNetImageProcessor:()=>G2,GLPNFeatureExtractor:()=>j2,Gemma3ImageProcessor:()=>V2,Gemma4ImageProcessor:()=>fl,Glm46VImageProcessor:()=>U2,GroundingDinoImageProcessor:()=>W2,Idefics3ImageProcessor:()=>gp,ImageFeatureExtractor:()=>fe,ImageProcessor:()=>fe,JinaCLIPImageProcessor:()=>H2,Lfm2VlImageProcessor:()=>J2,Lfm3VlImageProcessor:()=>Z2,LlavaOnevisionImageProcessor:()=>eA,Mask2FormerImageProcessor:()=>rA,MaskFormerFeatureExtractor:()=>tA,MaskFormerImageProcessor:()=>ml,MobileNetV1FeatureExtractor:()=>nA,MobileNetV1ImageProcessor:()=>Zm,MobileNetV2FeatureExtractor:()=>sA,MobileNetV2ImageProcessor:()=>eg,MobileNetV3FeatureExtractor:()=>aA,MobileNetV3ImageProcessor:()=>tg,MobileNetV4FeatureExtractor:()=>oA,MobileNetV4ImageProcessor:()=>rg,MobileViTFeatureExtractor:()=>iA,MobileViTImageProcessor:()=>ng,NougatImageProcessor:()=>lA,OwlViTFeatureExtractor:()=>cA,OwlViTImageProcessor:()=>gl,Owlv2ImageProcessor:()=>uA,Phi3VImageProcessor:()=>fA,PixtralImageProcessor:()=>hA,PvtImageProcessor:()=>_A,Qwen2VLImageProcessor:()=>pl,RTDetrImageProcessor:()=>pA,Sam2ImageProcessor:()=>Ci,Sam3ImageProcessor:()=>Ci,SamImageProcessor:()=>Ci,SapiensFeatureExtractor:()=>mA,SapiensImageProcessor:()=>sg,SegformerFeatureExtractor:()=>gA,SegformerImageProcessor:()=>ag,SiglipImageProcessor:()=>wA,SmolVLMImageProcessor:()=>gp,Swin2SRImageProcessor:()=>vA,VLMImageProcessor:()=>q2,ViTFeatureExtractor:()=>yA,ViTImageProcessor:()=>og,VitMatteImageProcessor:()=>bA,VitPoseImageProcessor:()=>MA,YolosFeatureExtractor:()=>xA,YolosImageProcessor:()=>ig});var P2=class extends fe{},F2=class extends fe{},I2=class extends fe{},L2=class extends fe{},Qm=class extends fe{},O2=class extends Qm{},Xm=class extends fe{constructor(e){super(e);this.crop_pct=this.config.crop_pct??0.875}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let r=Math.floor(t/this.crop_pct),[n,s]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,s,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},N2=class extends Xm{},Ym=class extends fe{},D2=class extends Ym{},Km=class extends fe{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=dt(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Fa(...e)}post_process_panoptic_segmentation(...e){return qm(...e)}post_process_instance_segmentation(...e){return Hm(...e)}},z2=class extends Km{},B2=class extends fe{},_l=class extends fe{pad_image(e,t,r,n={}){let[s,a,o]=t,i=this.image_mean;if(!Array.isArray(this.image_mean))i=Array(o).fill(i);let l=this.image_std;if(!Array.isArray(l))l=Array(o).fill(i);let c=i.map((d,f)=>-d/l[f]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...n})}},R2=class extends _l{},Jm=class extends fe{},$2=class extends Jm{},G2=class extends fe{constructor(e){super(e);if(this.include_top=this.config.include_top??!0,this.include_top)this.image_std=this.image_std.map((t)=>t*t)}},V2=class extends fe{},pl=class extends fe{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){let r=this.patch_size*this.merge_size;return hl(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:r,original_sizes:n,reshaped_input_sizes:s}=await super._call(e,...t),a=r,{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;if(a.dims[0]===1)a=Ne(Array.from({length:o},()=>a),0);let c=a.dims[0]/o,d=a.dims[1],f=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),p=a.view(c,o,d,Math.floor(f/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*f*_,d*o*l*l),w=new U("int64",[c,f,_],[1,3]);return{pixel_values:p,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},U2=class extends pl{get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return hl(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}},j2=class extends fe{},W2=class extends fe{async _call(e){let t=await super._call(e),r=t.pixel_values.dims,n=gt([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},gp=class extends fe{constructor(e){super(e);this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,n]=e.dims.slice(-2),s=n/r;if(n>=r)n=Math.ceil(n/t)*t,r=Math.floor(n/s),r=Math.ceil(r/t)*t;else r=Math.ceil(r/t)*t,n=Math.floor(r*s),n=Math.ceil(n/t)*t;return{height:r,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw Error("No images provided.");if(!Array.isArray(e[0]))n=[e];else n=e}let s=[],a=[],o=[],i=[],l=[];for(let y of n){let b=await Promise.all(y.map((E)=>this.preprocess(E)));i.push(...b.map((E)=>E.original_size)),l.push(...b.map((E)=>E.reshaped_input_size)),b.forEach((E)=>E.pixel_values.unsqueeze_(0));let{longest_edge:k}=this.max_image_size,A;if(t??this.do_image_splitting){let E=Array(b.length),C=Array(b.length);A=await Promise.all(b.map(async(N,M)=>{let G=this.get_resize_for_vision_encoder(N.pixel_values,k),R=await Gt(N.pixel_values,{size:[G.height,G.width]}),{frames:q,num_splits_h:X,num_splits_w:Q}=await this.split_image(R,this.max_image_size);return E[M]=X,C[M]=Q,Ne(q,0)})),a.push(E),o.push(C)}else{let E=[k,k];A=await Promise.all(b.map((C)=>Gt(C.pixel_values,{size:E}))),a.push(Array(b.length).fill(0)),o.push(Array(b.length).fill(0))}s.push(Ne(A,0))}let c=s.length,[d,f,_,p]=s[0].dims,w,v;if(c===1)w=s[0].unsqueeze_(0),v=dt([c,d,_,p],!0);else{let y=Math.max(...s.map((A)=>A.dims.at(0)));v=dt([c,y,_,p],!0);let b=v.data,k=y*_*p;for(let A=0;A<c;++A){let E=s[A].dims[0];if(E<y){s[A]=Ne([s[A],dt([y-E,f,_,p],0)],0);let C=A*k+E*_*p,N=(A+1)*k;b.fill(!1,C,N)}}w=_r(s,0)}return{pixel_values:w,pixel_attention_mask:v,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){let r=t,n=t,s=[],[a,o]=e.dims.slice(-2),i=0,l=0;if(a>r||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);let c=Math.ceil(a/i),d=Math.ceil(o/l);for(let p=0;p<i;++p)for(let w=0;w<l;++w){let v,y,b,k;if(p===i-1)y=a-c,k=a;else y=p*c,k=(p+1)*c;if(w===l-1)v=o-d,b=o;else v=w*d,b=(w+1)*d;let C=await Mm(e,[y,v],[k,b],[2,3]);s.push(C)}let f=r,_=n;if(a!==f||o!==_)e=await Gt(e,{size:[f,_]})}return s.push(e),{frames:s,num_splits_h:i,num_splits_w:l}}},q2=class extends fe{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e});this.constant_values=this.config.background_color.map((t)=>t*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},H2=class extends fe{constructor(e){let{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,o=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},i=n==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:s,do_normalize:!0})}};function wp(e,t){return Math.round(e/t)*t}function Q2(e,t,r,n,s){let a=1/0,o=[1,1],i=r*n;for(let l of t){let c=Math.abs(e-l[0]/l[1]);if(c<a)a=c,o=l;else if(c===a&&i>0.5*s*s*l[0]*l[1])o=l}return o}function X2(e,t){let r=[],n=new Set;for(let s=e;s<=t;++s)for(let a=1;a<=s;++a)for(let o=1;o<=s;++o){let i=a*o;if(i>=e&&i<=t){let l=a<<16|o;if(!n.has(l))n.add(l),r.push([a,o])}}return r.sort((s,a)=>s[0]*s[1]-a[0]*a[1])}function Y2(e,t){let[r,n,s,a]=e.dims,o=Math.floor(s/t),i=Math.floor(a/t),l=t*t*n,c=e.data,d=new Float32Array(r*o*i*l),f=s*a;for(let _=0;_<r;++_){let p=_*n*f,w=_*o*i*l;for(let v=0;v<o;++v)for(let y=0;y<i;++y){let b=w+(v*i+y)*l;for(let k=0;k<t;++k){let A=(v*t+k)*a+y*t;for(let E=0;E<t;++E){let C=A+E;for(let N=0;N<n;++N)d[b++]=c[p+N*f+C]}}}}return new U("float32",d,[r,o*i,l])}function K2(e,t){let[,r,n]=e.dims,s=new BigInt64Array(t);s.fill(1n,0,r);let a=e;if(r<t){let o=new Float32Array(t*n);o.set(e.data),a=new U("float32",o,[1,t,n])}return{padded:a,mask:new U("int64",s,[t])}}var J2=class extends fe{constructor(e){super(e);this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let 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){let r=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,wp(e,r)),s=Math.max(this.encoder_patch_size,wp(t,r));return n*s>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let r=X2(this.min_tiles,this.max_tiles),[n,s]=Q2(t/e,r,t,e,this.tile_size);return{grid_width:n,grid_height:s,target_width:this.tile_size*n,target_height:this.tile_size*s}}async _call(e,{return_row_col_info:t=null}={}){let r;if(!Array.isArray(e))r=[[e]];else if(!Array.isArray(e[0]))r=[e];else r=e;let n=[],s=[],a=[],o=[],i=[],l=[];for(let d of r){let f=await Promise.all(d.map((_)=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of f){let[,p,w]=_.dims,v=_.unsqueeze_(0),y=this.encoder_patch_size*this.downsample_factor,b=y**2,[k,A]=hl(Math.max(y,p),Math.max(y,w),y,this.min_image_tokens*b,this.max_image_tokens*b).map((R)=>Math.max(y,R)),E,C=1,N=1,M=this._is_image_too_large(p,w),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(M&&G){let{grid_width:R,grid_height:q,target_width:X,target_height:Q}=this._get_grid_layout(p,w);C=q,N=R;let H=await Gt(v,{size:[Q,X]});E=[];for(let B=0;B<q;++B)for(let P=0;P<R;++P){let Y=B*this.tile_size,ue=P*this.tile_size;E.push(H.slice(null,null,[Y,Y+this.tile_size],[ue,ue+this.tile_size]))}if(this.use_thumbnail&&R*q!==1)E.push(await Gt(v,{size:[A,k]}))}else E=[await Gt(v,{size:[A,k]})];for(let R of E){let[,,q,X]=R.dims,Q=Y2(R,this.encoder_patch_size),{padded:H,mask:B}=K2(Q,this.max_num_patches);n.push(H),s.push(B),a.push([Math.floor(q/this.encoder_patch_size),Math.floor(X/this.encoder_patch_size)])}o.push(C),i.push(N),l.push([A,k])}}let c={pixel_values:Ne(n,0),pixel_attention_mask:_r(s,0),spatial_shapes:new U("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};if(t??this.return_row_col_info)c.image_rows=o,c.image_cols=i,c.image_sizes=l;return c}},Z2=class extends pl{async _call(e,...t){if(!Array.isArray(e))e=[e];let r=await Promise.all(e.map((n)=>super._call(n,...t)));return{pixel_values:Ne(r.map((n)=>n.pixel_values),0),image_grid_thw:Ne(r.map((n)=>n.image_grid_thw),0),original_sizes:r.flatMap((n)=>n.original_sizes),reshaped_input_sizes:r.flatMap((n)=>n.reshaped_input_sizes)}}},eA=class extends fe{},ml=class extends fe{post_process_panoptic_segmentation(...e){return qm(...e)}post_process_instance_segmentation(...e){return Hm(...e)}},tA=class extends ml{},rA=class extends ml{},Zm=class extends fe{},nA=class extends Zm{},eg=class extends fe{},sA=class extends eg{},tg=class extends fe{},aA=class extends tg{},rg=class extends fe{},oA=class extends rg{},ng=class extends fe{},iA=class extends ng{},lA=class extends _l{},gl=class extends fe{post_process_object_detection(...e){return Fa(...e)}},cA=class extends gl{},uA=class extends gl{},Mt=336,dA=[2,3],{ceil:Ei,floor:gn,sqrt:Ai}=Math,fA=class extends fe{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0});this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){let{num_img_tokens:r}=this.config;return gn((gn(t/Mt)*gn(e/Mt)+1)*r+1+(gn(t/Mt)+1)*Ai(r))}get_resize_output_image_size(e,t){let r=this._num_crops,[n,s]=e.size,a=n/s,o=1;while(o*Math.ceil(o/a)<=r)o+=1;o-=1;let i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,n={}){let[s,a]=t,o=Mt*Ei(s/Mt),i=Mt*Ei(a/Mt),l=[1,1,1].map((c,d)=>(c-this.image_mean[d])/this.image_std[d]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Ai(t)%1!==0)throw Error("num_crops must be a square number >= 4");if(!Array.isArray(e))e=[e];let r=e.length,n=await Promise.all(e.map((f)=>this.preprocess(f))),s=n.map((f)=>f.original_size),a=n.map((f)=>f.reshaped_input_size),o=[];for(let{pixel_values:f}of n){f.unsqueeze_(0);let[_,p]=f.dims.slice(-2),w=await Gt(f,{size:[Mt,Mt],mode:"bicubic"});if(t>0){let v=[],y=Ai(t),b=gn(p/y),k=gn(_/y);for(let E=0;E<y;++E)for(let C=0;C<y;++C){let N,M,G,R;if(E===y-1)M=_-k,R=_;else M=E*k,R=(E+1)*k;if(C===y-1)N=p-b,G=p;else N=C*b,G=(C+1)*b;let Q=await Mm(f,[M,N],[R,G],dA);v.push(Q)}let A=await Gt(Ne(v,0),{size:[Mt,Mt],mode:"bicubic"});o.push(Ne([w,A],0))}else o.push(w)}let i=_r(o,0),l=a.map((f)=>f.map((_)=>Mt*Ei(_/Mt))),c=new U("int64",l.flat(),[r,2]),d=l.map(([f,_])=>this.calc_num_image_tokens_from_image_size(_,f));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},hA=class extends fe{get_resize_output_image_size(e,t){let{longest_edge:r}=t;if(r===void 0)throw Error("size must contain 'longest_edge'");let[n,s]=e.size,a=Math.max(n,s)/r,o=n,i=s;if(a>1)o=Math.floor(n/a),i=Math.floor(s/a);let{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw Error("config must contain 'spatial_merge_size'");let d=l*c,f=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[f*d,_*d]}},_A=class extends fe{},pA=class extends fe{post_process_object_detection(...e){return Fa(...e)}},Ci=class extends fe{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=P_(e);if(s.length===3){if(!n)s=[1,...s];e=[e]}else if(s.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[o,i]=t[a],[l,c]=r[a],d=[c/i,l/o];for(let f=0;f<e[a].length;++f)for(let _=0;_<e[a][f].length;++_)for(let p=0;p<e[a][f][_].length;++p)e[a][f][_][p]*=d[p%2]}return new U("float32",Float32Array.from(e.flat(1/0)),s)}add_input_labels(e,t){let r=P_(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((n,s)=>n!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:n=null}={}){let s=await super._call(e);if(t)s.input_points=this.reshape_input_points(t,s.original_sizes,s.reshaped_input_sizes);if(r){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(r,s.input_points)}if(n)s.input_boxes=this.reshape_input_points(n,s.original_sizes,s.reshaped_input_sizes,!0);return s}async post_process_masks(e,t,r,{mask_threshold:n=0,binarize:s=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let i=[a.height,a.width];for(let l=0;l<t.length;++l){let c=t[l],d=r[l],f=await Gt(e[l],{mode:"bilinear",size:i});if(f=f.slice(null,null,[0,d[0]],[0,d[1]]),f=await Gt(f,{mode:"bilinear",size:c}),s){let _=f.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)if(_[w]>n)p[w]=1;f=new U("bool",p,f.dims)}o.push(f)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:n=0.3413333333333333,points_per_crop:s=32,crop_n_points_downscale_factor:a=1}={}){}},sg=class extends fe{post_process_semantic_segmentation(...e){return Wm(...e)}},mA=class extends sg{},ag=class extends fe{post_process_semantic_segmentation(...e){return Wm(...e)}},gA=class extends ag{},wA=class extends fe{},vA=class extends fe{pad_image(e,t,r,n={}){let[s,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}},og=class extends fe{},yA=class extends og{},bA=class extends fe{async _call(e,t){if(!Array.isArray(e))e=[e];if(!Array.isArray(t))t=[t];let r=await Promise.all(e.map((a)=>this.preprocess(a))),n=await Promise.all(t.map((a)=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:_r(r.map((a,o)=>Ne([a.pixel_values,n[o].pixel_values],0)),0),original_sizes:r.map((a)=>a.original_size),reshaped_input_sizes:r.map((a)=>a.reshaped_input_size)}}},MA=class extends fe{post_process_pose_estimation(e,t,{threshold:r=null}={}){let n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let c=0;c<s;++c){let d=n[c],f=t[c],_=[];for(let p=0;p<f.length;++p){let w=f[p],v=[],y=[],b=[],k=w.at(-2)/i,A=w.at(-1)/o;for(let E=0;E<d.length;++E){let[C,N]=[0,0],M=0,G=-1/0,R=d[E];for(let X=0;X<R.length;++X){let Q=R[X];for(let H=0;H<Q.length;++H){let B=Q[H];M+=B,G=Math.max(G,B),C+=(H+0.5)*B,N+=X*B}}if(r!=null&&G<r)continue;let q=[k*C/M,A*N/M];v.push(q),b.push(E),y.push(G)}_.push({bbox:w,scores:y,labels:b,keypoints:v})}l.push(_)}return l}},ig=class extends fe{post_process_object_detection(...e){return Fa(...e)}},xA=class extends ig{},ot=class{static async from_pretrained(e,t={}){let r=await ar(e,ds,!0,t),n=r.image_processor_type??r.feature_extractor_type,s=Ma[n?.replace(/Fast$/,"")];if(!s){if(n!==void 0)ce.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Pa}.`);s=fe}return new s(r)}},kA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;constructor(e,t,r){super(e,t,r);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:s,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(s??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1000}construct_prompts(e){if(typeof e==="string")e=[e];let t=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(let[n,s]of this.task_prompts_with_input)if(r.includes(n)){t.push(s.replaceAll("{input}",r).replaceAll(n,""));break}if(t.length!==e.length)t.push(r)}return t}post_process_generation(e,t,r){let n=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let s;switch(n){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(let[c,d,...f]of o)i.push(d?d.trim():i.at(-1)??""),l.push(f.map((_,p)=>(Number(_)+0.5)/this.size_per_bin*r[p%2]));s={labels:i,[a]:l};break;default:throw Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:s}}async _call(e,t=null,r={}){if(!e&&!t)throw Error("Either text or images must be provided");let n=await this.image_processor(e,r),s=t?this.tokenizer(this.construct_prompts(t),r):{};return{...n,...s}}},TA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r);this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:s,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=s,this.eoi_token=a;let o=s.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
29
|
+
|
|
30
|
+
${n}${o}${a}
|
|
31
|
+
|
|
32
|
+
`}async _call(e,t=null,r={}){if(typeof e==="string")e=[e];let n;if(t)n=await this.image_processor(t,r),e=e.map((a)=>a.replaceAll(this.boi_token,this.full_image_sequence));return{...this.tokenizer(e,r),...n}}},EA=class extends Ee{static image_processor_class=ot;static feature_extractor_class=Ft;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;let{audio_token_id:n,boa_token:s,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;let f=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
33
|
+
|
|
34
|
+
${s}${f}${o}
|
|
35
|
+
|
|
36
|
+
`,this.image_token_id=i,this.boi_token=l,this.image_token=c;let _=c.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
37
|
+
|
|
38
|
+
${l}${_}${d}
|
|
39
|
+
|
|
40
|
+
`}async _call(e,t=null,r=null,n={}){if(typeof e==="string")e=[e];let s;if(r)s=await this.feature_extractor(r,n),e=e.map((i)=>i.replaceAll(this.audio_token,this.full_audio_sequence));let a;if(t)a=await this.image_processor(t,n),e=e.map((i)=>i.replaceAll(this.image_token,this.full_image_sequence));return{...this.tokenizer(e,n),...a,...s}}};var wl=class extends Ee{static image_processor_class=ot;static tokenizer_class=Te;static image_token="<|image_pad|>";async _call(e,t=null,...r){if(!Array.isArray(e))e=[e];let n,s;if(t)n=await this.image_processor(t),s=n.image_grid_thw;if(s){let o=this.image_processor.config.merge_size**2,i=0,l=this.constructor.image_token,c=s.tolist();e=e.map((d)=>{while(d.includes(l)){let f=Number(c[i++].reduce((_,p)=>_*p,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(f/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...n}}},AA=class extends wl{static image_token="<|image|>"},CA=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:n}=this.feature_extractor.config,s=Math.floor(r/n),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*s}async _call(e,t=null,r={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){let{input_features:a}=await this.feature_extractor(t);n.input_features=a;let o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);n.input_features_mask=new U("bool",i,[1,o]);let l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}};function SA(e,t){let n=e.dims.at(-1)-1,s=e.tolist();s.fill(!1,0,1),s.fill(!1,n);let a=t.tolist();return s.map((o,i)=>o?i:null).filter((o)=>o!==null).map((o)=>a[o])}var PA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;async _call(e,t,r={}){let n=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:r=0.25,text_threshold:n=0.25,target_sizes:s=null}={}){let{logits:a,pred_boxes:o}=e,i=a.dims[0];if(s!==null&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),f=o.tolist().map((p)=>p.map((w)=>jm(w))),_=[];for(let p=0;p<i;++p){let w=s!==null?s[p]:null;if(w!==null)f[p]=f[p].map((A)=>A.map((E,C)=>E*w[(C+1)%2]));let v=d[p],y=[],b=[],k=[];for(let A=0;A<l;++A){let E=v[A];if(E<=r)continue;let C=f[p][A],N=c[p][A];y.push(E),k.push(C);let M=SA(N.gt(n),t[p]);b.push(M)}_.push({scores:y,boxes:k,labels:this.batch_decode(b)})}return _}};function FA(e,t,r,n,s,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=n+`<row_${i+1}_col_${l+1}>`+s.repeat(e);o+=`
|
|
41
|
+
`}return o+=`
|
|
42
|
+
${n}${a}`+s.repeat(e)+`${n}`,o}function IA(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function LA(e,t,r,n,s,a){if(e===0&&t===0)return IA(r,n,s,a);return FA(r,e,t,n,s,a)}var vp=class extends Ee{static image_processor_class=ot;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 n;if(t)n=await this.image_processor(t,r);if(!Array.isArray(e))e=[e];let s=n.rows??[Array(e.length).fill(0)],a=n.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,i=[],l=[];for(let d=0;d<e.length;++d){let f=e[d],_=s[d],p=a[d];i.push(CM(f,this.image_token));let w=_.map((b,k)=>LA(b,p[k],o,this.fake_image_token,this.image_token,this.global_img_token)),v=f.split(this.image_token);if(v.length===0)throw Error("The image token should be present in the text.");let y=v[0];for(let b=0;b<w.length;++b)y+=w[b]+v[b+1];l.push(y)}return{...this.tokenizer(l),...n}}},OA=class extends Ee{static image_processor_class=ot;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"}={}){if(!t)t=await Promise.all(e.filter((v)=>v.images).flatMap((v)=>v.images).map((v)=>Vt.read(v)));else if(!Array.isArray(t))t=[t];let n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=(v)=>n.encode(v,{add_special_tokens:!1}),o=s.split(this.image_tag),i=o.length-1;if(t.length!==i)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);let[l,c,d]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),f=a(o[0]),_=Array(f.length).fill(!1);for(let v=1;v<o.length;++v){let y=Array(this.num_image_tokens).fill(l),b=a(o[v]);f=Bt(f,[c],y,[d],b);let k=Array(this.num_image_tokens).fill(!0);_=Bt(_,[!1],k,[!1],Array(b.length).fill(!1))}let p=[1,f.length],w={input_ids:new U("int64",f,p),attention_mask:new U("int64",Array(f.length).fill(1),p),images_seq_mask:new U("bool",_,p),images_emb_mask:new U("bool",Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){let v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},NA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;async _call(e=null,t=null,r={}){if(!e&&!t)throw Error("Either text or images must be provided");let n=e?this.tokenizer(e,r):{},s=t?await this.image_processor(t,r):{};return{...n,...s}}},DA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;async _call(e,t=null,r={}){let{image_rows:n,image_cols:s,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){let i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:f=!0}=this.image_processor.config,_=(k)=>Math.ceil(Math.floor(k/d)/c),p=_(l)**2,w=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",y=this.config.image_thumbnail??"<|img_thumbnail|>";if(!Array.isArray(t))t=[t];let b=0;t=t.map((k)=>{let A=k.split(i);return A[0]+A.slice(1).map((E)=>{let C=b++,[N,M]=a[C],G=n[C],R=s[C],q=_(N)*_(M),X=w;if(G>1||R>1){let Q=i.repeat(p);for(let H=0;H<G;++H)for(let B=0;B<R;++B)X+=`<|img_row_${H+1}_col_${B+1}|>`+Q;if(f)X+=y+i.repeat(q)}else X+=i.repeat(q);return X+v+E}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},zA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;async _call(e,t=null,r={}){let n=e?await this.image_processor(e,r):{};if(t!==null){if(!Array.isArray(t))t=[t];let s=this.tokenizer.config.image_token??"<|image|>",a=n.image_grid_thw?.tolist()??[],o=t.reduce((c,d)=>c+d.split(s).length-1,0);if(o!==a.length)throw Error(`Found ${o} ${s} tokens in the text but received ${a.length} images.`);let i=this.image_processor.config.merge_size,l=0;t=t.map((c)=>c.replaceAll(s,()=>{let d=Number(a[l++].reduce((f,_)=>f*_,1n));return s.repeat(d/i**2)}))}return{...n,...t!==null?this.tokenizer(t,r):{}}}},BA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;static uses_processor_config=!0;async _call(e,t=null,r={}){let n=await this.image_processor(e,r);if(t){let[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;if(t=structuredClone(t),!Array.isArray(t))t=[t];for(let f=0;f<t.length;++f)t[f]=t[f].replace(i,i.repeat(d))}let s=t?this.tokenizer(t,r):{};return{...n,...s}}},yp={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},RA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;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(!yp.hasOwnProperty(t))throw Error(`Format ${t} is not supported.`);let[r,n]=yp[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let f=0;f<a;++f){let _=c[f],p=[],w=[];for(let y=1;y<o;++y){let[b,k]=qe(st(_[y]));if(w.push(b),k==n)break;p.push(k)}let v=w.length>0?w.reduce((y,b)=>y*b,1):0;l.push(p),i.push(v)}return[s(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map((t)=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map((t)=>t.replaceAll(" ",""))}batch_decode([e,t,r]){let[n,s]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),c=[],d=[];for(let f=0;f<n.length;++f){let[_,p]=qe([s[f],o[f],l[f]]);c.push([n[f],a[f],i[f]][p]),d.push(_)}return{generated_text:c,scores:d,char_preds:n,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),r=await Te.from_pretrained("Xenova/gpt2"),n=await Te.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:n},t}async _call(e,t=null){let r=await this.image_processor(e);if(t)r.labels=this.tokenizer(t).input_ids;return r}},$A=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e){return await this.feature_extractor(e)}},GA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot},wn="<image>";function VA(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
|
|
43
|
+
`}var UA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;static uses_processor_config=!1;async _call(e,t=null,r={}){if(!t)ce.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t="";if(!Array.isArray(e))e=[e];if(!Array.isArray(t))t=[t];let n=this.tokenizer.bos_token,s=this.image_processor.config.image_seq_length,a;if(t.some((l)=>l.includes(wn)))a=t.map((l)=>{let c=l.replaceAll(wn,wn.repeat(s)),d=c.lastIndexOf(wn),f=d===-1?0:d+wn.length;return c.slice(0,f)+n+c.slice(f)+`
|
|
44
|
+
`});else ce.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)=>VA(l,n,s,wn,e.length));let o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},bp="<|image|>",jA=/<\|image_\d+\|>/g,WA=class extends Ee{static image_processor_class=ot;static tokenizer_class=Te;async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){if(!Array.isArray(e))e=[e];let a,o;if(t){o=await this.image_processor(t,{num_crops:s});let{num_img_tokens:i}=o,l=e.map((d,f)=>d.split(jA).join(bp.repeat(i[f])));a=this.tokenizer(l,{padding:r,truncation:n});let c=this.tokenizer._tokenizer.token_to_id(bp);a.input_ids.map_((d)=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},qA=class extends Ee{static tokenizer_class=Te;static image_processor_class=ot;static uses_processor_config=!0;async _call(e,t=null,r={}){let n=await this.image_processor(e,r);if(t){let[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:d,spatial_merge_size:f}=this.config,_=d*f,p=Math.floor(a/_),w=Math.floor(o/_);if(t=structuredClone(t),!Array.isArray(t))t=[t];for(let v=0;v<t.length;++v){let y=i.repeat(w),b=y+l,k=y+c,A=b.repeat(p-1)+k;t[v]=t[v].replace(i,A)}}let s=t?this.tokenizer(t,r):{};return{...n,...s}}},HA=class extends Ee{static feature_extractor_class=$m;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}},lg=class extends wl{},QA=class extends lg{},cg=class extends Ee{static image_processor_class=ot;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)}},ug=class extends cg{},XA=class extends ug{},YA=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e){return await this.feature_extractor(e)}},KA=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;static uses_processor_config=!0;async _call(e,t=null,r={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){let a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+0.0001),l=1+Math.ceil(i/this.config.stack_factor);n.audio_token_len=[l],n.audio_values=o;let c=this.config.audio_placeholder;if(!e.includes(c))throw Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},ra="[AUDIO]",JA="[BEGIN_AUDIO]",ZA=375;function eC(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.subarray(n,Math.min(n+t,e.length)));return r}var tC=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;static uses_processor_config=!1;async _call(e,t=null,r={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){if(!e.includes(ra))throw Error(`The input text does not contain the audio token ${ra}.`);if(!Array.isArray(t))t=[t];let a=e.split(ra),o=a.length-1;if(o!==t.length)throw Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);let i=this.feature_extractor.config.n_samples,l=t.map((p)=>eC(p,i)),c=l.map((p)=>p.length),d=l.flat(),f=(await Promise.all(d.map((p)=>this.feature_extractor(p,r)))).map((p)=>p.input_features);n.audio_values=f.length>1?Ne(f,0):f[0];let _=a[0];for(let p=0;p<c.length;++p){_+=JA;for(let w=0;w<c[p];++w)_+=ra.repeat(ZA);_+=a[p+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},Mp=32,Si=6,na=8,rC=10,nC=32,sC=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Si+1)*na}get num_samples_first_audio_chunk(){let{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(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return na*e+t}get num_right_pad_tokens(){return Si+1+rC}get audio_length_per_tok(){return na}get raw_audio_length_per_tok(){return na*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(at(e,"VoxtralRealtimeProcessor"),!t&&!r)throw Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){let n=Mp*this.raw_audio_length_per_tok,s=new Float32Array(n+e.length);s.set(e,n);let a=await this.feature_extractor(s,{center:!0}),i=1+(Mp+Si),l=new BigInt64Array(i).fill(BigInt(nC));return l[0]=1n,{input_ids:new U("int64",l,[1,i]),...a}}else{let n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,s=new Float32Array(e.length+n);return s.set(e),await this.feature_extractor(s,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},aC=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e){return await this.feature_extractor(e)}},oC=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e){return await this.feature_extractor(e)}},iC=class extends Ee{static tokenizer_class=Te;static feature_extractor_class=Ft;async _call(e){return await this.feature_extractor(e)}},lC=class{static async from_pretrained(e,t={}){let r=await ar(e,ds,!0,t),{image_processor_type:n,feature_extractor_type:s,processor_class:a}=r;if(a&&Ri[a])return Ri[a].from_pretrained(e,t);if(!n&&!s)throw Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let o={};if(n){let l=Ma[n.replace(/Fast$/,"")];if(!l)throw Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){let l=Ma[s];if(l)o.image_processor=new l(r);else{let c=dl[s];if(!c)throw Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new c(r)}}return new Ee({},o,null)}};async function cC(e,t){return await ar(e,"config.json",!0,t)}function vn(e){let t={},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"lfm3_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=vn(e.text_config);break;case"moondream1":r=vn(e.phi_config);break;case"musicgen":r=vn(e.decoder);break;case"multi_modality":r=vn(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"lfm3":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"deepseek_v4":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv=e.model_type==="deepseek_v4"?"head_dim":"qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"zaya":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"hrm_text":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";let{num_hidden_layers:s,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:s,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":let i=vn(e.decoder),l="num_decoder_layers"in i,c=et(e,["model_type","is_encoder_decoder"]);if(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;else c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size;return c}let n={...r,...et(e,["model_type","multi_query","is_encoder_decoder"])};for(let s in t)n[s]=e[t[s]];return n}function Ia(e,t){if(!(e instanceof Gi))e=new Gi(e);let r=t?.prefix??"past_key_values",n=r==="present"?"present":"past",s=new Set;if(["lfm2","lfm2_moe","lfm3"].includes(e.model_type)){let{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention"||a[o]==="sliding_attention")s.add(`${r}.${o}.key`),s.add(`${r}.${o}.value`);else if(a[o]==="conv")s.add(`${n}_conv.${o}`);else throw Error(`Unsupported layer type: ${a[o]}`);return s}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){let a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??o?.length;for(let l=0;l<i;++l){if(!o||o[l]==="mamba")s.add(`${n}_conv.${l}`),s.add(`${n}_ssm.${l}`);if(!o||o[l]==="attention")s.add(`${r}.${l}.key`),s.add(`${r}.${l}.value`)}return s}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){let{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")s.add(`${r}.${o}.key`),s.add(`${r}.${o}.value`);else if(a[o]==="linear_attention"){if(e.model_type==="olmo_hybrid")s.add(`${n}_conv.${o}.key`),s.add(`${n}_conv.${o}.value`),s.add(`${n}_conv.${o}.query`);else s.add(`${n}_conv.${o}`);s.add(`${n}_recurrent.${o}`)}else throw Error(`Unsupported layer type: ${a[o]}`);return s}else if(["gemma4","gemma4_text"].includes(e.model_type)){let a=e.model_type==="gemma4"?e.text_config:e,o=a.num_hidden_layers,i=a.num_kv_shared_layers??0,l=o-i;for(let c=0;c<l;++c)s.add(`${r}.${c}.key`),s.add(`${r}.${c}.value`);return s}else if(e.model_type==="deepseek_v4"){let{layer_types:a,num_hidden_layers:o}=e;for(let i=0;i<o;++i){s.add(`${r}.${i}.key`),s.add(`${r}.${i}.value`);let l=a[i];if(l==="compressed_sparse_attention")s.add(`${n}_compressor.${i}.kv`),s.add(`${n}_compressor.${i}.gate`),s.add(`${n}_indexer.${i}.kv`),s.add(`${n}_indexer.${i}.gate`);else if(l==="heavily_compressed_attention")s.add(`${n}_compressor.${i}.kv`),s.add(`${n}_compressor.${i}.gate`);else if(l&&l!=="sliding_attention")throw Error(`Unsupported layer type: ${l}`)}return s}else if(e.model_type==="zaya"){let{num_hidden_layers:a,cca_time1:o}=e,i=o??1;for(let l=0;l<a;l+=i)s.add(`${r}.${l}.key`),s.add(`${r}.${l}.value`),s.add(`${r}.${l}.conv_state`),s.add(`${r}.${l}.shift_state`);return s}else if(["lfm2_vl","lfm3_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let a;if(e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder")a=e.audio_config;else a=e.text_config;return Ia(a,t)}return uC(e,{prefix:r})}function uC(e,{prefix:t="past_key_values"}={}){let r=new Set,n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n)for(let s=0;s<n.num_decoder_layers;++s)r.add(`${t}.${s}.encoder.key`),r.add(`${t}.${s}.encoder.value`),r.add(`${t}.${s}.decoder.key`),r.add(`${t}.${s}.decoder.value`);else if(n.multi_query)for(let s=0;s<n.num_layers;++s)r.add(`${t}.${s}.key_value`);else for(let s=0;s<n.num_layers;++s)r.add(`${t}.${s}.key`),r.add(`${t}.${s}.value`);return r}var Gi=class e{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=vn(this)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){if(n&&!(n instanceof e))n=new e(n);let i=n??await cC(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},fs=class{static async from_pretrained(...e){return Gi.from_pretrained(...e)}};function dg(e,t,r){if(!e)return 0;if(typeof e==="object"&&e!==null){if(e.hasOwnProperty(t))return+e[t];if(e.hasOwnProperty(r))return+e[r];return 0}return+e}function fg(e,t){let r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function dC(e,t,r,n){let s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await ya(e,a,!0,r,pe.IS_NODE_ENV)}async function fC(e,t,r,n,s,a={}){let o=`${t}${r}.onnx`,i=pe.IS_NODE_ENV,l=[],c=dg(s,o,t);if(c>0){if(c>tp)throw Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${tp}).`);let d=fg(o,c);for(let f of d){let _=`${n.subfolder??""}/${f}`;l.push(ya(e,_,!0,n,i).then((p)=>p instanceof Uint8Array?{path:f,data:p}:f))}}else if(a.externalData!==void 0)l=a.externalData.map(async(d)=>{if(typeof d.data==="string"){let f=await ya(e,d.data,!0,n);return{...d,data:f}}return d});return Promise.all(l)}async function hC(e,t,r,n=!1,s=void 0){let a=r.config?.["transformers.js_config"]??{},o=vm(r.device??a.device,t,{warn:(k)=>ce.info(k)}),i=IT(o),l=a.device_config??{};if(l.hasOwnProperty(o))a={...a,...l[o]};let c=ym(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:(k)=>ce.info(k)});if(!ba.hasOwnProperty(c))throw Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(Qe).join(", ")}`);else if(o==="webgpu"&&!pe.IS_NODE_ENV&&c===Qe.fp16&&!await NT())throw Error(`The device (${o}) does not support fp16.`);let d=ba[c],f={...r.session_options};f.executionProviders??=i;let _=a.free_dimension_overrides;if(_)f.freeDimensionOverrides??=_;else if(o.startsWith("webnn")&&!f.freeDimensionOverrides)ce.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.`);let p=dC(e,t,r,d),w=r.use_external_data_format??a.use_external_data_format,v=await fC(e,t,d,r,w,f);if(v.length>0&&(!pe.IS_NODE_ENV||v.some((k)=>typeof k!=="string")))f.externalData=v;if(n&&o==="webgpu"){let k=Ia(r.config,{prefix:"present",session_name:s});if(k.size>0&&!sl()){let A={};for(let E of k)A[E]="gpu-buffer";f.preferredOutputLocation=A}}return{buffer_or_path:await p,session_options:f,session_config:{dtype:c,device:o}}}async function _C(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async(s)=>{let a=n?.[s]??!1,{buffer_or_path:o,session_options:i,session_config:l}=await hC(e,t[s],r,a,s),c=await mm(o,i,l);return[s,c]})))}function hg(e){for(let t in e)if(wm(e[t]))e[t]=new U(e[t]);else if(typeof e[t]==="object")hg(e[t]);return e}async function ye(e,t){let r=pC(e,t);try{let n=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i=o.ort_tensor;if(pe.IS_NODE_ENV){if(typeof Float16Array<"u"&&i.cpuData instanceof Float16Array)i.cpuData=new Uint16Array(i.cpuData.buffer)}return[a,i]})),s=await gm(e,n);return hg(s)}catch(n){let s=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i={type:o.type,dims:o.dims,location:o.location};if(i.location!=="gpu-buffer")i.data=o.data;return[a,i]}));throw ce.error(`An error occurred during model execution: "${n}".`),ce.error("Inputs given to model:",s),n}}function pC(e,t){let r=Object.create(null),n=[];for(let o of e.inputNames){let i=t[o];if(!(i instanceof U)){n.push(o);continue}r[o]=sl()?i.clone():i}if(n.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);let s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let o=Object.keys(t).filter((i)=>!e.inputNames.includes(i));ce.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var Ue=class{},mC=class extends Ue{constructor({last_hidden_state:e,hidden_states:t=null,attentions:r=null}){super();this.last_hidden_state=e,this.hidden_states=t,this.attentions=r}},oe=class extends Ue{constructor({logits:e,...t}){super();this.logits=e;let r=Object.values(t);if(r.length>0)this.attentions=r}},He=class extends Ue{constructor({logits:e}){super();this.logits=e}},Xe=class extends Ue{constructor({logits:e}){super();this.logits=e}},it=class extends Ue{constructor({start_logits:e,end_logits:t}){super();this.start_logits=e,this.end_logits=t}},Or=class extends Ue{constructor({logits:e}){super();this.logits=e}},gC=class extends Ue{constructor({logits:e,past_key_values:t}){super();this.logits=e,this.past_key_values=t}},wC=class extends Ue{constructor({logits:e,past_key_values:t,encoder_outputs:r,decoder_attentions:n=null,cross_attentions:s=null}){super();this.logits=e,this.past_key_values=t,this.encoder_outputs=r,this.decoder_attentions=n,this.cross_attentions=s}},_g=class extends Ue{constructor({alphas:e}){super();this.alphas=e}},Ht=class extends mt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},vC=class extends mt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Vi=class extends mt{constructor(){super();this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(let n of this.processors)r=n(e,r);return r}[Symbol.iterator](){return this.processors.values()}},yC=class extends Ht{constructor(e){super();this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){let n=t[r].data;n.fill(-1/0),n[this.bos_token_id]=0}return t}},bC=class extends Ht{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){let n=t[r].data;n.fill(-1/0);for(let s of this.eos_token_id)n[s]=0}return t}},MC=class extends Ht{constructor(e){super();this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data;for(let s of this.suppress_tokens)n[s]=-1/0}return t}},pg=class extends Ht{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){let n=t[r].data;for(let s of this.begin_suppress_tokens)n[s]=-1/0}return t}},xC=class extends Ht{constructor(e,t){super();if(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){let n=t[r].data;if(n[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){n.subarray(0,this.timestamp_begin).fill(-1/0);continue}let s=e[r].slice(this.begin_index),a=s.length>=1&&s[s.length-1]>=this.timestamp_begin,o=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a)if(o)n.subarray(this.timestamp_begin).fill(-1/0);else n.subarray(0,this.eos_token_id).fill(-1/0);if(e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){let d=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(d+1).fill(-1/0)}let i=wT(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,f)=>d+f)),c=qe(i.subarray(0,this.timestamp_begin))[0];if(l>c)n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},kC=class extends Ht{constructor(e){super();this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,r=[];for(let s=0;s<t+1-this.no_repeat_ngram_size;++s){let a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[s+o]);r.push(a.map(Number))}let n=new Map;for(let s of r){let a=s.slice(0,s.length-1),o=JSON.stringify(a),i=n.get(o)??[];i.push(s[s.length-1]),n.set(o,i)}return n}getGeneratedNgrams(e,t){let r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;else{let r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data,s=this.calcBannedNgramTokens(e[r]);for(let a of s)n[a]=-1/0}return t}},TC=class extends Ht{constructor(e){super();this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data;for(let s of new Set(e[r])){let a=Number(s);if(n[a]<0)n[a]*=this.penalty;else n[a]/=this.penalty}}return t}},EC=class extends Ht{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){let n=t[r].data;for(let s of this.eos_token_id)n[s]=-1/0}return t}},AC=class extends Ht{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){let s=t[r].data;for(let a of this.eos_token_id)s[a]=-1/0}return t}},CC=class extends Ht{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){let n=t[r].data,s=e[r];for(let a of this.bad_words_ids){if(s.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=s.at(-i)){o=!1;break}if(o)n[a.at(-1)]=-1/0}}return t}},SC=class extends Ht{constructor(e){super();if(e<=1)throw 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 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.`);let r=e.length,n=t.slice([0,r],null),s=t.slice([r,t.dims[0]],null);for(let a=0;a<s.data.length;++a)s.data[a]+=(n.data[a]-s.data[a])*this.guidance_scale;return s}},PC=class extends vC{constructor(e){super();if(typeof e!=="number"||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;if(e===0)t+=" If you're looking for greedy decoding strategies, set `do_sample=false`."}this.temperature=e}_call(e,t){let r=t.data;for(let n=0;n<r.length;++n)r[n]/=this.temperature;return t}};var mg=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,et(e,Object.getOwnPropertyNames(this)))}},gs=class extends mt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},gg=class e extends mt{constructor(){super();this.criteria=[]}push(t){this.criteria.push(t)}extend(t){if(t instanceof e)t=t.criteria;else if(t instanceof gs)t=[t];this.criteria.push(...t)}_call(t,r){let n=Array(t.length).fill(!1);for(let s of this.criteria){let a=s(t,r);for(let o=0;o<n.length;++o)n[o]||=a[o]}return n}[Symbol.iterator](){return this.criteria.values()}},FC=class extends gs{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)}},IC=class extends gs{constructor(e){super();if(!Array.isArray(e))e=[e];this.eos_token_id=e}_call(e,t){return e.map((r)=>{let n=r.at(-1);return this.eos_token_id.some((s)=>n==s)})}},Xz=class extends gs{constructor(){super();this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return Array(e.length).fill(this.interrupted)}},La=class extends mt{constructor(e){super();this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),n=e.data;if(t===-1)n=n.slice(-r);else{let s=t*r;n=n.slice(s,s+r)}return n}randomSelect(e){return tT(e)}static getSampler(e){if(e.do_sample)return new OC(e);else if(e.num_beams>1)return new NC(e);else{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 LC(e)}}},LC=class extends La{async sample(e){let t=qe(e.data)[1];return[[BigInt(t),0]]}},OC=class extends La{async sample(e){let t=e.dims.at(-1);if(this.generation_config.top_k>0)t=Math.min(this.generation_config.top_k,t);let[r,n]=await Pn(e,t),s=st(r.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},NC=class extends La{async sample(e){let t=e.dims.at(-1);if(this.generation_config.top_k>0)t=Math.min(this.generation_config.top_k,t);let[r,n]=await Pn(e,t),s=st(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},DC=class{constructor(e){if(!e)return;for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let r=e[t];if(!(r instanceof U))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw Error("Unable to determine sequence length from the cache.")}update(e){for(let t in e){let r=this[t],n=e[t];if(r&&r!==n&&r.location==="gpu-buffer")r.dispose();this[t]=n}}async dispose(){let e=[];for(let t of Object.values(this))if(t.location==="gpu-buffer")e.push(t.dispose());await Promise.all(e)}},vl=DC,W={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16,MultimodalEncoder:17},fr={[W.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[W.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.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"}},[W.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[W.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[W.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let n={...fr[W.ImageTextToText].text_only_sessions};if(!r)n.vision_encoder="vision_encoder";if(e.is_encoder_decoder)n.model="encoder_model";return n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let n={...fr[W.AudioTextToText].text_only_sessions};if(!r)n.audio_encoder="audio_encoder";return n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let n={...fr[W.ImageAudioTextToText].text_only_sessions};if(!r)n.audio_encoder="audio_encoder",n.vision_encoder="vision_encoder";return n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.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"}},[W.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"}},[W.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[W.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[W.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"}},[W.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let n={...fr[W.VoxtralRealtime].text_only_sessions};if(!r)n.audio_encoder="audio_encoder";return n},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},[W.MultimodalEncoder]:{sessions:(e,t)=>({model:t.model_file_name??"model",...e.vision_config&&{vision_encoder:"vision_encoder"},...e.audio_config&&{audio_encoder:"audio_encoder"}})},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};function zC(e){return fr[e]?.text_only_sessions??null}function BC(e,t,r={}){let n=fr[e]??fr.default;return{sessions:n.sessions(t,r,r.textOnly??!1),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}function wg(e,{warn:t=!0}={}){let r=e.architectures||[];for(let n of r){let s=hr.get(n);if(s!==void 0)return s}if(e.model_type){let n=hr.get(e.model_type);if(n!==void 0)return n;for(let s of Object.values(yn))if(s.has(e.model_type)){let a=hr.get(s.get(e.model_type));if(a!==void 0)return a}}if(t){let n=r.length>0?r.join(", "):"(none)";ce.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${n}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Pa}`)}return W.EncoderOnly}function vg(e,{config:t=null,cache_dir:r=null,local_files_only:n=!1,revision:s="main"}={}){if(t!==null)return fs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s});let a=tl(e,{cache_dir:r,local_files_only:n,revision:s});return lm(a,()=>fs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s}))}async function yg(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await vg(e,{config:t});let a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=n??o.device,d=r??o.dtype,f=wg(t),_=(v,y=null)=>{y=y??v;let b=vm(c,v),k=ym(d,v,b),A=ba[k]??"",E=`${y}${A}.onnx`,C=l?`${l}/${E}`:E;a.push(C);let N=dg(i,E,v);for(let M of fg(E,N)){let G=l?`${l}/${M}`:M;a.push(G)}},{sessions:p,optional_configs:w}=BC(f,t,{model_file_name:s});for(let[v,y]of Object.entries(p))_(v,y);if(w)for(let v of Object.values(w))a.push(v);return a}var yn=null;function RC(e){yn=e}function Ui(e){if(e instanceof U)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some((t)=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new U("int64",BigInt64Array.from(e.flat().map((t)=>BigInt(t))),[e.length,e[0].length])}else return new U("int64",BigInt64Array.from(e.map((t)=>BigInt(t))),[1,e.length])}function bg(e){return new U("bool",[e],[1])}var xp={[W.DecoderOnly]:{can_generate:!0,forward:pr,prepare_inputs:An},[W.DecoderOnlyWithoutHead]:{can_generate:!1,forward:pr,prepare_inputs:An},[W.Seq2Seq]:{can_generate:!0,forward:sa,prepare_inputs:xa},[W.Vision2Seq]:{can_generate:!0,forward:sa,prepare_inputs:xa},[W.Musicgen]:{can_generate:!0,forward:sa},[W.EncoderDecoder]:{can_generate:!1,forward:sa},[W.ImageTextToText]:{can_generate:!0,forward:UC,prepare_inputs:aa},[W.AudioTextToText]:{can_generate:!0,forward:VC,prepare_inputs:aa},[W.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:aa},[W.Phi3V]:{can_generate:!0,prepare_inputs:aa},[W.MultiModality]:{can_generate:!0},[W.AutoEncoder]:{can_generate:!1,forward:$C},[W.Chatterbox]:{can_generate:!0,forward:Lr},[W.VoxtralRealtime]:{can_generate:!0,prepare_inputs:An},default:{can_generate:!1,forward:Lr}};function kp(e,t){let r=hr.get(e),n=!1,s=t?.architectures?.[0];if(s&&s!==e&&e?.endsWith("ForCausalLM")&&s.endsWith("ForConditionalGeneration")){let i=hr.get(s);if(i!==void 0)r=i,n=!0}let a=xp[r]??xp.default,o=fr[r]??fr.default;return{typeConfig:{...a,...o},textOnly:n,modelType:r}}var hr=new Map,yl=new Map,En=new Map,I=class extends mt{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;let n=En.get(this.constructor),{typeConfig:s}=kp(n,e);if(this.can_generate=s.can_generate,this._forward=s.forward,this._prepare_inputs_for_generation=s.prepare_inputs,this.can_generate)this.forward_params.push("past_key_values");this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:f={}}={}){let _={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:f},p=En.get(this);r=_.config=await fs.from_pretrained(e,_);let{typeConfig:w,textOnly:v,modelType:y}=kp(p,r);if(y===void 0){let E=p??r?.model_type;if(E!=="custom")ce.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Pa}.`)}if(t&&!(t instanceof da)){let E={};try{let C=await yg(e,{config:r,dtype:c,device:l,model_file_name:o});(await Promise.all(C.map((M)=>ms(e,M,_)))).forEach((M,G)=>{if(M.exists){let R=C[G]==="config.json";E[C[G]]={loaded:R?M.size??0:0,total:M.size??0}}})}catch(C){ce.warn(`Unable to fetch model file metadata for total progress tracking: ${C}`)}if(Object.keys(E).length>0)_.progress_callback=new da(t,E)}let b=w.sessions(r,_,v),k=[_C(e,b,_,w.cache_sessions)];if(w.optional_configs)k.push(WC(e,w.optional_configs,_));let 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){let n=new Vi;if(e.repetition_penalty!==null&&e.repetition_penalty!==1)n.push(new TC(e.repetition_penalty));if(e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0)n.push(new kC(e.no_repeat_ngram_size));if(e.bad_words_ids!==null)n.push(new CC(e.bad_words_ids,e.eos_token_id));if(e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0)n.push(new EC(e.min_length,e.eos_token_id));if(e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0)n.push(new AC(t,e.min_new_tokens,e.eos_token_id));if(e.forced_bos_token_id!==null)n.push(new yC(e.forced_bos_token_id));if(e.forced_eos_token_id!==null)n.push(new bC(e.max_length,e.forced_eos_token_id));if(e.suppress_tokens!==null)n.push(new MC(e.suppress_tokens));if(e.begin_suppress_tokens!==null){let s=t>1||e.forced_bos_token_id===null?t:t+1;n.push(new pg(e.begin_suppress_tokens,s))}if(e.guidance_scale!==null&&e.guidance_scale>1)n.push(new SC(e.guidance_scale));if(e.temperature===0&&e.do_sample)ce.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;if(e.do_sample){if(e.temperature!==null&&e.temperature!==1)n.push(new PC(e.temperature))}if(r!==null)n.extend(r);return n}_prepare_generation_config(e,t,r=mg){let n={...this.config};for(let a of["decoder","generator","text_config"])if(a in n)Object.assign(n,n[a]);let s=new r(n);if(Object.assign(s,this.generation_config??{}),e)Object.assign(s,e);if(t)Object.assign(s,et(t,Object.getOwnPropertyNames(s)));return s}_get_stopping_criteria(e,t=null){let r=new gg;if(e.max_length!==null)r.push(new FC(e.max_length,this.config.max_position_embeddings??null));if(e.eos_token_id!==null)r.push(new IC(e.eos_token_id));if(t)r.extend(t);return r}_validate_model_class(){if(!this.can_generate){let e=[yn.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,yn.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,yn.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,yn.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=En.get(this.constructor),r=new Set,n=this.config.model_type;for(let a of e){let o=a?.get(n);if(o)r.add(o)}let s=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;if(r.size>0)s+=` Please use the following class instead: ${[...r].join(", ")}`;throw Error(s)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:n}){if(r.past_key_values=ji(t,r.past_key_values),r.input_ids=new U("int64",e.flat(),[e.length,1]),!n)r.attention_mask=Ne([r.attention_mask,gt([r.attention_mask.dims[0],1])],1);else if("decoder_attention_mask"in r)r.decoder_attention_mask=Ne([r.decoder_attention_mask,gt([r.decoder_attention_mask.dims[0],1])],1);return r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){let n=et(r,this.forward_params),s=this.main_input_name;if(s in n){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[s]=e;return{inputs_tensor:n[s],model_inputs:n,model_input_name:s}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:o,attention_mask:i,...l}=t,c=await this._prepare_inputs_embeds(t);t={...l,...et(c,["inputs_embeds","attention_mask"])}}let{last_hidden_state:s}=await Lr(this,t);if(n.guidance_scale!==null&&n.guidance_scale>1){if(s=Ne([s,Bi(s,0)],0),"attention_mask"in t)t.attention_mask=Ne([t.attention_mask,ll(t.attention_mask)],0)}else if(t.decoder_input_ids){let a=Ui(t.decoder_input_ids).dims[0];if(a!==s.dims[0]){if(s.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${s.dims[0]}) than the decoder inputs (${a}).`);s=Ne(Array.from({length:a},()=>s),0)}}return t.encoder_outputs=s,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:n,bos_token_id:s,generation_config:a}){let{decoder_input_ids:o,...i}=r;if(!(o instanceof U)){if(!o)if(n??=s,this.config.model_type==="musicgen")o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw Error(`\`decoder_start_token_id\` expected to have length ${e} but got ${n.length}`);o=n}else o=Array.from({length:e},()=>[n]);else if(!Array.isArray(o[0]))o=Array.from({length:e},()=>o);o=Ui(o)}return i.decoder_attention_mask=il(o),{input_ids:o,model_inputs:i}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,streamer:s=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),c=this.config.is_encoder_decoder;if(!c);else if(!("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;if(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}));else d=i[l];let f=d.dims.at(-1);if(t.max_new_tokens!==null)t.max_length=f+t.max_new_tokens;let _=this._get_logits_processor(t,f,r),p=this._get_stopping_criteria(t,n),w=i[l].dims.at(0),v=La.getSampler(t),y=Array(w).fill(0),b=d.tolist();if(s)s.put(b);let k,A={},E={};while(!0){if(i=this.prepare_inputs_for_generation(b,i,t),k=await this.forward(i),t.return_dict_in_generate){if(t.output_attentions){let H=GC(k);for(let B in H){if(!(B in A))A[B]=[];A[B].push(H[B])}}else if(this._return_dict_in_generate_keys)Object.assign(E,et(k,this._return_dict_in_generate_keys))}let R=k.logits.slice(null,-1,null).to("float32"),q=_(b,R),X=[];for(let H=0;H<q.dims.at(0);++H){let B=q[H],P=await v(B);for(let[Y,ue]of P){let Z=BigInt(Y);y[H]+=ue,b[H].push(Z),X.push([Z]);break}}if(s)s.put(X);if(p(b).every((H)=>H))break;i=this._update_model_kwargs_for_generation({generated_input_ids:X,outputs:k,model_inputs:i,is_encoder_decoder:c})}if(s)s.end();let C=new U("int64",b.flat(),[b.length,b[0].length]),N=ji(k,i.past_key_values),M=new Set(Object.values(N));for(let R of Object.values(k))if(R.location==="gpu-buffer"&&!M.has(R))R.dispose();if(!(("past_key_values"in a)||t.return_dict_in_generate))await N.dispose();if(t.return_dict_in_generate)return{sequences:C,past_key_values:N,...A,...E};return C}async _encode_input(e,t,r){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await ye(n,et(t,n.inputNames)))[r]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function sa(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,decoder_attention_mask:a,...o}=t;if(!r){let i=et(t,e.sessions.model.inputNames);r=(await Lr(e,i)).last_hidden_state}if(o.input_ids=s,o.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask"))o.encoder_attention_mask=t.attention_mask;if(a&&!o.attention_mask)o.attention_mask=a;return await pr(e,o,!0)}async function Lr(e,t){let r=e.sessions.model,n=et(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=ll(n.input_ids)}if(r.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let s=n.pixel_values.dims;n.pixel_mask=gt([s[0],s[2],s[3]])}return await ye(r,n)}async function $C(e,t){let r=await e.encode(t);return await e.decode(r)}function ji(e,t){let r=Object.create(null);for(let n in e)if(n.startsWith("present")){let s=n.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present_compressor","past_compressor").replace("present_indexer","past_indexer").replace("present","past_key_values");if(n.includes("encoder")&&t)r[s]=t[s];else r[s]=e[n]}if(t)return t.update(r),t;return new vl(r)}function GC(e){let t={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)if(n.startsWith(r)){if(!(r in t))t[r]=[];t[r].push(e[n])}return t}function Mg(e,t){return e.map((r)=>{if(typeof r==="number")return r;return t[r]??0})}function bl(e,t,r){if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;let n=e.sessions.decoder_model_merged??e.sessions.model,s=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=Ia(e.config),o=e.config?.normalized_config?.num_heads,i={batch_size:s};if(typeof o==="number")i["batch_size x num_heads"]=s*o;let l=Object.create(null);for(let c of n.inputMetadata){if(!a.has(c.name))continue;let d=Mg(c.shape,i),f=d.reduce((w,v)=>w*v,1),_=us[c.type],p=new U(c.type,new _(f),d);t[c.name]=p,l[c.name]=p}if(r)return r.update(l),r;return new vl(l)}function ws(e,t,r){if(t.num_logits_to_keep)return;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep"))t.num_logits_to_keep=new U("int64",[r],[])}async function pr(e,t,r=!1){let n=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:s,...a}=t;if(n.inputNames.includes("use_cache_branch"))a.use_cache_branch=bg(s!=null&&Object.keys(s).length>0);if(n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=jC(a,s,i)}ws(e,a,0n),bl(e,a,s);let o=et(a,n.inputNames);return await ye(n,o)}async function xg(e,{encode_function:t,merge_function:r,modality_input_names:n,modality_output_name:s,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:f=null,num_logits_to_keep:_=null,...p}){if(!l){l=await e.encode_text({input_ids:a,...p});let v=et(p,n);if(Object.keys(v).length>0){if(a.dims[1]!==1){let y=await t({...v,...p});({inputs_embeds:l,attention_mask:o}=r({[s]:y,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){let y=a.dims[1],b=c.get_seq_length();o=Ne([gt([a.dims[0],b]),o.slice(null,[o.dims[1]-y,o.dims[1]])],1)}}}if(!i){if(["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)){let{image_grid_thw:v,video_grid_thw:y}=p;[i]=e.get_rope_index(a,v,y,o)}}return await pr(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:f,num_logits_to_keep:_},!0)}async function VC(e,t){return await xg(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 UC(e,t){return await xg(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 kg(e,t=0){let[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;o<r;++o){let i=o*n,l=BigInt(t);for(let c=0;c<n;++c){let d=i+c;if(s[d]===0n)a[d]=BigInt(1);else a[d]=l,l+=s[d]}}return{data:a,dims:e.dims}}function jC(e,t=null,r=0){let{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=kg(a,r),l=new U("int64",o,i);if(t){let c=-(n??s).dims.at(1);l=l.slice(null,[c,null])}return l}function An(e,t,r,n){let s=r.past_key_values?r.past_key_values.get_seq_length():0;if(ws(e,r,1n),!r.attention_mask){let a;for(let o of["input_ids","inputs_embeds","position_ids"])if(r[o]){a=r[o].dims;break}if(!a)throw Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=gt([a[0],s+a[1]])}if(r.past_key_values){let{input_ids:a,attention_mask:o}=r;if(o&&o.dims[1]>a.dims[1]);else if(s<a.dims[1])r.input_ids=a.slice(null,[s,null])}return r}function xa(e,t,r,n){if(r.past_key_values)t=t.map((s)=>[s.at(-1)]);return ws(e,r,1n),{...r,decoder_input_ids:Ui(t)}}function aa(e,...t){if(e.config.is_encoder_decoder)return xa(e,...t);else return An(e,...t)}function Tg({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){let a=n.tolist().map((c)=>c.reduce((d,f,_)=>{if(f==e)d.push(_);return d},[])),o=a.reduce((c,d)=>c+d.length,0),i=r.dims[0];if(o!==i)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){let d=a[c],f=t[c];for(let _=0;_<d.length;++_)f[d[_]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function Ml({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return Tg({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function Eg({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:n,attention_mask:s}){return Tg({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}async function WC(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async(n)=>{let s=await ar(e,t[n],!1,r);return[n,s]})))}var xl={};hs(xl,{ASTForAudioClassification:()=>nS,ASTModel:()=>rS,ASTPreTrainedModel:()=>Al,AfmoeForCausalLM:()=>ZC,AfmoeModel:()=>JC,AfmoePreTrainedModel:()=>Tl,AlbertForMaskedLM:()=>XC,AlbertForQuestionAnswering:()=>QC,AlbertForSequenceClassification:()=>HC,AlbertModel:()=>qC,AlbertPreTrainedModel:()=>vs,ApertusForCausalLM:()=>KC,ApertusModel:()=>YC,ApertusPreTrainedModel:()=>kl,ArceeForCausalLM:()=>tS,ArceeModel:()=>eS,ArceePreTrainedModel:()=>El,BartForConditionalGeneration:()=>aS,BartForSequenceClassification:()=>oS,BartModel:()=>sS,BartPretrainedModel:()=>Oa,BaseModelOutput:()=>mC,BeitForImageClassification:()=>lS,BeitModel:()=>iS,BeitPreTrainedModel:()=>Cl,BertForMaskedLM:()=>uS,BertForQuestionAnswering:()=>hS,BertForSequenceClassification:()=>dS,BertForTokenClassification:()=>fS,BertModel:()=>cS,BertPreTrainedModel:()=>Fn,BlenderbotForConditionalGeneration:()=>pS,BlenderbotModel:()=>_S,BlenderbotPreTrainedModel:()=>Sl,BlenderbotSmallForConditionalGeneration:()=>gS,BlenderbotSmallModel:()=>mS,BlenderbotSmallPreTrainedModel:()=>Pl,BloomForCausalLM:()=>vS,BloomModel:()=>wS,BloomPreTrainedModel:()=>Fl,CHMv2ForDepthEstimation:()=>AS,CHMv2PreTrainedModel:()=>Pg,CLIPModel:()=>SS,CLIPPreTrainedModel:()=>nn,CLIPSegForImageSegmentation:()=>OS,CLIPSegModel:()=>LS,CLIPSegPreTrainedModel:()=>Il,CLIPTextModel:()=>PS,CLIPTextModelWithProjection:()=>Lg,CLIPVisionModel:()=>FS,CLIPVisionModelWithProjection:()=>IS,CamembertForMaskedLM:()=>bS,CamembertForQuestionAnswering:()=>kS,CamembertForSequenceClassification:()=>MS,CamembertForTokenClassification:()=>xS,CamembertModel:()=>yS,CamembertPreTrainedModel:()=>In,CausalLMOutput:()=>Or,CausalLMOutputWithPast:()=>gC,ChatterboxModel:()=>Cg,ChatterboxPreTrainedModel:()=>Ag,ChineseCLIPModel:()=>ES,ChineseCLIPPreTrainedModel:()=>Sg,ClapAudioModelWithProjection:()=>Ig,ClapModel:()=>CS,ClapPreTrainedModel:()=>Na,ClapTextModelWithProjection:()=>Fg,CodeGenForCausalLM:()=>DS,CodeGenModel:()=>NS,CodeGenPreTrainedModel:()=>Ll,Cohere2ForCausalLM:()=>$S,Cohere2Model:()=>RS,Cohere2PreTrainedModel:()=>Nl,CohereAsrForConditionalGeneration:()=>VS,CohereAsrModel:()=>GS,CohereAsrPreTrainedModel:()=>Dl,CohereForCausalLM:()=>BS,CohereModel:()=>zS,CoherePreTrainedModel:()=>Ol,ConvBertForMaskedLM:()=>jS,ConvBertForQuestionAnswering:()=>HS,ConvBertForSequenceClassification:()=>WS,ConvBertForTokenClassification:()=>qS,ConvBertModel:()=>US,ConvBertPreTrainedModel:()=>Ln,ConvNextForImageClassification:()=>XS,ConvNextModel:()=>QS,ConvNextPreTrainedModel:()=>zl,ConvNextV2ForImageClassification:()=>KS,ConvNextV2Model:()=>YS,ConvNextV2PreTrainedModel:()=>Bl,DFineForObjectDetection:()=>tP,DFineModel:()=>eP,DFinePreTrainedModel:()=>$l,DINOv3ConvNextModel:()=>SP,DINOv3ConvNextPreTrainedModel:()=>Vg,DINOv3ViTModel:()=>PP,DINOv3ViTPreTrainedModel:()=>Ug,DPTForDepthEstimation:()=>BP,DPTModel:()=>zP,DPTPreTrainedModel:()=>Hl,DacDecoderModel:()=>zg,DacDecoderOutput:()=>Ng,DacEncoderModel:()=>Dg,DacEncoderOutput:()=>Og,DacModel:()=>rP,DacPreTrainedModel:()=>Da,DebertaForMaskedLM:()=>sP,DebertaForQuestionAnswering:()=>iP,DebertaForSequenceClassification:()=>aP,DebertaForTokenClassification:()=>oP,DebertaModel:()=>nP,DebertaPreTrainedModel:()=>On,DebertaV2ForMaskedLM:()=>hP,DebertaV2ForQuestionAnswering:()=>mP,DebertaV2ForSequenceClassification:()=>_P,DebertaV2ForTokenClassification:()=>pP,DebertaV2Model:()=>fP,DebertaV2PreTrainedModel:()=>Nn,DecisionTransformerModel:()=>gP,DecisionTransformerPreTrainedModel:()=>Bg,DeepseekV3ForCausalLM:()=>cP,DeepseekV3Model:()=>lP,DeepseekV3PreTrainedModel:()=>Gl,DeepseekV4ForCausalLM:()=>dP,DeepseekV4Model:()=>uP,DeepseekV4PreTrainedModel:()=>Vl,DeiTForImageClassification:()=>vP,DeiTModel:()=>wP,DeiTPreTrainedModel:()=>Ul,DepthAnythingForDepthEstimation:()=>yP,DepthAnythingPreTrainedModel:()=>Rg,DepthProForDepthEstimation:()=>bP,DepthProPreTrainedModel:()=>$g,DetrForObjectDetection:()=>xP,DetrForSegmentation:()=>kP,DetrModel:()=>MP,DetrObjectDetectionOutput:()=>jl,DetrPreTrainedModel:()=>za,DetrSegmentationOutput:()=>Gg,Dinov2ForImageClassification:()=>EP,Dinov2Model:()=>TP,Dinov2PreTrainedModel:()=>Wl,Dinov2WithRegistersForImageClassification:()=>CP,Dinov2WithRegistersModel:()=>AP,Dinov2WithRegistersPreTrainedModel:()=>ql,DistilBertForMaskedLM:()=>NP,DistilBertForQuestionAnswering:()=>OP,DistilBertForSequenceClassification:()=>IP,DistilBertForTokenClassification:()=>LP,DistilBertModel:()=>FP,DistilBertPreTrainedModel:()=>Dn,DonutSwinModel:()=>DP,DonutSwinPreTrainedModel:()=>jg,EdgeTamModel:()=>aN,EfficientNetForImageClassification:()=>$P,EfficientNetModel:()=>RP,EfficientNetPreTrainedModel:()=>Ql,ElectraForMaskedLM:()=>VP,ElectraForQuestionAnswering:()=>WP,ElectraForSequenceClassification:()=>UP,ElectraForTokenClassification:()=>jP,ElectraModel:()=>GP,ElectraPreTrainedModel:()=>zn,EmbeddingGemma2Model:()=>qg,EmbeddingGemma2PreTrainedModel:()=>Wg,Ernie4_5ForCausalLM:()=>HP,Ernie4_5Model:()=>qP,Ernie4_5PretrainedModel:()=>Xl,EsmForMaskedLM:()=>XP,EsmForSequenceClassification:()=>YP,EsmForTokenClassification:()=>KP,EsmModel:()=>QP,EsmPreTrainedModel:()=>bs,EuroBertForMaskedLM:()=>ZP,EuroBertForSequenceClassification:()=>eF,EuroBertForTokenClassification:()=>tF,EuroBertModel:()=>JP,EuroBertPreTrainedModel:()=>Ms,ExaoneForCausalLM:()=>nF,ExaoneModel:()=>rF,ExaonePreTrainedModel:()=>Yl,FalconForCausalLM:()=>aF,FalconH1ForCausalLM:()=>iF,FalconH1Model:()=>oF,FalconH1PreTrainedModel:()=>Jl,FalconModel:()=>sF,FalconPreTrainedModel:()=>Kl,FastViTForImageClassification:()=>cF,FastViTModel:()=>lF,FastViTPreTrainedModel:()=>Zl,Florence2ForConditionalGeneration:()=>uF,Florence2PreTrainedModel:()=>Hg,GLPNForDepthEstimation:()=>AF,GLPNModel:()=>EF,GLPNPreTrainedModel:()=>ic,GPT2LMHeadModel:()=>zF,GPT2Model:()=>DF,GPT2PreTrainedModel:()=>fc,GPTBigCodeForCausalLM:()=>SF,GPTBigCodeModel:()=>CF,GPTBigCodePreTrainedModel:()=>lc,GPTJForCausalLM:()=>RF,GPTJModel:()=>BF,GPTJPreTrainedModel:()=>hc,GPTNeoForCausalLM:()=>FF,GPTNeoModel:()=>PF,GPTNeoPreTrainedModel:()=>cc,GPTNeoXForCausalLM:()=>LF,GPTNeoXModel:()=>IF,GPTNeoXPreTrainedModel:()=>uc,Gemma2ForCausalLM:()=>_F,Gemma2Model:()=>hF,Gemma2PreTrainedModel:()=>tc,Gemma3ForCausalLM:()=>wF,Gemma3ForConditionalGeneration:()=>Yg,Gemma3Model:()=>gF,Gemma3PreTrainedModel:()=>Xg,Gemma3nForCausalLM:()=>vF,Gemma3nForConditionalGeneration:()=>Ba,Gemma3nPreTrainedModel:()=>Kg,Gemma4ForCausalLM:()=>yF,Gemma4ForConditionalGeneration:()=>rc,GemmaForCausalLM:()=>fF,GemmaModel:()=>dF,GemmaPreTrainedModel:()=>ec,GlmForCausalLM:()=>MF,GlmModel:()=>bF,GlmMoeDsaForCausalLM:()=>kF,GlmMoeDsaModel:()=>xF,GlmMoeDsaPreTrainedModel:()=>sc,GlmOcrForConditionalGeneration:()=>TF,GlmPreTrainedModel:()=>nc,GptOssForCausalLM:()=>NF,GptOssModel:()=>OF,GptOssPreTrainedModel:()=>dc,GraniteForCausalLM:()=>GF,GraniteModel:()=>$F,GraniteMoeHybridForCausalLM:()=>UF,GraniteMoeHybridModel:()=>VF,GraniteMoeHybridPreTrainedModel:()=>pc,GranitePreTrainedModel:()=>_c,GraniteSpeechForConditionalGeneration:()=>jF,GroundingDinoForObjectDetection:()=>WF,GroundingDinoPreTrainedModel:()=>rw,GroupViTModel:()=>qF,GroupViTPreTrainedModel:()=>nw,HeliumForCausalLM:()=>QF,HeliumModel:()=>HF,HeliumPreTrainedModel:()=>gc,HieraForImageClassification:()=>YF,HieraModel:()=>XF,HieraPreTrainedModel:()=>wc,HrmTextForCausalLM:()=>JF,HrmTextModel:()=>KF,HrmTextPreTrainedModel:()=>vc,HubertForCTC:()=>aI,HubertForSequenceClassification:()=>oI,HubertModel:()=>sI,HubertPreTrainedModel:()=>nI,HunYuanDenseV1ForCausalLM:()=>lI,HunYuanDenseV1Model:()=>iI,HunYuanDenseV1PreTrainedModel:()=>yc,IJepaForImageClassification:()=>uI,IJepaModel:()=>cI,IJepaPreTrainedModel:()=>bc,Idefics3ForConditionalGeneration:()=>sw,ImageMattingOutput:()=>_g,JAISLMHeadModel:()=>fI,JAISModel:()=>dI,JAISPreTrainedModel:()=>Mc,JinaCLIPModel:()=>hI,JinaCLIPPreTrainedModel:()=>Ra,JinaCLIPTextModel:()=>aw,JinaCLIPVisionModel:()=>_I,Lfm2ForCausalLM:()=>mI,Lfm2Model:()=>pI,Lfm2MoeForCausalLM:()=>vI,Lfm2MoeModel:()=>wI,Lfm2MoePreTrainedModel:()=>kc,Lfm2PreTrainedModel:()=>xc,Lfm2VlForConditionalGeneration:()=>yI,Lfm3ForCausalLM:()=>MI,Lfm3Model:()=>bI,Lfm3PreTrainedModel:()=>Tc,Lfm3VlForConditionalGeneration:()=>xI,LightOnOcrForConditionalGeneration:()=>gI,LiteWhisperForConditionalGeneration:()=>E3,Llama4ForCausalLM:()=>EI,Llama4PreTrainedModel:()=>ow,LlamaForCausalLM:()=>TI,LlamaModel:()=>kI,LlamaPreTrainedModel:()=>Ec,LlavaForConditionalGeneration:()=>Ut,LlavaOnevisionForConditionalGeneration:()=>Ut,LlavaPreTrainedModel:()=>Qg,LlavaQwen2ForCausalLM:()=>mF,LongT5ForConditionalGeneration:()=>CI,LongT5Model:()=>AI,LongT5PreTrainedModel:()=>Ac,M2M100ForConditionalGeneration:()=>PI,M2M100Model:()=>SI,M2M100PreTrainedModel:()=>Cc,MBartForCausalLM:()=>BI,MBartForConditionalGeneration:()=>DI,MBartForSequenceClassification:()=>zI,MBartModel:()=>NI,MBartPreTrainedModel:()=>xs,MPNetForMaskedLM:()=>SL,MPNetForQuestionAnswering:()=>IL,MPNetForSequenceClassification:()=>PL,MPNetForTokenClassification:()=>FL,MPNetModel:()=>CL,MPNetPreTrainedModel:()=>Bn,MT5ForConditionalGeneration:()=>DL,MT5Model:()=>NL,MT5PreTrainedModel:()=>Gc,MarianMTModel:()=>II,MarianModel:()=>FI,MarianPreTrainedModel:()=>Sc,MaskFormerForInstanceSegmentation:()=>OI,MaskFormerModel:()=>LI,MaskFormerPreTrainedModel:()=>Pc,MaskedLMOutput:()=>Xe,Metric3DForDepthEstimation:()=>RI,Metric3DPreTrainedModel:()=>iw,Metric3Dv2ForDepthEstimation:()=>$I,Metric3Dv2PreTrainedModel:()=>lw,MgpstrForSceneTextRecognition:()=>GI,MgpstrModelOutput:()=>cw,MgpstrPreTrainedModel:()=>uw,MimiDecoderModel:()=>_w,MimiDecoderOutput:()=>fw,MimiEncoderModel:()=>hw,MimiEncoderOutput:()=>dw,MimiModel:()=>VI,MimiPreTrainedModel:()=>$a,Ministral3ForCausalLM:()=>qI,Ministral3Model:()=>WI,Ministral3PreTrainedModel:()=>Ic,MinistralForCausalLM:()=>jI,MinistralModel:()=>UI,MinistralPreTrainedModel:()=>Fc,Mistral3ForConditionalGeneration:()=>XI,Mistral4ForCausalLM:()=>KI,Mistral4Model:()=>YI,Mistral4PreTrainedModel:()=>Oc,MistralForCausalLM:()=>QI,MistralModel:()=>HI,MistralPreTrainedModel:()=>Lc,MobileBertForMaskedLM:()=>ZI,MobileBertForQuestionAnswering:()=>tL,MobileBertForSequenceClassification:()=>eL,MobileBertModel:()=>JI,MobileBertPreTrainedModel:()=>ks,MobileLLMForCausalLM:()=>nL,MobileLLMModel:()=>rL,MobileLLMPreTrainedModel:()=>Nc,MobileNetV1ForImageClassification:()=>aL,MobileNetV1ForSemanticSegmentation:()=>oL,MobileNetV1Model:()=>sL,MobileNetV1PreTrainedModel:()=>Ga,MobileNetV2ForImageClassification:()=>lL,MobileNetV2ForSemanticSegmentation:()=>cL,MobileNetV2Model:()=>iL,MobileNetV2PreTrainedModel:()=>Va,MobileNetV3ForImageClassification:()=>dL,MobileNetV3ForSemanticSegmentation:()=>fL,MobileNetV3Model:()=>uL,MobileNetV3PreTrainedModel:()=>Ua,MobileNetV4ForImageClassification:()=>_L,MobileNetV4ForSemanticSegmentation:()=>pL,MobileNetV4Model:()=>hL,MobileNetV4PreTrainedModel:()=>ja,MobileViTForImageClassification:()=>gL,MobileViTModel:()=>mL,MobileViTPreTrainedModel:()=>Dc,MobileViTV2ForImageClassification:()=>vL,MobileViTV2Model:()=>wL,MobileViTV2PreTrainedModel:()=>zc,ModelOutput:()=>Ue,ModernBertDecoderForCausalLM:()=>TL,ModernBertDecoderModel:()=>kL,ModernBertDecoderPreTrainedModel:()=>Bc,ModernBertForMaskedLM:()=>bL,ModernBertForSequenceClassification:()=>ML,ModernBertForTokenClassification:()=>xL,ModernBertModel:()=>yL,ModernBertPreTrainedModel:()=>Ts,Moondream1ForConditionalGeneration:()=>pF,MoonshineForConditionalGeneration:()=>AL,MoonshineModel:()=>EL,MoonshinePreTrainedModel:()=>Rc,MptForCausalLM:()=>OL,MptModel:()=>LL,MptPreTrainedModel:()=>$c,MultiModalityCausalLM:()=>zL,MultiModalityPreTrainedModel:()=>pw,MusicgenForCausalLM:()=>RL,MusicgenForConditionalGeneration:()=>mw,MusicgenModel:()=>BL,MusicgenPreTrainedModel:()=>Vc,NanoChatForCausalLM:()=>GL,NanoChatModel:()=>$L,NanoChatPreTrainedModel:()=>Uc,NemotronHForCausalLM:()=>UL,NemotronHModel:()=>VL,NemotronHPreTrainedModel:()=>jc,NeoBertForMaskedLM:()=>WL,NeoBertForQuestionAnswering:()=>QL,NeoBertForSequenceClassification:()=>qL,NeoBertForTokenClassification:()=>HL,NeoBertModel:()=>jL,NeoBertPreTrainedModel:()=>Rn,NomicBertModel:()=>XL,NomicBertPreTrainedModel:()=>gw,OPTForCausalLM:()=>cO,OPTModel:()=>lO,OPTPreTrainedModel:()=>Kc,Olmo2ForCausalLM:()=>ZL,Olmo2Model:()=>JL,Olmo2PreTrainedModel:()=>qc,Olmo3ForCausalLM:()=>tO,Olmo3Model:()=>eO,Olmo3PreTrainedModel:()=>Hc,OlmoForCausalLM:()=>KL,OlmoHybridForCausalLM:()=>nO,OlmoHybridModel:()=>rO,OlmoHybridPreTrainedModel:()=>Qc,OlmoModel:()=>YL,OlmoPreTrainedModel:()=>Wc,OpenAIPrivacyFilterForTokenClassification:()=>aO,OpenAIPrivacyFilterModel:()=>sO,OpenAIPrivacyFilterPreTrainedModel:()=>Xc,OpenELMForCausalLM:()=>iO,OpenELMModel:()=>oO,OpenELMPreTrainedModel:()=>Yc,OwlViTForObjectDetection:()=>hO,OwlViTModel:()=>fO,OwlViTPreTrainedModel:()=>Zc,Owlv2ForObjectDetection:()=>dO,Owlv2Model:()=>uO,Owlv2PreTrainedModel:()=>Jc,PaliGemmaForConditionalGeneration:()=>_O,ParakeetForCTC:()=>pO,ParakeetPreTrainedModel:()=>ww,PatchTSMixerForPrediction:()=>gO,PatchTSMixerModel:()=>mO,PatchTSMixerPreTrainedModel:()=>eu,PatchTSTForPrediction:()=>vO,PatchTSTModel:()=>wO,PatchTSTPreTrainedModel:()=>tu,Phi3ForCausalLM:()=>xO,Phi3Model:()=>MO,Phi3PreTrainedModel:()=>nu,Phi3VForCausalLM:()=>yw,Phi3VPreTrainedModel:()=>vw,PhiForCausalLM:()=>bO,PhiModel:()=>yO,PhiPreTrainedModel:()=>ru,PreTrainedModel:()=>I,PvtForImageClassification:()=>TO,PvtModel:()=>kO,PvtPreTrainedModel:()=>su,PyAnnoteForAudioFrameClassification:()=>AO,PyAnnoteModel:()=>EO,PyAnnotePreTrainedModel:()=>au,QuestionAnsweringModelOutput:()=>it,Qwen2ForCausalLM:()=>SO,Qwen2Model:()=>CO,Qwen2MoeForCausalLM:()=>FO,Qwen2MoeModel:()=>PO,Qwen2MoePreTrainedModel:()=>iu,Qwen2PreTrainedModel:()=>ou,Qwen2VLForCausalLM:()=>Zg,Qwen2VLForConditionalGeneration:()=>ac,Qwen2VLPreTrainedModel:()=>Jg,Qwen2_5_VLForCausalLM:()=>ew,Qwen2_5_VLForConditionalGeneration:()=>oc,Qwen3ForCausalLM:()=>LO,Qwen3Model:()=>IO,Qwen3MoeForCausalLM:()=>NO,Qwen3MoeModel:()=>OO,Qwen3MoePreTrainedModel:()=>cu,Qwen3NextForCausalLM:()=>zO,Qwen3NextModel:()=>DO,Qwen3NextPreTrainedModel:()=>uu,Qwen3PreTrainedModel:()=>lu,Qwen3VLForCausalLM:()=>bw,Qwen3VLForConditionalGeneration:()=>du,Qwen3VLMoeForCausalLM:()=>RO,Qwen3VLMoeForConditionalGeneration:()=>BO,Qwen3_5ForCausalLM:()=>Mw,Qwen3_5ForConditionalGeneration:()=>fu,Qwen3_5MoeForCausalLM:()=>GO,Qwen3_5MoeForConditionalGeneration:()=>$O,RFDetrForObjectDetection:()=>WO,RFDetrModel:()=>jO,RFDetrObjectDetectionOutput:()=>xw,RFDetrPreTrainedModel:()=>_u,RTDetrForObjectDetection:()=>ZS,RTDetrModel:()=>JS,RTDetrObjectDetectionOutput:()=>ys,RTDetrPreTrainedModel:()=>Rl,RTDetrV2ForObjectDetection:()=>nN,RTDetrV2Model:()=>rN,RTDetrV2ObjectDetectionOutput:()=>kw,RTDetrV2PreTrainedModel:()=>pu,ResNetForImageClassification:()=>UO,ResNetModel:()=>VO,ResNetPreTrainedModel:()=>hu,RoFormerForMaskedLM:()=>JO,RoFormerForQuestionAnswering:()=>tN,RoFormerForSequenceClassification:()=>ZO,RoFormerForTokenClassification:()=>eN,RoFormerModel:()=>KO,RoFormerPreTrainedModel:()=>Gn,RobertaForMaskedLM:()=>HO,RobertaForQuestionAnswering:()=>YO,RobertaForSequenceClassification:()=>QO,RobertaForTokenClassification:()=>XO,RobertaModel:()=>qO,RobertaPreTrainedModel:()=>$n,Sam2ImageSegmentationOutput:()=>Aw,Sam2Model:()=>mu,Sam2PreTrainedModel:()=>Cw,Sam3TrackerModel:()=>oN,SamImageSegmentationOutput:()=>Tw,SamModel:()=>sN,SamPreTrainedModel:()=>Ew,SapiensForDepthEstimation:()=>lN,SapiensForNormalEstimation:()=>cN,SapiensForSemanticSegmentation:()=>iN,SapiensPreTrainedModel:()=>Wa,SegformerForImageClassification:()=>dN,SegformerForSemanticSegmentation:()=>fN,SegformerModel:()=>uN,SegformerPreTrainedModel:()=>qa,Seq2SeqLMOutput:()=>wC,SequenceClassifierOutput:()=>oe,SiglipModel:()=>hN,SiglipPreTrainedModel:()=>gu,SiglipTextModel:()=>Sw,SiglipVisionModel:()=>_N,SmolLM3ForCausalLM:()=>mN,SmolLM3Model:()=>pN,SmolLM3PreTrainedModel:()=>wu,SmolVLMForConditionalGeneration:()=>gN,SnacDecoderModel:()=>Fw,SnacEncoderModel:()=>Pw,SnacModel:()=>wN,SnacPreTrainedModel:()=>Ha,SolarOpenForCausalLM:()=>yN,SolarOpenModel:()=>vN,SolarOpenPreTrainedModel:()=>vu,SpeechT5ForSpeechToText:()=>MN,SpeechT5ForTextToSpeech:()=>xN,SpeechT5HifiGan:()=>kN,SpeechT5Model:()=>bN,SpeechT5PreTrainedModel:()=>Qa,SqueezeBertForMaskedLM:()=>EN,SqueezeBertForQuestionAnswering:()=>CN,SqueezeBertForSequenceClassification:()=>AN,SqueezeBertModel:()=>TN,SqueezeBertPreTrainedModel:()=>Es,StableLmForCausalLM:()=>PN,StableLmModel:()=>SN,StableLmPreTrainedModel:()=>yu,Starcoder2ForCausalLM:()=>IN,Starcoder2Model:()=>FN,Starcoder2PreTrainedModel:()=>bu,StyleTextToSpeech2Model:()=>LN,StyleTextToSpeech2PreTrainedModel:()=>Iw,SupertonicForConditionalGeneration:()=>Ow,SupertonicPreTrainedModel:()=>Lw,Swin2SRForImageSuperResolution:()=>BN,Swin2SRModel:()=>zN,Swin2SRPreTrainedModel:()=>Mu,SwinForImageClassification:()=>NN,SwinForSemanticSegmentation:()=>DN,SwinModel:()=>ON,SwinPreTrainedModel:()=>Xa,T5ForConditionalGeneration:()=>$N,T5Model:()=>RN,T5PreTrainedModel:()=>xu,TableTransformerForObjectDetection:()=>VN,TableTransformerModel:()=>GN,TableTransformerObjectDetectionOutput:()=>Nw,TableTransformerPreTrainedModel:()=>ku,TokenClassifierOutput:()=>He,TrOCRForCausalLM:()=>UN,TrOCRPreTrainedModel:()=>Dw,UltravoxModel:()=>mc,UltravoxPreTrainedModel:()=>tw,UniSpeechForCTC:()=>WN,UniSpeechForSequenceClassification:()=>qN,UniSpeechModel:()=>jN,UniSpeechPreTrainedModel:()=>Ya,UniSpeechSatForAudioFrameClassification:()=>YN,UniSpeechSatForCTC:()=>QN,UniSpeechSatForSequenceClassification:()=>XN,UniSpeechSatModel:()=>HN,UniSpeechSatPreTrainedModel:()=>As,VaultGemmaForCausalLM:()=>JN,VaultGemmaModel:()=>KN,VaultGemmaPreTrainedModel:()=>Tu,ViTForImageClassification:()=>t3,ViTMAEModel:()=>r3,ViTMAEPreTrainedModel:()=>zw,ViTMSNForImageClassification:()=>s3,ViTMSNModel:()=>n3,ViTMSNPreTrainedModel:()=>Au,ViTModel:()=>e3,ViTPreTrainedModel:()=>Eu,VisionEncoderDecoderModel:()=>ZN,VitMatteForImageMatting:()=>a3,VitMattePreTrainedModel:()=>Bw,VitPoseForPoseEstimation:()=>o3,VitPosePreTrainedModel:()=>Rw,VitsModel:()=>i3,VitsModelOutput:()=>$w,VitsPreTrainedModel:()=>Gw,VoxtralForConditionalGeneration:()=>l3,VoxtralRealtimeForConditionalGeneration:()=>Uw,VoxtralRealtimePreTrainedModel:()=>Vw,Wav2Vec2BertForCTC:()=>m3,Wav2Vec2BertForSequenceClassification:()=>g3,Wav2Vec2BertModel:()=>p3,Wav2Vec2BertPreTrainedModel:()=>Ka,Wav2Vec2ForAudioFrameClassification:()=>rI,Wav2Vec2ForCTC:()=>eI,Wav2Vec2ForSequenceClassification:()=>tI,Wav2Vec2Model:()=>ZF,Wav2Vec2PreTrainedModel:()=>Nr,WavLMForAudioFrameClassification:()=>M3,WavLMForCTC:()=>v3,WavLMForSequenceClassification:()=>y3,WavLMForXVector:()=>b3,WavLMModel:()=>w3,WavLMPreTrainedModel:()=>Vn,WeSpeakerResNetModel:()=>x3,WeSpeakerResNetPreTrainedModel:()=>Ww,WhisperForConditionalGeneration:()=>qw,WhisperModel:()=>T3,WhisperPreTrainedModel:()=>Cu,XLMForQuestionAnswering:()=>F3,XLMForSequenceClassification:()=>S3,XLMForTokenClassification:()=>P3,XLMModel:()=>A3,XLMPreTrainedModel:()=>Un,XLMRobertaForMaskedLM:()=>L3,XLMRobertaForQuestionAnswering:()=>D3,XLMRobertaForSequenceClassification:()=>O3,XLMRobertaForTokenClassification:()=>N3,XLMRobertaModel:()=>I3,XLMRobertaPreTrainedModel:()=>jn,XLMWithLMHeadModel:()=>C3,XVectorOutput:()=>jw,YolosForObjectDetection:()=>B3,YolosModel:()=>z3,YolosObjectDetectionOutput:()=>Hw,YolosPreTrainedModel:()=>Su,YoutuForCausalLM:()=>$3,YoutuModel:()=>R3,YoutuPreTrainedModel:()=>Pu,ZayaForCausalLM:()=>V3,ZayaModel:()=>G3,ZayaPreTrainedModel:()=>Fu});var vs=class extends I{},qC=class extends vs{},HC=class extends vs{async _call(e){return new oe(await super._call(e))}},QC=class extends vs{async _call(e){return new it(await super._call(e))}},XC=class extends vs{async _call(e){return new Xe(await super._call(e))}},kl=class extends I{},YC=class extends kl{},KC=class extends kl{},Tl=class extends I{},JC=class extends Tl{},ZC=class extends Tl{},El=class extends I{},eS=class extends El{},tS=class extends El{},Al=class extends I{},rS=class extends Al{},nS=class extends Al{},Oa=class extends I{},sS=class extends Oa{},aS=class extends Oa{},oS=class extends Oa{async _call(e){return new oe(await super._call(e))}},Cl=class extends I{},iS=class extends Cl{},lS=class extends Cl{async _call(e){return new oe(await super._call(e))}},Fn=class extends I{},cS=class extends Fn{},uS=class extends Fn{async _call(e){return new Xe(await super._call(e))}},dS=class extends Fn{async _call(e){return new oe(await super._call(e))}},fS=class extends Fn{async _call(e){return new He(await super._call(e))}},hS=class extends Fn{async _call(e){return new it(await super._call(e))}},Sl=class extends I{},_S=class extends Sl{},pS=class extends Sl{},Pl=class extends I{},mS=class extends Pl{},gS=class extends Pl{},Fl=class extends I{},wS=class extends Fl{},vS=class extends Fl{},In=class extends I{},yS=class extends In{},bS=class extends In{async _call(e){return new Xe(await super._call(e))}},MS=class extends In{async _call(e){return new oe(await super._call(e))}},xS=class extends In{async _call(e){return new He(await super._call(e))}},kS=class extends In{async _call(e){return new it(await super._call(e))}},TS=4299n,Tp=6561n,Ag=class extends I{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"]},Cg=class extends Ag{async encode_speech(e){return ye(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,num_logits_to_keep:c=null,audio_features:d=null,audio_tokens:f=null,speaker_embeddings:_=null,speaker_features:p=null,...w}){let v;if(!a){let b=this.sessions.embed_tokens.inputNames,k={input_ids:e};if(b.includes("exaggeration")){if(!(n instanceof U)){let A=e.dims[0];if(n==null)n=dt([A],0.5);else if(typeof n==="number")n=dt([A],n);else if(Array.isArray(n))n=new U("float32",n,[A]);else throw Error("Unsupported type for `exaggeration` input")}k.exaggeration=n}if(b.includes("position_ids"))k.position_ids=s;if({inputs_embeds:a}=await ye(this.sessions.embed_tokens,k),d&&f&&_&&p)v={audio_features:d,audio_tokens:f,speaker_embeddings:_,speaker_features:p};if(v||r)v??=await this.encode_speech(r),a=Ne([v.audio_features,a],1),t=gt([a.dims[0],a.dims[1]]);else{let A=a.dims[1];if(!o||A!==1)throw Error("Incorrect state encountered during generation.");let E=o.get_seq_length();t=gt([a.dims[0],E+A])}}return{...await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1),...v}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){let n=Array.from({length:e.length},(s,a)=>e[a].length-e[a].findLastIndex((o)=>o==Tp)-1);t.position_ids=new U("int64",n,[e.length,1])}else{let s=t.input_ids.tolist().map((a)=>{let o=0;return a.map((i)=>i>=Tp?0:o++)});t.position_ids=new U("int64",s.flat(),t.input_ids.dims)}if(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;return An(this,e,t,r)}async generate(e){let t=e.past_key_values,{sequences:r,audio_tokens:n,speaker_embeddings:s,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{let i=r.slice(null,[e.input_ids.dims[1],-1]),l=dt([i.dims[0],3],TS),c=Ne([n,i,l],1),{waveform:d}=await ye(this.sessions.conditional_decoder,{speech_tokens:c,speaker_features:a,speaker_embeddings:s});return d}finally{if(o!==t)await o?.dispose()}}},Sg=class extends I{},ES=class extends Sg{},Pg=class extends I{},AS=class extends Pg{},Na=class extends I{},CS=class extends Na{},Fg=class extends Na{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Ig=class extends Na{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},nn=class extends I{},SS=class extends nn{},PS=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Lg=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},FS=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},IS=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Il=class extends I{},LS=class extends Il{},OS=class extends Il{},Ll=class extends I{},NS=class extends Ll{},DS=class extends Ll{},Ol=class extends I{},zS=class extends Ol{},BS=class extends Ol{},Nl=class extends I{},RS=class extends Nl{},$S=class extends Nl{},Dl=class extends I{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},GS=class extends Dl{},VS=class extends Dl{},Ln=class extends I{},US=class extends Ln{},jS=class extends Ln{async _call(e){return new Xe(await super._call(e))}};var WS=class extends Ln{async _call(e){return new oe(await super._call(e))}},qS=class extends Ln{async _call(e){return new He(await super._call(e))}},HS=class extends Ln{async _call(e){return new it(await super._call(e))}},zl=class extends I{},QS=class extends zl{},XS=class extends zl{async _call(e){return new oe(await super._call(e))}},Bl=class extends I{},YS=class extends Bl{},KS=class extends Bl{async _call(e){return new oe(await super._call(e))}},Rl=class extends I{},JS=class extends Rl{},ZS=class extends Rl{async _call(e){return new ys(await super._call(e))}},ys=class extends Ue{constructor({logits:e,pred_boxes:t}){super();this.logits=e,this.pred_boxes=t}},$l=class extends I{},eP=class extends $l{},tP=class extends $l{async _call(e){return new ys(await super._call(e))}},Og=class extends Ue{constructor({audio_codes:e}){super();this.audio_codes=e}},Ng=class extends Ue{constructor({audio_values:e}){super();this.audio_values=e}},Da=class extends I{main_input_name="input_values";forward_params=["input_values"]},rP=class extends Da{async encode(e){return new Og(await ye(this.sessions.encoder_model,e))}async decode(e){return new Ng(await ye(this.sessions.decoder_model,e))}},Dg=class extends Da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},zg=class extends Da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},On=class extends I{},nP=class extends On{},sP=class extends On{async _call(e){return new Xe(await super._call(e))}},aP=class extends On{async _call(e){return new oe(await super._call(e))}},oP=class extends On{async _call(e){return new He(await super._call(e))}},iP=class extends On{async _call(e){return new it(await super._call(e))}},Gl=class extends I{},lP=class extends Gl{},cP=class extends Gl{},Vl=class extends I{},uP=class extends Vl{},dP=class extends Vl{},Nn=class extends I{},fP=class extends Nn{},hP=class extends Nn{async _call(e){return new Xe(await super._call(e))}},_P=class extends Nn{async _call(e){return new oe(await super._call(e))}},pP=class extends Nn{async _call(e){return new He(await super._call(e))}},mP=class extends Nn{async _call(e){return new it(await super._call(e))}},Bg=class extends I{},gP=class extends Bg{},Ul=class extends I{},wP=class extends Ul{},vP=class extends Ul{async _call(e){return new oe(await super._call(e))}},Rg=class extends I{},yP=class extends Rg{},$g=class extends I{},bP=class extends $g{},za=class extends I{},MP=class extends za{},xP=class extends za{async _call(e){return new jl(await super._call(e))}},kP=class extends za{async _call(e){return new Gg(await super._call(e))}},jl=class extends Ue{constructor({logits:e,pred_boxes:t}){super();this.logits=e,this.pred_boxes=t}},Gg=class extends Ue{constructor({logits:e,pred_boxes:t,pred_masks:r}){super();this.logits=e,this.pred_boxes=t,this.pred_masks=r}},Wl=class extends I{},TP=class extends Wl{},EP=class extends Wl{async _call(e){return new oe(await super._call(e))}},ql=class extends I{},AP=class extends ql{},CP=class extends ql{async _call(e){return new oe(await super._call(e))}},Vg=class extends I{},SP=class extends Vg{},Ug=class extends I{},PP=class extends Ug{},Dn=class extends I{},FP=class extends Dn{},IP=class extends Dn{async _call(e){return new oe(await super._call(e))}},LP=class extends Dn{async _call(e){return new He(await super._call(e))}},OP=class extends Dn{async _call(e){return new it(await super._call(e))}},NP=class extends Dn{async _call(e){return new Xe(await super._call(e))}},jg=class extends I{},DP=class extends jg{},Hl=class extends I{},zP=class extends Hl{},BP=class extends Hl{},Ql=class extends I{},RP=class extends Ql{},$P=class extends Ql{async _call(e){return new oe(await super._call(e))}},zn=class extends I{},GP=class extends zn{},VP=class extends zn{async _call(e){return new Xe(await super._call(e))}},UP=class extends zn{async _call(e){return new oe(await super._call(e))}},jP=class extends zn{async _call(e){return new He(await super._call(e))}},WP=class extends zn{async _call(e){return new it(await super._call(e))}},Wg=class extends I{},qg=class extends Wg{async forward({input_ids:e,attention_mask:t,pixel_values:r=null,image_position_ids:n=null,pixel_values_videos:s=null,video_position_ids:a=null,input_features:o=null,input_features_mask:i=null}){let l={image_features:r&&await this.encode_image({pixel_values:r,pixel_position_ids:n}),video_features:s&&await this.encode_image({pixel_values:s,pixel_position_ids:a}),audio_features:o&&await this.encode_audio({input_features:o,input_features_mask:i})},{image_token_id:c,video_token_id:d,audio_token_id:f,text_config:_}=this.config,p={image:c,video:d,audio:f};for(let[w,v]of Object.entries(p)){let y=`${w}_features`;l[y]??=new U("float32",new Float32Array(0),[0,_.hidden_size]);let b=0;for(let k of e.data)if(Number(k)===v)++b;if(b!==l[y].dims[0])throw Error(`The number of ${w} tokens (${b}) and ${w} features (${l[y].dims[0]}) do not match.`)}return await ye(this.sessions.model,{input_ids:e,attention_mask:t,...l})}},Xl=class extends I{},qP=class extends Xl{},HP=class extends Xl{},bs=class extends I{},QP=class extends bs{},XP=class extends bs{async _call(e){return new Xe(await super._call(e))}},YP=class extends bs{async _call(e){return new oe(await super._call(e))}},KP=class extends bs{async _call(e){return new He(await super._call(e))}},Ms=class extends I{},JP=class extends Ms{},ZP=class extends Ms{async _call(e){return new Xe(await super._call(e))}},eF=class extends Ms{async _call(e){return new oe(await super._call(e))}},tF=class extends Ms{async _call(e){return new He(await super._call(e))}},Yl=class extends I{},rF=class extends Yl{},nF=class extends Yl{},Kl=class extends I{},sF=class extends Kl{},aF=class extends Kl{},Jl=class extends I{},oF=class extends Jl{},iF=class extends Jl{},Zl=class extends I{},lF=class extends Zl{},cF=class extends Zl{async _call(e){return new oe(await super._call(e))}},Hg=class extends I{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"},uF=class extends Hg{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Ne([t,e],1),attention_mask:Ne([gt(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:n}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let s,a;if(e)s=await this.encode_text({input_ids:e});if(t)a=await this.encode_image({pixel_values:t});if(s&&a)({inputs_embeds:r,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:s,image_features:a,input_ids:e,attention_mask:n}));else r=s||a;return{inputs_embeds:r,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:n,decoder_attention_mask:s,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l,num_logits_to_keep:c=null}){if(!i)({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r}));if(!a){let{last_hidden_state:f}=await Lr(this,{inputs_embeds:i,attention_mask:r});a=f}if(!l){if(!n)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}return await pr(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:c},!0)}},ec=class extends I{},dF=class extends ec{},fF=class extends ec{},tc=class extends I{},hF=class extends tc{},_F=class extends tc{},Qg=class extends I{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Ut=class extends Qg{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Ml({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},pF=class extends Ut{},mF=class extends Ut{},Xg=class extends I{},gF=class extends Xg{},Yg=class extends Ut{},wF=class extends Yg{},Kg=class extends I{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},Ba=class extends Kg{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:n=null,input_features_mask:s=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,num_logits_to_keep:f=null,..._}){if(!o||!i){if({inputs_embeds:o,per_layer_inputs:i}=await ye(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1){if(r){let{image_features:w}=await this._encode_vision({pixel_values:r,..._});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){let{audio_features:w}=await ye(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:o,input_ids:e,attention_mask:t}))}}}return await pr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d,num_logits_to_keep:f},!0)}_encode_vision(e){return ye(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Ml({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Eg({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},vF=class extends Ba{},rc=class extends Ba{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})}},yF=class extends rc{},nc=class extends I{},bF=class extends nc{},MF=class extends nc{},sc=class extends I{},xF=class extends sc{},kF=class extends sc{},Jg=class extends I{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},ac=class extends Jg{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){let{data:r,dims:n}=kg(t),s=BigInt64Array.from({length:3*r.length},(o,i)=>r[i%r.length]),a=Array.from({length:n[0]},(o,i)=>qe(r.subarray(n[1]*i,n[1]*(i+1)))[0]+1n+BigInt(n[1]));return[new U("int64",s,[3,...n]),new U("int64",a,[a.length,1])]}else{let[r,n]=e.dims,s=BigInt64Array.from({length:3*r*n},(a,o)=>BigInt(Math.floor(o%n/r)));return[new U("int64",s,[3,...e.dims]),xm([r,1])]}}_reorder_and_write_positions(e,t,r,n){let s=e.reduce((l,c)=>l+c.length,0),a=Array(s),o=0;for(let l=0;l<3;++l)for(let c of e){let d=c.length/3;for(let f=l*d;f<(l+1)*d;++f)a[o++]=c[f]}let i=0;for(let l=0;l<t.length;++l)if(t[l]==1){for(let c=0;c<3;++c)r[c][n][l]=a[c*s/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:n,state:s}){let{image_token_id:a,video_token_id:o,vision_start_token_id:i}=this.config,l=e,d=l.reduce((b,k,A)=>{if(k==i)b.push(A);return b},[]).map((b)=>l[b+1]),f=d.filter((b)=>b==a).length,_=d.filter((b)=>b==o).length,p=[],w=0,v=f,y=_;for(let b=0;b<d.length;++b){let k=l.findIndex((L,O)=>O>w&&L==a),A=l.findIndex((L,O)=>O>w&&L==o),E=v>0&&k!==-1?k:l.length+1,C=y>0&&A!==-1?A:l.length+1,N,M,G,R;if(E<C)[M,G,R]=t[s.image_index],++s.image_index,--v,N=E;else[M,G,R]=r[s.video_index],++s.video_index,--y,N=C;let[q,X,Q]=[Number(M),Math.floor(Number(G)/n),Math.floor(Number(R)/n)],H=N-w,B=p.length>0?qe(p.at(-1))[0]+1:0;p.push(Array.from({length:3*H},(L,O)=>B+O%H));let P=H+B,Y=q*X*Q,ue=Array.from({length:Y},(L,O)=>P+Math.floor(O/(X*Q))),Z=Array.from({length:Y},(L,O)=>P+Math.floor(O/Q)%X),se=Array.from({length:Y},(L,O)=>P+O%Q);p.push([ue,Z,se].flat()),w=N+Y}if(w<l.length){let b=p.length>0?qe(p.at(-1))[0]+1:0,k=l.length-w;p.push(Array.from({length:3*k},(A,E)=>b+E%k))}return p}get_rope_index(e,t,r,n){let{vision_config:s}=this.config,a=s.spatial_merge_size??2;if(t||r){let o=e.tolist();if(!n)n=il(e);let i=n.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():[],f={image_index:0,video_index:0},_=[];for(let p=0;p<o.length;++p){let w=o[p].filter((b,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:f}),y=this._reorder_and_write_positions(v,i[p],l,p);_.push(qe(y)[0]+1-o[p].length)}return[new U("int64",l.flat(1/0),[3,e.dims[0],e.dims[1]]),new U("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await ye(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Ml({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(ws(this,t,1n),!t.attention_mask||t.position_ids)return t;if(!(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;let s=t.past_key_values.get_seq_length();if(s<t.input_ids.dims[1]){let[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,[s,null]),t.input_ids=t.input_ids.slice(null,[s,null])}else{if(!t.rope_deltas)[,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);let a=BigInt(s),o=t.rope_deltas.map((i)=>a+i);t.position_ids=_r([o,o,o],0)}}return t}},Zg=class extends ac{},oc=class extends ac{image_grid_thw_name="image_grid_thw"},ew=class extends Zg{image_grid_thw_name="image_grid_thw"},TF=class extends oc{get_vision_position_ids(e,t,r,n){let s=Math.floor(t[0]/r),a=Math.floor(t[1]/n),o=Math.floor(t[2]/n),i=a*o*s,l=Array.from({length:i},()=>e),c=Array.from({length:i},(f,_)=>e+Math.floor(_/(o*s))),d=Array.from({length:i},(f,_)=>e+_%o);return[...l,...c,...d]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:n,state:s}){let{image_token_id:a}=this.config,o=[],i=0,l=e[0]==a?1:0;for(let f=1;f<=e.length;++f){let _=f<e.length?e[f]==a?1:0:-1;if(_!==l)o.push([l,i,f]),i=f,l=_}let c=0,d=[];for(let[f,_,p]of o)if(f===0){let w=p-_;d.push(Array.from({length:3*w},(v,y)=>c+y%w)),c+=w}else{let w=t[s.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(c,w,v,n)),c+=Math.max(w[1],w[2])/n}return d}},ic=class extends I{},EF=class extends ic{},AF=class extends ic{},lc=class extends I{},CF=class extends lc{},SF=class extends lc{},cc=class extends I{},PF=class extends cc{},FF=class extends cc{},uc=class extends I{},IF=class extends uc{},LF=class extends uc{},dc=class extends I{},OF=class extends dc{},NF=class extends dc{},fc=class extends I{},DF=class extends fc{},zF=class extends fc{},hc=class extends I{},BF=class extends hc{},RF=class extends hc{},_c=class extends I{},$F=class extends _c{},GF=class extends _c{},pc=class extends I{},VF=class extends pc{},UF=class extends pc{},tw=class extends I{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},mc=class extends tw{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Eg({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},jF=class extends mc{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},rw=class extends I{},WF=class extends rw{},nw=class extends I{},qF=class extends nw{},gc=class extends I{},HF=class extends gc{},QF=class extends gc{},wc=class extends I{},XF=class extends wc{},YF=class extends wc{async _call(e){return new oe(await super._call(e))}},vc=class extends I{},KF=class extends vc{},JF=class extends vc{forward_params=["input_ids","attention_mask","token_type_ids","past_key_values"];prepare_inputs_for_generation(e,t,r){let n=An(this,e,t,r);return n.token_type_ids=(n.past_key_values?ll:il)(n.input_ids),n}},Nr=class extends I{},ZF=class extends Nr{},eI=class extends Nr{async _call(e){return new Or(await super._call(e))}},tI=class extends Nr{async _call(e){return new oe(await super._call(e))}},rI=class extends Nr{async _call(e){return new He(await super._call(e))}},nI=class extends I{},sI=class extends Nr{},aI=class extends Nr{async _call(e){return new Or(await super._call(e))}},oI=class extends Nr{async _call(e){return new oe(await super._call(e))}},yc=class extends I{},iI=class extends yc{},lI=class extends yc{},sw=class extends Ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},bc=class extends I{},cI=class extends bc{},uI=class extends bc{async _call(e){return new oe(await super._call(e))}},Mc=class extends I{},dI=class extends Mc{},fI=class extends Mc{},Ra=class extends I{},hI=class extends Ra{async forward(e){let t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t)e.input_ids=gt([e.pixel_values.dims[0],1]);if(r){let{image_size:l}=this.config.vision_config;e.pixel_values=dt([0,3,l,l],0)}let{text_embeddings:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};if(!t)i.text_embeddings=n,i.l2norm_text_embeddings=a;if(!r)i.image_embeddings=s,i.l2norm_image_embeddings=o;return i}},aw=class extends Ra{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_I=class extends Ra{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},xc=class extends I{},pI=class extends xc{},mI=class extends xc{},gI=class extends Ut{},kc=class extends I{},wI=class extends kc{},vI=class extends kc{},yI=class extends Ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},Tc=class extends I{},bI=class extends Tc{},MI=class extends Tc{},xI=class extends Ut{forward_params=["input_ids","attention_mask","pixel_values","image_grid_thw","position_ids","past_key_values"]},Ec=class extends I{},kI=class extends Ec{},TI=class extends Ec{},ow=class extends I{},EI=class extends ow{},Ac=class extends I{},AI=class extends Ac{},CI=class extends Ac{},Cc=class extends I{},SI=class extends Cc{},PI=class extends Cc{},Sc=class extends I{},FI=class extends Sc{},II=class extends Sc{},Pc=class extends I{},LI=class extends Pc{},OI=class extends Pc{},xs=class extends I{},NI=class extends xs{},DI=class extends xs{},zI=class extends xs{async _call(e){return new oe(await super._call(e))}},BI=class extends xs{},iw=class extends I{},RI=class extends iw{},lw=class extends I{},$I=class extends lw{},cw=class extends Ue{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]}},uw=class extends I{},GI=class extends uw{async _call(e){return new cw(await super._call(e))}},dw=class extends Ue{constructor({audio_codes:e}){super();this.audio_codes=e}},fw=class extends Ue{constructor({audio_values:e}){super();this.audio_values=e}},$a=class extends I{main_input_name="input_values";forward_params=["input_values"]},VI=class extends $a{async encode(e){return new dw(await ye(this.sessions.encoder_model,e))}async decode(e){return new fw(await ye(this.sessions.decoder_model,e))}},hw=class extends $a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},_w=class extends $a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Fc=class extends I{},UI=class extends Fc{},jI=class extends Fc{},Ic=class extends I{},WI=class extends Ic{},qI=class extends Ic{},Lc=class extends I{},HI=class extends Lc{},QI=class extends Lc{},XI=class extends Ut{},Oc=class extends I{},YI=class extends Oc{},KI=class extends Oc{},ks=class extends I{},JI=class extends ks{},ZI=class extends ks{async _call(e){return new Xe(await super._call(e))}},eL=class extends ks{async _call(e){return new oe(await super._call(e))}},tL=class extends ks{async _call(e){return new it(await super._call(e))}},Nc=class extends I{},rL=class extends Nc{},nL=class extends Nc{},Ga=class extends I{},sL=class extends Ga{},aL=class extends Ga{async _call(e){return new oe(await super._call(e))}},oL=class extends Ga{},Va=class extends I{},iL=class extends Va{},lL=class extends Va{async _call(e){return new oe(await super._call(e))}},cL=class extends Va{},Ua=class extends I{},uL=class extends Ua{},dL=class extends Ua{async _call(e){return new oe(await super._call(e))}},fL=class extends Ua{},ja=class extends I{},hL=class extends ja{},_L=class extends ja{async _call(e){return new oe(await super._call(e))}},pL=class extends ja{},Dc=class extends I{},mL=class extends Dc{},gL=class extends Dc{async _call(e){return new oe(await super._call(e))}},zc=class extends I{},wL=class extends zc{},vL=class extends zc{async _call(e){return new oe(await super._call(e))}},Ts=class extends I{},yL=class extends Ts{},bL=class extends Ts{async _call(e){return new Xe(await super._call(e))}},ML=class extends Ts{async _call(e){return new oe(await super._call(e))}},xL=class extends Ts{async _call(e){return new He(await super._call(e))}},Bc=class extends I{},kL=class extends Bc{},TL=class extends Bc{},Rc=class extends I{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},EL=class extends Rc{},AL=class extends Rc{},Bn=class extends I{},CL=class extends Bn{},SL=class extends Bn{async _call(e){return new Xe(await super._call(e))}},PL=class extends Bn{async _call(e){return new oe(await super._call(e))}},FL=class extends Bn{async _call(e){return new He(await super._call(e))}},IL=class extends Bn{async _call(e){return new it(await super._call(e))}},$c=class extends I{},LL=class extends $c{},OL=class extends $c{},Gc=class extends I{},NL=class extends Gc{},DL=class extends Gc{},pw=class extends I{},zL=class extends pw{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){let t=this._generation_mode??"text",r;if(t==="text"||!e.past_key_values){let i=this.sessions.prepare_inputs_embeds,l=et(e,i.inputNames);r=await ye(i,l)}else{let i=this.sessions.gen_img_embeds,l=et({image_ids:e.input_ids},i.inputNames);r=await ye(i,l)}let n={...e,...r},s=await pr(this,n),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await ye(a,et(s,a.inputNames));return{...r,...s,...o}}prepare_inputs_for_generation(e,t,r){let n=!!t.past_key_values;if(ws(this,t,1n),r.guidance_scale!==null&&r.guidance_scale>1)if(n)t.input_ids=Ne([t.input_ids,t.input_ids],0);else t.input_ids=Ne([t.input_ids,Bi(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=Ne([t.attention_mask,Bi(t.attention_mask,0n)],0);if(n||!t.pixel_values)t.pixel_values=dt([0,0,3,384,384],1);if(n)t.images_seq_mask=new U("bool",[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new U("bool",[].fill(!1),[1,1,0]);return t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),s=this.sessions.image_decode,{decoded_image:a}=await ye(s,{generated_tokens:n}),o=a.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),i=[];for(let l of o){let c=Vt.fromTensor(l);i.push(c)}return i}},Vc=class extends I{},BL=class extends Vc{},RL=class extends Vc{},mw=class extends I{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){let[t,r]=e.dims,n=this.config.decoder.num_codebooks,s=r-n,a=0;for(let l=0;l<e.size;++l){if(e.data[l]==this.config.decoder.pad_token_id)continue;let c=l%r,d=Math.floor(l/r)%n,f=c-d;if(f>0&&f<=s)e.data[a++]=e.data[l]}let o=Math.floor(t/n),i=a/(o*n);return new U(e.type,e.data.slice(0,a),[o,n,i])}prepare_inputs_for_generation(e,t,r){let n=BigInt(this.config.decoder.pad_token_id),s=structuredClone(e);for(let a=0;a<s.length;++a)for(let o=0;o<s[a].length;++o)if(a%this.config.decoder.num_codebooks>=o)s[a][o]=n;if(r.guidance_scale!==null&&r.guidance_scale>1)s=s.concat(s);return xa(this,s,t,r)}async generate(e){let t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:n}=await ye(this.sessions.encodec_decode,{audio_codes:r});return n}},Uc=class extends I{},$L=class extends Uc{},GL=class extends Uc{},jc=class extends I{},VL=class extends jc{},UL=class extends jc{},Rn=class extends I{},jL=class extends Rn{},WL=class extends Rn{async _call(e){return new Xe(await super._call(e))}},qL=class extends Rn{async _call(e){return new oe(await super._call(e))}},HL=class extends Rn{async _call(e){return new He(await super._call(e))}},QL=class extends Rn{async _call(e){return new it(await super._call(e))}},gw=class extends I{},XL=class extends gw{},Wc=class extends I{},YL=class extends Wc{},KL=class extends Wc{},qc=class extends I{},JL=class extends qc{},ZL=class extends qc{},Hc=class extends I{},eO=class extends Hc{},tO=class extends Hc{},Qc=class extends I{},rO=class extends Qc{},nO=class extends Qc{},Xc=class extends I{},sO=class extends Xc{},aO=class extends Xc{async _call(e){return new oe(await super._call(e))}},Yc=class extends I{},oO=class extends Yc{},iO=class extends Yc{},Kc=class extends I{},lO=class extends Kc{},cO=class extends Kc{},Jc=class extends I{},uO=class extends Jc{},dO=class extends Jc{},Zc=class extends I{},fO=class extends Zc{},hO=class extends Zc{},_O=class extends Ut{},ww=class extends I{},pO=class extends ww{async _call(e){return new Or(await super._call(e))}},eu=class extends I{},mO=class extends eu{},gO=class extends eu{},tu=class extends I{},wO=class extends tu{},vO=class extends tu{},ru=class extends I{},yO=class extends ru{},bO=class extends ru{},nu=class extends I{},MO=class extends nu{},xO=class extends nu{},vw=class extends I{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},yw=class extends vw{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,num_logits_to_keep:c=null,...d}){if(!a){let _;if(r&&e.dims[1]!==1){if(!n)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await ye(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{let p=this.config.normalized_config.hidden_size;_=new U("float32",[],[0,p])}({inputs_embeds:a}=await ye(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1)}},su=class extends I{},kO=class extends su{},TO=class extends su{async _call(e){return new oe(await super._call(e))}},au=class extends I{},EO=class extends au{},AO=class extends au{async _call(e){return new He(await super._call(e))}},ou=class extends I{},CO=class extends ou{},SO=class extends ou{},iu=class extends I{},PO=class extends iu{},FO=class extends iu{},lu=class extends I{},IO=class extends lu{},LO=class extends lu{},cu=class extends I{},OO=class extends cu{},NO=class extends cu{},uu=class extends I{},DO=class extends uu{},zO=class extends uu{},du=class extends oc{},bw=class extends ew{},BO=class extends du{},RO=class extends bw{},fu=class extends du{},Mw=class extends fu{},$O=class extends fu{},GO=class extends Mw{},hu=class extends I{},VO=class extends hu{},UO=class extends hu{async _call(e){return new oe(await super._call(e))}},_u=class extends I{},jO=class extends _u{},WO=class extends _u{async _call(e){return new xw(await super._call(e))}},xw=class extends ys{},$n=class extends I{},qO=class extends $n{},HO=class extends $n{async _call(e){return new Xe(await super._call(e))}},QO=class extends $n{async _call(e){return new oe(await super._call(e))}},XO=class extends $n{async _call(e){return new He(await super._call(e))}},YO=class extends $n{async _call(e){return new it(await super._call(e))}},Gn=class extends I{},KO=class extends Gn{},JO=class extends Gn{async _call(e){return new Xe(await super._call(e))}},ZO=class extends Gn{async _call(e){return new oe(await super._call(e))}},eN=class extends Gn{async _call(e){return new He(await super._call(e))}},tN=class extends Gn{async _call(e){return new it(await super._call(e))}},pu=class extends I{},rN=class extends pu{},nN=class extends pu{async _call(e){return new kw(await super._call(e))}},kw=class extends ys{},Tw=class extends Ue{constructor({iou_scores:e,pred_masks:t}){super();this.iou_scores=e,this.pred_masks=t}},Ew=class extends I{},sN=class extends Ew{async get_image_embeddings({pixel_values:e}){return await Lr(this,{pixel_values:e})}async forward(e){if(!e.image_embeddings||!e.image_positional_embeddings)e={...e,...await this.get_image_embeddings(e)};else e={...e};e.input_labels??=gt(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};if(e.input_points)t.input_points=e.input_points;if(e.input_labels)t.input_labels=e.input_labels;if(e.input_boxes)t.input_boxes=e.input_boxes;return await ye(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new Tw(await super._call(e))}},Aw=class extends Ue{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}},Cw=class extends I{},mu=class extends Cw{async get_image_embeddings({pixel_values:e}){return await Lr(this,{pixel_values:e})}async forward(e){let{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)};else e={...e};if(e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=gt(a.slice(0,-1)),e.input_boxes??=dt([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=dt([a[0],a[1],0],-1n),e.input_points=dt([a[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,s=et(e,n.inputNames);return await ye(n,s)}async _call(e){return new Aw(await super._call(e))}},aN=class extends mu{},oN=class extends mu{},Wa=class extends I{},iN=class extends Wa{},lN=class extends Wa{},cN=class extends Wa{},qa=class extends I{},uN=class extends qa{},dN=class extends qa{},fN=class extends qa{},gu=class extends I{},hN=class extends gu{},Sw=class extends gu{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_N=class extends nn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},wu=class extends I{},pN=class extends wu{},mN=class extends wu{},gN=class extends sw{},Ha=class extends I{main_input_name="input_values";forward_params=["input_values"]},wN=class extends Ha{async encode(e){return await ye(this.sessions.encoder_model,e)}async decode(e){return await ye(this.sessions.decoder_model,e)}},Pw=class extends Ha{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Fw=class extends Ha{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},vu=class extends I{},vN=class extends vu{},yN=class extends vu{},Qa=class extends I{},bN=class extends Qa{},MN=class extends Qa{},xN=class extends Qa{async generate_speech(e,t,{threshold:r=0.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Lr(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*s),f=Math.floor(c*n),_=this.config.num_mel_bins,p=[],w=null,v=null,y=0;while(!0){++y;let A=bg(!!v),E;if(v)E=v.output_sequence_out;else E=new U("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};bl(this,C,w),v=await ye(this.sessions.decoder_model_merged,C),w=ji(v,w);let{prob:N,spectrum:M}=v;if(p.push(M),y>=f&&(Array.from(N.data).filter((G)=>G>=r).length>0||y>=d))break}let b=Ne(p),{waveform:k}=await ye(a.sessions.model,{spectrogram:b});return{spectrogram:b,waveform:k}}},kN=class extends I{main_input_name="spectrogram"},Es=class extends I{},TN=class extends Es{},EN=class extends Es{async _call(e){return new Xe(await super._call(e))}},AN=class extends Es{async _call(e){return new oe(await super._call(e))}},CN=class extends Es{async _call(e){return new it(await super._call(e))}},yu=class extends I{},SN=class extends yu{},PN=class extends yu{},bu=class extends I{},FN=class extends bu{},IN=class extends bu{},Iw=class extends I{},LN=class extends Iw{},Lw=class extends I{},Ow=class extends Lw{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:n=5,speed:s=1.05}){let{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}),f=d.div(s).mul_(a),_=i*o,p=f.data,w=Int32Array.from(p,(R)=>Math.ceil(R/_)),v=Math.max(...w),y=e.dims[0],b=new BigInt64Array(y*v);for(let R=0;R<y;++R)b.fill(1n,R*v,R*v+w[R]);let k=new U("int64",b,[y,v]),A=l*o,E=A*v,C=GT([y,A,v]),N=C.data;for(let R=0;R<y;++R){if(w[R]===v)continue;for(let q=0;q<A;++q)N.fill(0,R*E+q*v+w[R],R*E+(q+1)*v)}let M=dt([y],n);for(let R=0;R<n;++R){let q=dt([y],R);({denoised_latents:C}=await ye(this.sessions.latent_denoiser,{style:r,noisy_latents:C,latent_mask:k,encoder_outputs:c,attention_mask:t,timestep:q,num_inference_steps:M}))}let{waveform:G}=await ye(this.sessions.voice_decoder,{latents:C});return{waveform:G,durations:f}}},Xa=class extends I{},ON=class extends Xa{},NN=class extends Xa{async _call(e){return new oe(await super._call(e))}},DN=class extends Xa{},Mu=class extends I{},zN=class extends Mu{},BN=class extends Mu{},xu=class extends I{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},RN=class extends xu{},$N=class extends xu{},ku=class extends I{},GN=class extends ku{},VN=class extends ku{async _call(e){return new Nw(await super._call(e))}},Nw=class extends jl{},Dw=class extends I{},UN=class extends Dw{},Ya=class extends I{},jN=class extends Ya{},WN=class extends Ya{async _call(e){return new Or(await super._call(e))}},qN=class extends Ya{async _call(e){return new oe(await super._call(e))}},As=class extends I{},HN=class extends As{},QN=class extends As{async _call(e){return new Or(await super._call(e))}},XN=class extends As{async _call(e){return new oe(await super._call(e))}},YN=class extends As{async _call(e){return new He(await super._call(e))}},Tu=class extends I{},KN=class extends Tu{},JN=class extends Tu{},ZN=class extends I{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},Eu=class extends I{},e3=class extends Eu{},t3=class extends Eu{async _call(e){return new oe(await super._call(e))}},zw=class extends I{},r3=class extends zw{},Au=class extends I{},n3=class extends Au{},s3=class extends Au{async _call(e){return new oe(await super._call(e))}},Bw=class extends I{},a3=class extends Bw{async _call(e){return new _g(await super._call(e))}},Rw=class extends I{},o3=class extends Rw{},$w=class extends Ue{constructor({waveform:e,spectrogram:t}){super();this.waveform=e,this.spectrogram=t}},Gw=class extends I{},i3=class extends Gw{async _call(e){return new $w(await super._call(e))}},l3=class extends mc{},Ep=2,c3=1,Pi=new WeakMap;function u3(e,t){let{text_config:r,audio_config:n}=e.config,s=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=n,i=a+o,l=new vl,c=Ia(n),d={batch_size:1},f="float32";for(let v of s.inputMetadata){if(v.name==="past_padding_cache"){f=v.type;continue}if(!c.has(v.name))continue;let y=Mg(v.shape,d),b=y.reduce((A,E)=>A*E,1),k=us[v.type];l[v.name]=new U(v.type,new k(b),y)}let _=us[f],p=new U(f,new _(i*Ep),[1,i,Ep]),w=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!w)throw Error("input_features must be iterable or async iterable");return{encoder_session:s,enc_kv_cache:l,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function d3(e,t){let r=t.dims[2],n=Math.floor((c3+r-3)/2)+1,s=new U("int64",BigInt64Array.from({length:n},(d,f)=>BigInt(e.enc_past_seq_len+f)),[1,n]),a=e.enc_past_seq_len+n,o=gt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await ye(e.encoder_session,{input_features:t,attention_mask:o,position_ids:s,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});if(e.enc_padding_cache.location==="gpu-buffer")e.enc_padding_cache.dispose();e.enc_padding_cache=l;for(let d in c)if(d.startsWith("present.")){let f=d.replace("present","past_key_values"),_=e.enc_kv_cache[f];if(_?.location==="gpu-buffer")_.dispose();e.enc_kv_cache[f]=c[d]}return e.enc_past_seq_len=a,i}async function f3(e,t){while(e.audio_embed_total_tokens<t&&!e.stream_exhausted){let r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}let n=await d3(e,r.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function h3(e,t,r){if(e.audio_embed_queue.length===0)return;let n=t.data,s=0,a=r;while(a>0&&e.audio_embed_queue.length>0){let o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)n[s*e.text_hidden_size+d]+=o.data[c+d];if(s+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens)e.audio_embed_queue.shift(),e.audio_queue_offset=0}e.audio_consumed+=r-a}var _3=class extends gs{constructor(e){super();this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},Vw=class extends I{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Uw=class extends Vw{async forward({input_ids:e,past_key_values:t,...r}){let n=e.dims[1],s=Pi.get(this);if(s)await f3(s,s.audio_consumed+n);let{inputs_embeds:a}=await ye(this.sessions.embed_tokens,{input_ids:e});if(s)h3(s,a,n);let o={inputs_embeds:a,...r};bl(this,o,t);let i=this.sessions.decoder_model_merged,l=et(o,i.inputNames);return await ye(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw Error("input_features (generator/iterable) must be provided");let n=u3(this,e);Pi.set(this,n);let s=new gg;if(s.push(new _3(n)),t)s.extend(t);try{return await super.generate({...r,stopping_criteria:s})}finally{n.enc_kv_cache.dispose(),Pi.delete(this)}}},Ka=class extends I{},p3=class extends Ka{},m3=class extends Ka{async _call(e){return new Or(await super._call(e))}},g3=class extends Ka{async _call(e){return new oe(await super._call(e))}},jw=class extends Ue{constructor({logits:e,embeddings:t}){super();this.logits=e,this.embeddings=t}},Vn=class extends I{},w3=class extends Vn{},v3=class extends Vn{async _call(e){return new Or(await super._call(e))}},y3=class extends Vn{async _call(e){return new oe(await super._call(e))}},b3=class extends Vn{async _call(e){return new jw(await super._call(e))}},M3=class extends Vn{async _call(e){return new He(await super._call(e))}},Ww=class extends I{},x3=class extends Ww{},k3=class extends mg{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},Cu=class extends I{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},T3=class extends Cu{},qw=class extends Cu{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,k3)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],{language:r,task:n}=e;if(e.is_multilingual){if(!r)ce.warn("No language specified - defaulting to English (en)."),r="en";let a=`<|${DE(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(r||n)throw 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.");if(!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id)t.push(e.no_timestamps_token_id);else if(e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id)ce.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop();return t.filter((s)=>s!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,...s}){t=this._prepare_generation_config(t,s);let a=s.decoder_input_ids instanceof U?cl(s.decoder_input_ids):s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps)r??=new Vi,r.push(new xC(t,a));if(t.begin_suppress_tokens)r??=new Vi,r.push(new pg(t.begin_suppress_tokens,a.length));if(t.return_token_timestamps){if(!t.alignment_heads)throw 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.");if(t.task==="translate")ce.warn("Token-level timestamps may not be reliable for task 'translate'.");t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!s.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:s});let o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});if(t.return_token_timestamps)o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,0.02,a.length);return o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:n,kwargs:s}){let 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,_=2*this.config.max_source_positions,p=0,w=[],v=[];while(p<c){let b=Math.min(p+_,c),k=l.slice(null,null,[p,b]),A,E=k.dims[2];if(E<_){let Y=l.dims[1],ue=new Float32Array(Y*_),Z=k.data;for(let se=0;se<Y;++se)ue.set(Z.subarray(se*E,(se+1)*E),se*_);A=new U("float32",ue,[1,Y,_])}else A=k;if(r){for(let Y of r)if("begin_index"in Y)Y.begin_index=n.length}let C=await super.generate({inputs:A,generation_config:t,logits_processor:r,decoder_input_ids:n,...s}),M=(i?C.sequences:C)[0].tolist().map(Number).slice(n.length),G;if(i){C.token_timestamps=this._extract_token_timestamps(C,t.alignment_heads,Math.floor((b-p)/2),0.02,n.length);let Y=p/2*0.02;G=C.token_timestamps[0].tolist().slice(n.length).map((ue)=>ue+Y)}if(M.length>0&&M.at(-1)===o)M.pop();if(M.length===0)break;let R=M.map((Y)=>Y>=a),q=M.length>=2&&R[M.length-1]&&!R[M.length-2],X=[];for(let Y=0;Y<M.length-1;++Y)if(R[Y]&&R[Y+1])X.push(Y+1);let Q,H=M.length;if(X.length>0)if(q)Q=b-p;else{let Y=X.at(-1);Q=(M[Y-1]-a)*2,H=Y}else Q=b-p;let B=Math.floor(p/2),P=a+1500;for(let Y=0;Y<H;++Y)if(M[Y]>=a)M[Y]=Math.min(M[Y]+B,P);if(w.push(...M.slice(0,H)),G)v.push(...G.slice(0,H));p+=Q}w.push(o);let y=[...n,...w];if(i){let b=new U("int64",y.map(BigInt),[1,y.length]),k=[...Array(n.length).fill(0),...v,0],A=new U("float32",new Float32Array(k),[1,k.length]);return{sequences:b,token_timestamps:A}}return new U("int64",y.map(BigInt),[1,y.length])}_extract_token_timestamps(e,t,r=null,n=0.02,s=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");if(r==null)ce.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;if(a===void 0)ce.warn("Model config has no `median_filter_width`, using default value of 7."),a=7;let o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(y,b)=>Ne(o.map((k)=>k[b]),2)),l=_r(t.map(([y,b])=>{if(y>=i.length)throw Error(`Layer index ${y} is out of bounds for cross attentions (length ${i.length}).`);return r?i[y].slice(null,b,null,[0,r]):i[y].slice(null,b)})).permute(1,0,2,3),[c,d]=$T(l,-2,0,!0),f=l.clone();for(let y=0;y<f.dims[0];++y){let b=f[y];for(let k=0;k<b.dims[0];++k){let A=b[k],E=c[y][k][0].data,C=d[y][k][0].data;for(let N=0;N<A.dims[0];++N){let M=A[N].data;for(let G=0;G<M.length;++G)M[G]=(M[G]-C[G])/E[G];M.set(bT(M,a))}}}let _=s>0?f.slice(null,null,[s,f.dims[2]],null):f,p=[al(_,1)],w=e.sequences.dims,v=new U("float32",new Float32Array(w[0]*w[1]),w);for(let y=0;y<w[0];++y){let b=p[y].neg().squeeze_(0),[k,A]=xT(b.tolist()),E=Array.from({length:k.length-1},(G,R)=>k[R+1]-k[R]),C=Bt([1],E).map((G)=>!!G),N=[];for(let G=0;G<C.length;++G)if(C[G])N.push(A[G]*n);let M=Array(s).fill(0);if(M.push(...N),N.length>0)M.push(N.at(-1));v[y].data.set(M)}return v}},E3=class extends qw{},Un=class extends I{},A3=class extends Un{},C3=class extends Un{async _call(e){return new Xe(await super._call(e))}},S3=class extends Un{async _call(e){return new oe(await super._call(e))}},P3=class extends Un{async _call(e){return new He(await super._call(e))}},F3=class extends Un{async _call(e){return new it(await super._call(e))}},jn=class extends I{},I3=class extends jn{},L3=class extends jn{async _call(e){return new Xe(await super._call(e))}},O3=class extends jn{async _call(e){return new oe(await super._call(e))}},N3=class extends jn{async _call(e){return new He(await super._call(e))}},D3=class extends jn{async _call(e){return new it(await super._call(e))}},Su=class extends I{},z3=class extends Su{},B3=class extends Su{async _call(e){return new Hw(await super._call(e))}},Hw=class extends Ue{constructor({logits:e,pred_boxes:t}){super();this.logits=e,this.pred_boxes=t}},Pu=class extends I{},R3=class extends Pu{},$3=class extends Pu{},Fu=class extends I{},G3=class extends Fu{},V3=class extends Fu{},U3=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"],["embedding_gemma2","EmbeddingGemma2Model"]]),j3=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"]]),W3=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),q3=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"],["lfm3","Lfm3Model"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["deepseek_v4","DeepseekV4Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"],["zaya","ZayaModel"],["hrm_text","HrmTextModel"]]),Qw=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Xw=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Yw=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Kw=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"]]),Jw=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"]]),Zw=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),ev=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"],["lfm3","Lfm3ForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["deepseek_v4","DeepseekV4ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["zaya","ZayaForCausalLM"],["hrm_text","HrmTextForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),H3=new Map([["multi_modality","MultiModalityCausalLM"]]),tv=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"]]),rv=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"]]),nv=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),sv=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"],["lfm3_vl","Lfm3VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),av=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),Q3=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),ov=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"]]),iv=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),lv=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),bn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),cv=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),uv=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),dv=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),fv=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),hv=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),_v=new Map([["wavlm","WavLMForXVector"]]),pv=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),mv=new Map([["vitmatte","VitMatteForImageMatting"]]),X3=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),gv=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),wv=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),vv=new Map([["sapiens","SapiensForNormalEstimation"]]),yv=new Map([["vitpose","VitPoseForPoseEstimation"]]),bv=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),Mv=[[U3,W.EncoderOnly],[j3,W.EncoderDecoder],[q3,W.DecoderOnlyWithoutHead],[W3,W.AutoEncoder],[Kw,W.EncoderOnly],[Jw,W.EncoderOnly],[Zw,W.Seq2Seq],[Qw,W.Seq2Seq],[ev,W.DecoderOnly],[H3,W.MultiModality],[tv,W.EncoderOnly],[rv,W.EncoderOnly],[nv,W.Vision2Seq],[sv,W.ImageTextToText],[av,W.AudioTextToText],[ov,W.EncoderOnly],[bn,W.EncoderOnly],[uv,W.EncoderOnly],[cv,W.EncoderOnly],[mv,W.EncoderOnly],[X3,W.EncoderOnly],[gv,W.EncoderOnly],[wv,W.EncoderOnly],[vv,W.EncoderOnly],[yv,W.EncoderOnly],[iv,W.EncoderOnly],[lv,W.EncoderOnly],[dv,W.MaskGeneration],[fv,W.EncoderOnly],[hv,W.EncoderOnly],[Xw,W.Seq2Seq],[Yw,W.EncoderOnly],[_v,W.EncoderOnly],[pv,W.EncoderOnly],[bv,W.EncoderOnly]];for(let[e,t]of Mv)for(let r of e.values()){hr.set(r,t);let n=xl[r];En.set(n,r),yl.set(r,n)}var Y3=[["MusicgenForConditionalGeneration",mw,W.Musicgen],["Phi3VForCausalLM",yw,W.Phi3V],["CLIPTextModelWithProjection",Lg,W.EncoderOnly],["SiglipTextModel",Sw,W.EncoderOnly],["JinaCLIPTextModel",aw,W.EncoderOnly],["ClapTextModelWithProjection",Fg,W.EncoderOnly],["ClapAudioModelWithProjection",Ig,W.EncoderOnly],["DacEncoderModel",Dg,W.EncoderOnly],["DacDecoderModel",zg,W.EncoderOnly],["MimiEncoderModel",hw,W.EncoderOnly],["MimiDecoderModel",_w,W.EncoderOnly],["SnacEncoderModel",Pw,W.EncoderOnly],["SnacDecoderModel",Fw,W.EncoderOnly],["Gemma3nForConditionalGeneration",Ba,W.ImageAudioTextToText],["Gemma4ForConditionalGeneration",rc,W.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ow,W.Supertonic],["ChatterboxModel",Cg,W.Chatterbox],["EmbeddingGemma2Model",qg,W.MultimodalEncoder],["VoxtralRealtimeForConditionalGeneration",Uw,W.VoxtralRealtime]];for(let[e,t,r]of Y3)hr.set(e,r),En.set(t,e),yl.set(e,t);var xv=new Map([["modnet",bn],["birefnet",bn],["isnet",bn],["ben",bn]]);for(let[e,t]of xv.entries())t.set(e,"PreTrainedModel"),hr.set(e,W.EncoderOnly),yl.set(e,I);var K3=new Set(xv.keys());hr.set("PreTrainedModel",W.EncoderOnly);En.set(I,"PreTrainedModel");var Se={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Kw,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Jw,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Xw,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Yw,MODEL_FOR_MASKED_LM_MAPPING_NAMES:tv,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:rv,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:ov,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:bn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:cv,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:uv,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:iv,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:lv,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:dv,MODEL_FOR_CTC_MAPPING_NAMES:fv,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:hv,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:_v,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:pv,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:Q3,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:mv,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:gv,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:wv,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:vv,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:yv,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:bv,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:sv,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:av,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Zw,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Qw,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:ev,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:nv};RC(Se);var Pe=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:f={}}={}){let _={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:f};if(_.config=await fs.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=_.config;for(let w of this.MODEL_CLASS_MAPPINGS){let v=w.get(p);if(!v){for(let y of w.values())if(y[0]===p){v=y;break}if(!v)continue}return await xl[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL){if(!K3.has(p))ce.warn(`Unknown model class "${p}", attempting to construct from base class.`);return await I.from_pretrained(e,_)}else throw Error(`Unsupported model type: ${p}`)}},os=class extends Pe{static MODEL_CLASS_MAPPINGS=Mv.map((e)=>e[0]);static BASE_IF_FAIL=!0},Ap=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},J3=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Fi=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Z3=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},eD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},tD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},rD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},nD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},sD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},aD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},oD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Cp=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Sp=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Pp=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},iD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},lD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},Yz=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},cD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_CTC_MAPPING_NAMES]},uD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},Kz=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},Jz=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},dD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},Zz=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},fD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},hD=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},eB=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},tB=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},_D=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},rB=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},nB=class extends Pe{static MODEL_CLASS_MAPPINGS=[Se.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Qt(e){if(!Array.isArray(e))e=[e];return await Promise.all(e.map((t)=>Vt.read(t)))}async function Mn(e,t){if(!Array.isArray(e))e=[e];return await Promise.all(e.map((r)=>{if(typeof r==="string"||r instanceof URL)return HE(r,t);else if(r instanceof Float64Array)return new Float32Array(r);return r}))}function Wi(e,t){if(t)e=e.map((o)=>o|0);let[r,n,s,a]=e;return{xmin:r,ymin:n,xmax:s,ymax:a}}var je=class extends mt{constructor({task:e,model:t,tokenizer:r=null,processor:n=null}){super();this.task=e,this.model=t,this.tokenizer=r,this.processor=n}async dispose(){await this.model.dispose()}},pD=class extends je{async _call(e,{top_k:t=1}={}){let r=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(r),{problem_type:s,id2label:a}=this.model.config,o=s==="multi_label_classification"?(l)=>l.sigmoid():(l)=>new U("float32",st(l.data),l.dims),i=[];for(let l of n.logits){let c=o(l),d=await Pn(c,t),f=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:a?a[w]:`LABEL_${w}`,score:f[v]}));if(t===1)i.push(...p);else i.push(p)}return Array.isArray(e)||t===1?i:i[0]}},mD=class extends je{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:r="none"}={}){if(r!=="none"&&r!=="simple")throw Error(`Invalid aggregation_strategy: "${r}". Must be one of "none" or "simple".`);let n=Array.isArray(e),s=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),o=(await this.model(s)).logits,i=this.model.config.id2label,l=[];for(let c=0;c<o.dims[0];++c){let d=s.input_ids[c].tolist(),f=o[c],_=[];for(let p=0;p<f.dims[0];++p){let w=f[p],v=qe(w.data)[1],y=i?i[v]:`LABEL_${v}`;if(t.includes(y))continue;let b=this.tokenizer.decode([d[p]],{skip_special_tokens:!0});if(b==="")continue;let k=st(w.data);_.push({entity:y,score:k[v],index:p,word:b})}l.push(r==="simple"?wD(_,d,this.tokenizer):_)}return n?l:l[0]}};function gD(e){let t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function wD(e,t,r){let n=[],s=null;for(let a=0;a<e.length;++a){let[o,i]=gD(e[a].entity);if(s===i&&o!=="B"&&o!=="S"){if(n[n.length-1].end=a+1,o==="E")s=null}else n.push({tag:i,start:a,end:a+1}),s=o==="S"?null:i}return n.map(({tag:a,start:o,end:i})=>{let l=0,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 vD=class extends je{async _call(e,t,{top_k:r=1}={}){let n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),s=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(n),i=n.input_ids.tolist(),l=n.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,f=[];for(let _=0;_<a.dims[0];++_){let p=i[_],w=p.findIndex((C)=>C==d),v=a[_].tolist(),y=o[_].tolist();for(let C=1;C<v.length;++C)if(l[_]==0||C<=w||c.findIndex((N)=>N==p[C])!==-1)v[C]=-1/0,y[C]=-1/0;let b=st(v).map((C,N)=>[C,N]),k=st(y).map((C,N)=>[C,N]);b[0][0]=0,k[0][0]=0;let A=AM(b,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,N)=>N[2]-C[2]),E=[];for(let C=0;C<Math.min(A.length,r);++C){let[N,M,G]=A[C],R=p.slice(N,M+1),q=this.tokenizer.decode(R,{skip_special_tokens:!0});E.push({answer:q,score:G})}if(r===1)f.push(...E);else f.push(E)}return s?f:f[0]}},yD=class extends je{async _call(e,{top_k:t=5}={}){let{mask_token_id:r,mask_token:n}=this.tokenizer,s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(s),o=[],i=s.input_ids.tolist();for(let l=0;l<i.length;++l){let c=i[l],d=c.findIndex((v)=>v==r);if(d===-1)throw Error(`Mask token (${n}) not found in text.`);let f=a[l][d],_=await Pn(new U("float32",st(f.data),f.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((v,y)=>{let b=c.slice();return b[d]=v,{score:p[y],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(b,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Iu=class extends je{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,t={}){if(!Array.isArray(e))e=[e];if(this.model.config.prefix)e=e.map((i)=>this.model.config.prefix+i);let r=this.model.config.task_specific_params;if(r&&r[this.task]){if(r[this.task].prefix)e=e.map((i)=>r[this.task].prefix+i)}let n=this.tokenizer,s={padding:!0,truncation:!0},a;if(this.task==="translation"&&"_build_translation_inputs"in n)a=n._build_translation_inputs(e,s,t);else a=n(e,s);let o=await this.model.generate({...a,...this._default_generation_config,...t});return n.batch_decode(o,{skip_special_tokens:!0}).map((i)=>({[this._key]:i}))}},bD=class extends Iu{_key="summary_text"},MD=class extends Iu{_key="translation_text"};function Fp(e){return Array.isArray(e)&&e.every((t)=>("role"in t)&&("content"in t))}var xD=class extends je{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:r,return_full_text:n,tools:s,documents:a,chat_template:o,tokenizer_encode_kwargs:i,...l}=t,c=!1,d=!1,f=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(Fp(e))e=[e];else if(Array.isArray(e)&&e.every(Fp))c=!0;else throw Error("Input must be a string, an array of strings, a Chat, or an array of Chats");d=!0;let E={tokenize:!1,add_generation_prompt:!0,...et({tools:s,documents:a,chat_template:o},["tools","documents","chat_template"]),..._};p=e.map((C)=>this.tokenizer.apply_chat_template(C,E)),f=!1,_=void 0}let w=d?!1:n??!0;this.tokenizer.padding_side="left";let v=this.tokenizer(p,{add_special_tokens:f,padding:!0,truncation:!0,..._}),y=await this.model.generate({...v,...this._default_generation_config,...l}),b=this.tokenizer.batch_decode(y,{skip_special_tokens:!0}),k;if(!w&&v.input_ids.dims.at(-1)>0)k=this.tokenizer.batch_decode(v.input_ids,{skip_special_tokens:!0}).map((E)=>E.length);let A=Array.from({length:e.length},(E)=>[]);for(let E=0;E<b.length;++E){let C=Math.floor(E/y.dims[0]*e.length);if(k)b[E]=b[E].slice(k[C]);A[C].push({generated_text:d?[...e[C],{role:"assistant",content:b[E]}]:b[E]})}return!c&&A.length===1?A[0]:A}},kD=class extends je{constructor(e){super(e);if(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)ce.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2;if(this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0)ce.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:n=!1}={}){let s=Array.isArray(e);if(!s)e=[e];if(!Array.isArray(t))t=[t];let a=t.map((l)=>r.replace("{}",l)),o=n||t.length===1,i=[];for(let l of e){let c=[];for(let _ of a){let p=this.tokenizer(l,{text_pair:_,padding:!0,truncation:!0}),w=await this.model(p);if(o)c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]);else c.push(w.logits.data[this.entailment_id])}let f=(o?c.map((_)=>st(_)[1]):st(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:f.map((_)=>t[_[1]]),scores:f.map((_)=>_[0])})}return s?i:i[0]}},TD=class extends je{async _call(e,{top_k:t=5}={}){let r=this.processor.feature_extractor.config.sampling_rate,n=await Mn(e,r),s=this.model.config.id2label,a=[];for(let o of n){let i=await this.processor(o),c=(await this.model(i)).logits[0],d=await Pn(new U("float32",st(c.data),c.dims),t),f=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:s?s[w]:`LABEL_${w}`,score:f[v]}));a.push(p)}return Array.isArray(e)?a:a[0]}},ED=class extends je{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){let n=!Array.isArray(e);if(n)e=[e];let s=t.map((c)=>r.replace("{}",c)),a=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await Mn(e,o),l=[];for(let c of i){let d=await this.processor(c),f=await this.model({...a,...d}),_=st(f.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})))}return n?l[0]:l}},AD=class extends je{_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 Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){if(t.language)ce.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');if(t.task)ce.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await Mn(n,s),o=[];for(let i of a){let l=await this.processor(i),d=(await this.model(l)).logits[0],f=[];for(let p of d)f.push(qe(p.data)[1]);let _=this.tokenizer.decode(f,{skip_special_tokens:!0}).trim();o.push({text:_})}return r?o[0]:o}async _call_whisper(e,t){let r=t.return_timestamps??!1,n=t.chunk_length_s??0,s=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};if(r==="word")o.return_token_timestamps=!0,o.return_timestamps=!0;let i=!Array.isArray(e),l=i?[e]:e,c=this.processor.feature_extractor.config,d=c.chunk_length/this.model.config.max_source_positions,{hop_length:f,sampling_rate:_}=c,p=await Mn(l,_),w=[];for(let v of p){let y=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let A=_*n,E=_*a,C=A-2*E,N=0;while(!0){let M=N+A,G=v.subarray(N,M),R=await this.processor(G),q=N===0,X=M>=v.length;if(y.push({stride:[G.length,q?0:E,X?0:E],input_features:R.input_features,is_last:X}),X)break;N+=C}}else y=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(let A of y){o.num_frames=Math.floor(A.stride[0]/f);let E=await this.model.generate({inputs:A.input_features,...o});if(r==="word"){let C=E.sequences.tolist()[0],N=E.token_timestamps.tolist()[0],M=this.tokenizer.timestamp_begin,G=Math.max(C.findIndex((R)=>Number(R)>=M),0);A.tokens=C.slice(G),A.token_timestamps=N.slice(G).map((R)=>as(R,2))}else A.tokens=E[0].tolist();A.stride=A.stride.map((C)=>C/_)}let[b,k]=this.tokenizer._decode_asr(y,{time_precision:d,return_timestamps:r,force_full_sequences:s});w.push({text:b,...k})}return i?w[0]:w}async _call_moonshine(e,t){let r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await Mn(n,s),o=[];for(let i of a){let l=await this.processor(i),c=Math.floor(i.length/s)*6,d=await this.model.generate({max_new_tokens:c,...t,...l}),f=this.tokenizer.batch_decode(d,{skip_special_tokens:!0})[0];o.push({text:f})}return r?o[0]:o}async _call_cohere_asr(e,t){let r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor,a=s.config.sampling_rate,o=await Mn(n,a),i=t.language??"en",l=this.processor.get_decoder_prompt_ids(i),c=[];for(let d of o){let f=s.split_audio(d),_=[];for(let w of f){let v=await this.processor(w),y=await this.model.generate({...v,decoder_input_ids:l,...t}),b=this.tokenizer.decode(y[0].tolist(),{skip_special_tokens:!0}).trim();_.push(b)}let p=this.processor.constructor.join_chunks(_,i);c.push({text:p})}return r?c[0]:c}},CD=class extends je{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 ve.fetch(e)).arrayBuffer());if(e instanceof Float32Array)e=new U("float32",e,[e.length]);else if(!(e instanceof U))throw 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 Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,r,n=null){let s=t.data,[a,o]=t.dims,i=n?n.data:null,l=[];for(let c=0;c<a;++c){let d=i?Math.min(Math.ceil(i[c]),o):o,f=c*o;l.push(new n2(s.slice(f,f+d),r))}return Array.isArray(e)?l:l[0]}async _call(e,t){if(this.processor)return this._call_text_to_spectrogram(e,t);else if(this.model.config.model_type==="supertonic")return this._call_supertonic(e,t);else return this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:r,speed:n}){if(!t)throw Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:s,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);let{waveform:l,durations:c}=await this.model.generate_speech({...o,style:t,num_inference_steps:r,speed:n});return this._postprocess_waveform(e,l,s,c)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(t),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,r,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(!this.vocoder)ce.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await os.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"});let{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),n=r.dims[0];t=await this._prepare_speaker_embeddings(t,n),t=t.view(n,-1);let{waveform:s}=await this.model.generate_speech(r,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,s,a)}},SD=class extends je{async _call(e,t={}){let r=Array.isArray(e),n=await Qt(e),{pixel_values:s}=await this.processor(n),a=[];for(let o of s){o.dims=[1,...o.dims];let 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]}},PD=class extends je{async _call(e,{top_k:t=5}={}){let r=await Qt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),{id2label:a}=this.model.config,o=[];for(let i of s.logits){let l=await Pn(new U("float32",st(i.data),i.dims),t),c=l[0].tolist(),f=l[1].tolist().map((_,p)=>({label:a?a[_]:`LABEL_${_}`,score:c[p]}));o.push(f)}return Array.isArray(e)?o:o[0]}},Ip={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},kv=class extends je{async _call(e,{threshold:t=0.5,mask_threshold:r=0.5,overlap_mask_area_threshold:n=0.8,label_ids_to_fuse:s=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let l=await Qt(e),c=l.map((b)=>[b.height,b.width]),d=await this.processor(l),{inputNames:f,outputNames:_}=this.model.sessions.model;if(!f.includes("pixel_values")){if(f.length!==1)throw Error(`Expected a single input name, but got ${f.length} inputs: ${f}.`);let b=f[0];if(b in d)throw Error(`Input name ${b} already exists in the inputs.`);d[b]=d.pixel_values}let p=await this.model(d),w=null;if(o!==null)w=Ip[o];else if(this.processor.image_processor){for(let[b,k]of Object.entries(Ip))if(k in this.processor.image_processor){w=this.processor.image_processor[k].bind(this.processor.image_processor),o=b;break}}let v=this.model.config.id2label,y=[];if(!o){let k=p[_[0]];for(let A=0;A<c.length;++A){let E=c[A],C=k[A];if(C.data.some((M)=>M<-0.00001||M>1.00001))C.sigmoid_();let N=await Vt.fromTensor(C.mul_(255).to("uint8")).resize(E[1],E[0]);y.push({label:null,score:null,mask:N})}}else if(o==="panoptic"||o==="instance"){let b=w(p,t,r,n,s,a??c)[0],k=b.segmentation;for(let A of b.segments_info){let E=new Uint8ClampedArray(k.data.length);for(let N=0;N<k.data.length;++N)if(k.data[N]===A.id)E[N]=255;let C=new Vt(E,k.dims[1],k.dims[0],1);y.push({score:A.score,label:v[A.label_id],mask:C})}}else if(o==="semantic"){let{segmentation:b,labels:k}=w(p,a??c)[0];for(let A of k){let E=new Uint8ClampedArray(b.data.length);for(let N=0;N<b.data.length;++N)if(b.data[N]===A)E[N]=255;let C=new Vt(E,b.dims[1],b.dims[0],1);y.push({score:null,label:v[A],mask:C})}}else throw Error(`Subtask ${o} not supported.`);return y}},FD=class extends kv{async _call(e,t={}){let r=await Qt(e),n=await super._call(e,t),s=r.map((a,o)=>{let i=a.clone();return i.putAlpha(n[o].mask),i});return Array.isArray(e)?s:s[0]}},ID=class extends je{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){let n=Array.isArray(e),s=await Qt(e),a=t.map((f)=>r.replace("{}",f)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(s),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?(f)=>f.sigmoid().data:(f)=>st(f.data),d=[];for(let f of l.logits_per_image){let p=[...c(f)].map((w,v)=>({score:w,label:t[v]}));p.sort((w,v)=>v.score-w.score),d.push(p)}return n?d:d[0]}},LD=class extends je{async _call(e,{threshold:t=0.9,percentage:r=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let s=await Qt(e),a=r?null:s.map((_)=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(s),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,f=c.map((_)=>_.boxes.map((p,w)=>({score:_.scores[w],label:d[_.classes[w]],box:Wi(p,!r)})));return n?f:f[0]}},OD=class extends je{async _call(e,t,{threshold:r=0.1,top_k:n=null,percentage:s=!1}={}){let a=Array.isArray(e),o=await Qt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){let f=o[d],_=s?null:[[f.height,f.width]],p=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:p}),v;if("post_process_grounded_object_detection"in this.processor){let y=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];v=y.boxes.map((b,k)=>({score:y.scores[k],label:y.labels[k],box:Wi(b,!s)}))}else{let y=this.processor.image_processor.post_process_object_detection(w,r,_,!0)[0];v=y.boxes.map((b,k)=>({score:y.scores[k],label:t[y.classes[k]],box:Wi(b,!s)}))}if(v.sort((y,b)=>b.score-y.score),n!==null)v=v.slice(0,n);c.push(v)}return a?c:c[0]}},ND=class extends je{_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]}let n=(await Qt(e))[0],{pixel_values:s}=await this.processor(n),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:s,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>/),d=null;if(c&&c.length>=2)d=c[1].trim();return[{answer:d}]}},DD=class extends je{async _call(e){let t=await Qt(e),r=await this.processor(t),n=await this.model(r),s=[];for(let a of n.reconstruction){let o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(Vt.fromTensor(o))}return Array.isArray(e)?s:s[0]}},zD=class extends je{async _call(e){let t=await Qt(e),r=await this.processor(t),{predicted_depth:n}=await this.model(r),s=[];for(let a=0;a<t.length;++a){let o=n[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,f=(await Gt(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=f.min().item(),p=f.max().item(),w=f.sub(_).div_(p-_).mul_(255).to("uint8").unsqueeze(0),v=Vt.fromTensor(w);s.push({predicted_depth:f,depth:v})}return Array.isArray(e)?s:s[0]}},BD=class extends je{async _call(e,{pooling:t="none",normalize:r=!1,quantize:n=!1,precision:s="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a),i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=RT(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.`)}if(r)i=i.normalize(2,-1);if(n)i=VT(i,s);return i}},RD=class extends je{async _call(e,{pool:t=null}={}){let r=await Qt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),a;if(t){if(!("pooler_output"in s))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=s.pooler_output}else a=s.last_hidden_state??s.logits??s.image_embeds;return a}},ka=Object.freeze({"text-classification":{pipeline:pD,model:Ap,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:mD,model:J3,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:vD,model:sD,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:yD,model:nD,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:bD,model:Fi,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:MD,model:Fi,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Iu,model:Fi,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:xD,model:rD,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:kD,model:Ap,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:TD,model:uD,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:ED,model:os,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:AD,model:[Z3,cD],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:CD,model:[tD,eD],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:SD,model:aD,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:PD,model:oD,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:kv,model:[Cp,Sp,Pp],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:FD,model:[Cp,Sp,Pp],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:ID,model:os,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:LD,model:iD,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:OD,model:lD,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:ND,model:dD,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:DD,model:fD,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:zD,model:hD,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:BD,model:os,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:RD,model:[_D,os],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),Tv=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $D(e){if(!e)throw Error("modelId is required");return(await ms(e,ds,{})).exists?[ds]:[]}async function GD(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null,include_tokenizer:a=!0,include_processor:o=!0}={}){let i=await yg(e,{config:t,dtype:r,device:n,model_file_name:s});if(a){let l=await km(e);i.push(...l)}if(o){let l=await $D(e);i.push(...l)}return i}async function VD(e,t,r={}){e=Tv[e]??e;let n=ka[e];if(!n)throw Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(ka).join(", ")}]`);let{type:s}=n,i=await GD(t,{...r,include_tokenizer:s!=="audio"&&s!=="image",include_processor:s!=="text"});if(e==="text-generation"){let l=await vg(t,r),c=wg(l),d=zC(c);if(d){let f=Object.values(d).map((_)=>`onnx/${_}`);return i.filter((_)=>!_.startsWith("onnx/")||f.some((p)=>_.startsWith(p)))}}return i}async function sB(e,t=null,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:f=null,session_options:_={}}={}){e=Tv[e]??e;let p=ka[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(ka)}]`);if(!t){if(t=p.default.model,ce.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype)l=p.default.dtype}let w=await VD(e,t,{device:i,dtype:l}),v={};if(r)try{(await Promise.all(w.map(async(X)=>ms(t,X)))).forEach((X,Q)=>{if(X.exists)v[w[Q]]={loaded:0,total:X.size??0}})}catch(q){ce.warn(`Unable to fetch model file metadata for total progress tracking: ${q}`)}let y={progress_callback:r?new da(r,v):void 0,config:n,cache_dir:s,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:f,session_options:_},b=w.includes("tokenizer.json"),k=w.includes("preprocessor_config.json"),A=p.model,E;if(Array.isArray(A)){let q=n??await fs.from_pretrained(t,y),{model_type:X}=q,Q=A.find((H)=>H.supports(X));if(!Q)throw Error(`Unsupported model type "${X}" for task "${e}". None of the candidate model classes support this type.`);E=Q.from_pretrained(t,{...y,config:q})}else E=A.from_pretrained(t,y);let[C,N,M]=await Promise.all([b?Te.from_pretrained(t,y):null,k?lC.from_pretrained(t,y):null,E]),G={task:e,model:M};if(C)G.tokenizer=C;if(N)G.processor=N;return Pr(r,{status:"ready",task:e,model:t}),new p.pipeline(G)}var UD=(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,jD=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},Lp=pe.IS_PROCESS_AVAILABLE?(e)=>process.stdout.write(e):(e)=>console.log(e),aB=class extends jD{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,skip_special_tokens:s=!0,decode_kwargs:a={},...o}={}){super();this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??Lp,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:s,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let t=this.next_tokens_are_prompt;if(t){if(this.next_tokens_are_prompt=!1,this.skip_prompt)return}let r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let i=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(i,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=Bt(this.token_cache,r);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),s;if(t||n.endsWith(`
|
|
45
|
+
`))s=n.slice(this.print_len),this.token_cache=[],this.print_len=0;else if(n.length>0&&UD(n.charCodeAt(n.length-1)))s=n.slice(this.print_len),this.print_len+=s.length;else s=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=s.length;this.on_finalized_text(s,!1)}end(){let e;if(this.token_cache.length>0)e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0;else e="";this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){if(e.length>0)this.callback_function?.(e);if(t&&this.callback_function===Lp&&pe.IS_PROCESS_AVAILABLE)this.callback_function?.(`
|
|
46
|
+
`)}};var oB=Object.keys(ba);export{Xz as InterruptableStoppingCriteria,gg as StoppingCriteriaList,aB as TextStreamer,sB as pipeline};
|