bf2f59e292
Built from main 4ae9c5ffef
Merge branch 'refactor/task-21-batch1-corrections'
43 lines
493 KiB
JavaScript
43 lines
493 KiB
JavaScript
(function(){"use strict";/*!
|
||
* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0
|
||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||
* Licensed under the MIT License.
|
||
*/var zn=Object.defineProperty,yf=Object.getOwnPropertyDescriptor,Mf=Object.getOwnPropertyNames,bf=Object.prototype.hasOwnProperty,xf=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Z=(e,t,s)=>()=>{if(s)throw s[0];try{return e&&(t=e(e=0)),t}catch(r){throw s=[r],r}},Er=(e,t)=>{for(var s in t)zn(e,s,{get:t[s],enumerable:!0})},kf=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Mf(t))!bf.call(e,n)&&n!==s&&zn(e,n,{get:()=>t[n],enumerable:!(r=yf(t,n))||r.enumerable});return e},Dn=e=>kf(zn({},"__esModule",{value:!0}),e),Xs,Lt,Qt,jl,ql,Wl=Z(()=>{"use strict";Xs=new Map,Lt=[],Qt=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let r=Xs.get(e);if(r===void 0)Xs.set(e,{backend:t,priority:s});else{if(r.priority>s)return;if(r.priority===s&&r.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let n=Lt.indexOf(e);n!==-1&&Lt.splice(n,1);for(let a=0;a<Lt.length;a++)if(Xs.get(Lt[a]).priority<=s){Lt.splice(a,0,e);return}Lt.push(e)}return}throw new TypeError("not a valid backend")},jl=async e=>{let t=Xs.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(r){return s||(t.error=`${r}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ql=async e=>{let t=e.executionProviders||[],s=t.map(l=>typeof l=="string"?l:l.name),r=s.length===0?Lt:s,n,a=[],o=new Set;for(let l of r){let c=await jl(l);typeof c=="string"?a.push({name:l,err:c}):(n||(n=c),n===c&&o.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)s.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Ef=Z(()=>{"use strict";Wl()}),Hl,Tf=Z(()=>{"use strict";Hl="1.31.0-dev.20260911-2a43ec07e"}),Bn,Fe,Ql=Z(()=>{"use strict";Tf(),Bn="warning",Fe={wasm:{},webgl:{},webgpu:{},versions:{common:Hl},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Bn=e}},get logLevel(){return Bn}},Object.defineProperty(Fe,"logLevel",{enumerable:!0})}),me,Af=Z(()=>{"use strict";Ql(),me=Fe}),Xl,Yl,Cf=Z(()=>{"use strict";Xl=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let r=s.getContext("2d");if(r!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*n,u=0,_=d,h=d*2,p=-1;o==="RGBA"?(u=0,_=d,h=d*2,p=d*3):o==="RGB"?(u=0,_=d,h=d*2):o==="RBG"&&(u=0,h=d,_=d*2);for(let f=0;f<a;f++)for(let g=0;g<n;g++){let m=(e.data[u++]-c[0])*l[0],w=(e.data[_++]-c[1])*l[1],y=(e.data[h++]-c[2])*l[2],v=p===-1?255:(e.data[p++]-c[3])*l[3];r.fillStyle="rgba("+m+","+w+","+y+","+v+")",r.fillRect(g,f,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Yl=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(s!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let u=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,h=0,p=1,f=2,g=3,m=0,w=u,y=u*2,v=-1;i==="RGBA"?(m=0,w=u,y=u*2,v=u*3):i==="RGB"?(m=0,w=u,y=u*2):i==="RBG"&&(m=0,y=u,w=u*2),r=s.createImageData(n,a);for(let M=0;M<a*n;h+=_,p+=_,f+=_,g+=_,M++)r.data[h]=(e.data[m++]-d[0])*c[0],r.data[p]=(e.data[w++]-d[1])*c[1],r.data[f]=(e.data[y++]-d[2])*c[2],r.data[g]=v===-1?255:(e.data[v++]-d[3])*c[3]}else throw new Error("Can not access image data");return r}}),Tr,Kl,Jl,Zl,ec,tc,Sf=Z(()=>{"use strict";$n(),Tr=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:r}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=s*r,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),u=4,_=0,h=1,p=2,f=3,g=0,m=c,w=c*2,y=-1;i==="RGB"&&(u=3,_=0,h=1,p=2,f=-1),l==="RGBA"?y=c*3:l==="RBG"?(g=0,w=c,m=c*2):l==="BGR"&&(w=0,m=c,g=c*2);for(let v=0;v<c;v++,_+=u,p+=u,h+=u,f+=u)d[g++]=(e[_]+o[0])/a[0],d[m++]=(e[h]+o[1])/a[1],d[w++]=(e[p]+o[2])/a[2],y!==-1&&f!==-1&&(d[y++]=(e[f]+o[3])/a[3]);return l==="RGBA"?new We("float32",d,[1,4,s,r]):new We("float32",d,[1,3,s,r])},Kl=async(e,t)=>{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(s){let d=l();d.width=e.width,d.height=e.height;let u=c(d);if(u!=null){let _=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=h}else i.tensorFormat="RGBA",i.height=_,i.width=h;u.drawImage(e,0,0),o=u.getImageData(0,0,h,_).data}else throw new Error("Can not access image data")}else if(r){let d,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,u=t.resizedWidth):(d=e.height,u=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=u,t!==void 0){let _=l();_.width=u,_.height=d;let h=c(_);if(h!=null)h.putImageData(e,0,0),o=h.getImageData(0,0,u,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let u=c(d);if(u!=null){let _=e.height,h=e.width;return u.drawImage(e,0,0,h,_),o=u.getImageData(0,0,h,_).data,i.height=_,i.width=h,Tr(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,u)=>{let _=l(),h=c(_);if(!e||!h)return u();let p=new Image;p.crossOrigin="Anonymous",p.src=e,p.onload=()=>{_.width=p.width,_.height=p.height,h.drawImage(p,0,0,_.width,_.height);let f=h.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(Tr(f.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Tr(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Jl=(e,t)=>{let{width:s,height:r,download:n,dispose:a}=t,o=[1,r,s,4];return new We({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Zl=(e,t)=>{let{dataType:s,dims:r,download:n,dispose:a}=t;return new We({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:r,download:n,dispose:a})},ec=(e,t)=>{let{dataType:s,dims:r,download:n,dispose:a}=t;return new We({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:r,download:n,dispose:a})},tc=(e,t,s)=>new We({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Xt,Ys,Rn,sc,Pf=Z(()=>{"use strict";Xt=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ys=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Rn=!1,sc=()=>{if(!Rn){Rn=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,r=typeof s<"u"&&s.from;e&&(Xt.set("int64",BigInt64Array),Ys.set(BigInt64Array,"int64")),t&&(Xt.set("uint64",BigUint64Array),Ys.set(BigUint64Array,"uint64")),r?(Xt.set("float16",s),Ys.set(s,"float16")):Xt.set("float16",Uint16Array)}}}),rc,nc,Ff=Z(()=>{"use strict";$n(),rc=e=>{let t=1;for(let s=0;s<e.length;s++){let r=e[s];if(typeof r!="number"||!Number.isSafeInteger(r))throw new TypeError(`dims[${s}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${r}`);t*=r}return t},nc=(e,t)=>{switch(e.location){case"cpu":return new We(e.type,e.data,t);case"cpu-pinned":return new We({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new We({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new We({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new We({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),We,$n=Z(()=>{"use strict";Cf(),Sf(),Pf(),Ff(),We=class{constructor(e,t,s){sc();let r,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,r=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=Xt.get(r);if(!o)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="uint64"&&r!=="int8"&&r!=="uint8"&&r!=="bool"&&r!=="uint4"&&r!=="int4")throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e=="string")if(r=e,i=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Xt.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${r} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")r="string",o=e;else if(l==="boolean")r="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)r="uint8",o=Uint8Array.from(e);else{let l=Ys.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=o,this.dataLocation="cpu"}let a=rc(n);if(this.cpuData&&a!==this.cpuData.length&&!((r==="uint4"||r==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=n,this.size=a}static async fromImage(e,t){return Kl(e,t)}static fromTexture(e,t){return Jl(e,t)}static fromGpuBuffer(e,t){return Zl(e,t)}static fromMLTensor(e,t){return ec(e,t)}static fromPinnedBuffer(e,t,s){return tc(e,t,s)}toDataURL(e){return Xl(this,e)}toImageData(e){return Yl(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return nc(this,e)}}}),nt,ac=Z(()=>{"use strict";$n(),nt=We}),Ar,Gn,Yt,Kt,Ot,Nt,oc=Z(()=>{"use strict";Ql(),Ar=(e,t)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.timeStamp(`${e}::ORT::${t}`)},Gn=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let n=0;n<s.length;n++){if(r&&!s[n].includes("TRACE_FUNC")){let a=`FUNC_${e}::${s[n].trim().split(" ")[1]}`;t&&(a+=`::${t}`),Ar("CPU",a);return}s[n].includes("TRACE_FUNC")&&(r=!0)}},Yt=e=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||Gn("BEGIN",e)},Kt=e=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||Gn("END",e)},Ot=e=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.time(`ORT::${e}`)},Nt=e=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.timeEnd(`ORT::${e}`)}}),ic,If=Z(()=>{"use strict";Wl(),ac(),oc(),ic=class ff{constructor(t){this.handler=t}async run(t,s,r){Yt(),Ot("InferenceSession.run");let n={},a={};if(typeof t!="object"||t===null||t instanceof nt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof nt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let c of s){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(s);for(let u of this.outputNames)if(d.indexOf(u)!==-1){let _=s[u];(_===null||_ instanceof nt)&&(c=!0,o=!1,n[u]=_)}if(c){if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(t,n,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof nt?l[c]=d:l[c]=new nt(d.type,d.data,d.dims)}return Nt("InferenceSession.run"),Kt(),l}async release(){return this.handler.dispose()}static async create(t,s,r,n){Yt(),Ot("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,u=0,_=t.byteLength;if(typeof s=="object"&&s!==null)o=s;else if(typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-u,typeof r=="number"){if(_=r,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||u+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-u}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(d,u,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await ql(o),c=await i.createInferenceSessionHandler(a,l);return Nt("InferenceSession.create"),Kt(),new ff(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}}}),Vn,Lf=Z(()=>{"use strict";If(),Vn=ic}),Of=Z(()=>{"use strict"}),Nf=Z(()=>{"use strict"}),zf=Z(()=>{"use strict"}),Df=Z(()=>{"use strict"}),lc={};Er(lc,{InferenceSession:()=>Vn,TRACE:()=>Ar,TRACE_EVENT_BEGIN:()=>Ot,TRACE_EVENT_END:()=>Nt,TRACE_FUNC_BEGIN:()=>Yt,TRACE_FUNC_END:()=>Kt,Tensor:()=>nt,env:()=>me,registerBackend:()=>Qt});var Jt=Z(()=>{"use strict";Ef(),Af(),Lf(),ac(),Of(),Nf(),oc(),zf(),Df()}),Un=Z(()=>{"use strict"}),cc={};Er(cc,{default:()=>dc});var jn,qn,dc,Bf=Z(()=>{"use strict";Wc(),Zt(),Kn(),jn="ort-wasm-proxy-worker",qn=globalThis.self?.name===jn,qn&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":ea(s.wasm).then(()=>{_a(s).then(()=>{postMessage({type:t})},r=>{postMessage({type:t,err:r})})},r=>{postMessage({type:t,err:r})});break;case"init-ep":{let{epName:r,env:n}=s;ha(n,r).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:r}=s,n=Lr(r);postMessage({type:t,out:n});break}case"create":{let{model:r,options:n}=s;fa(r,n).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":ma(s),postMessage({type:t});break;case"run":{let{sessionId:r,inputIndices:n,inputs:a,outputIndices:o,options:i}=s;wa(r,n,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},ya([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":va(s),postMessage({type:t});break;default:}}catch(r){postMessage({type:t,err:r})}}),dc=qn?null:e=>new Worker(e??He,{type:"module",name:jn})}),Wn,uc,_c,He,Hn,Cr,hc,pc,Qn,fc,Xn,mc,Yn,gc,Kn=Z(()=>{"use strict";Un(),Wn=typeof location>"u"?void 0:location.origin,uc=self.location.href>"file:"&&self.location.href<"file;",_c=()=>{if(uc){let e=URL;return new URL(new e("ort.webgpu.min.mjs",self.location.href).href,Wn).href}return self.location.href},He=_c(),Hn=()=>{if(He&&!He.startsWith("blob:"))return He.substring(0,He.lastIndexOf("/")+1)},Cr=(e,t)=>{try{let s=t??He;return(s?new URL(e,s):new URL(e)).origin===Wn}catch{return!1}},hc=(e,t)=>{let s=t??He;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},pc=(e,t)=>`${t??"./"}${e}`,Qn=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},fc=async e=>(await import(e)).default,Xn=(Bf(),Dn(cc)).default,mc=async()=>{if(!He)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Cr(He))return[void 0,Xn()];let e=await Qn(He);return[e,Xn(e)]},Yn=void 0,gc=async(e,t,s,r)=>{let n=Yn&&!(e||t);if(n)if(He)n=Cr(He)||r&&!s;else if(r&&!s)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Yn];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??hc(a,t),i=s&&o&&!Cr(o,t),l=i?await Qn(o):o??pc(a,t);return[i?l:void 0,await fc(l)]}}}),Jn,Sr,Ks,Zn,wc,vc,yc,ea,ce,Zt=Z(()=>{"use strict";Kn(),Sr=!1,Ks=!1,Zn=!1,wc=()=>{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}},vc=()=>{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}},yc=()=>{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}},ea=async e=>{if(Sr)return Promise.resolve();if(Ks)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Zn)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ks=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!yc())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vc())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let r=wc();s>1&&!r&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", 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=s=1);let n=e.wasmPaths,a=typeof n=="string"?n:void 0,o=n?.mjs,i=o?.href??o,l=n?.wasm,c=l?.href??l,d=e.wasmBinary,[u,_]=await gc(i,a,s>1,!!d||!!c),h=!1,p=[];if(t>0&&p.push(new Promise(f=>{setTimeout(()=>{h=!0,f()},t)})),p.push(new Promise((f,g)=>{let m={numThreads:s};if(d)m.wasmBinary=d,m.locateFile=w=>w;else if(c||a)m.locateFile=w=>c??a+w;else if(i&&i.indexOf("blob:")!==0)m.locateFile=w=>new URL(w,i).href;else if(u){let w=Hn();w&&(m.locateFile=y=>w+y)}_(m).then(w=>{Ks=!1,Sr=!0,Jn=w,f(),u&&URL.revokeObjectURL(u)},w=>{Ks=!1,Zn=!0,g(w)})})),await Promise.race(p),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ce=()=>{if(Sr&&Jn)return Jn;throw new Error("WebAssembly is not initialized yet.")}}),Qe,Pr,re,ta=Z(()=>{"use strict";Zt(),Qe=(e,t)=>{let s=ce(),r=s.lengthBytesUTF8(e)+1,n=s._malloc(r);return s.stringToUTF8(e,n,r),t.push(n),n},Pr=(e,t,s,r)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([n,a])=>{let o=t?t+n:n;if(typeof a=="object")Pr(a,o+".",s,r);else if(typeof a=="string"||typeof a=="number")r(o,a.toString());else if(typeof a=="boolean")r(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},re=e=>{let t=ce(),s=t.stackSave();try{let r=t.PTR_SIZE,n=t.stackAlloc(2*r);t._OrtGetLastError(n,n+r);let a=Number(t.getValue(n,r===4?"i32":"i64")),o=t.getValue(n+r,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(s)}}}),Mc,Rf=Z(()=>{"use strict";Zt(),ta(),Mc=e=>{let t=ce(),s=0,r=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Qe(e.tag,r)),s=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,a),s===0&&re("Can't create run options."),e?.extra!==void 0&&Pr(e.extra,"",new WeakSet,(o,i)=>{let l=Qe(o,r),c=Qe(i,r);t._OrtAddRunConfigEntry(s,l,c)!==0&&re(`Can't set a run config entry: ${o} - ${i}.`)}),[s,r]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),r.forEach(o=>t._free(o)),a}}}),bc,xc,kc,us,gt,Ec,Tc,$f=Z(()=>{"use strict";Zt(),ta(),bc=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},xc=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},kc=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(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},us=(e,t,s,r)=>{let n=Qe(t,r),a=Qe(s,r);ce()._OrtAddSessionConfigEntry(e,n,a)!==0&&re(`Can't set a session config entry: ${t} - ${s}.`)},gt=(e,t,s,r)=>{let n=Qe(t,r),a=Qe(s,r);e.push([n,a])},Ec=async(e,t,s)=>{let r=t.executionProviders;for(let n of r){let a=typeof n=="string"?n:n.name,o=[];switch(a){case"webnn":if(a="WEBNN",us(e,"session.disable_quant_qdq","1",s),us(e,"session.disable_qdq_constant_folding","1",s),typeof n!="string"){let u=n?.deviceType;u&&us(e,"deviceType",u,s)}break;case"webgpu":{a="WebGPU";let u;if(typeof n!="string"){let h=n;if(h.device)if(typeof GPUDevice<"u"&&h.device instanceof GPUDevice)u=h.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:p}=t;if(typeof p=="boolean"&&p&>(o,"enableGraphCapture","1",s),typeof h.preferredLayout=="string"&>(o,"preferredLayout",h.preferredLayout,s),h.forceCpuNodeNames){let f=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];gt(o,"forceCpuNodeNames",f.join(`
|
||
`),s)}h.validationMode&>(o,"validationMode",h.validationMode,s),typeof h.enableMatmulFp32Accumulation=="boolean"&>(o,"enableMatmulFp32Accumulation",h.enableMatmulFp32Accumulation?"1":"0",s);for(let f of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let g=h[f];if(g){if(g!=="disabled"&&g!=="lazyRelease"&&g!=="simple"&&g!=="bucket")throw new Error(`${f} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${g}`);gt(o,f,g,s)}}}let _=ce().webgpuRegisterDevice(u);if(_){let[h,p,f]=_;gt(o,"deviceId",h.toString(),s),gt(o,"webgpuInstance",p.toString(),s),gt(o,"webgpuDevice",f.toString(),s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=Qe(a,s),l=o.length,c=0,d=0;if(l>0){c=ce()._malloc(l*ce().PTR_SIZE),s.push(c),d=ce()._malloc(l*ce().PTR_SIZE),s.push(d);for(let u=0;u<l;u++)ce().setValue(c+u*ce().PTR_SIZE,o[u][0],"*"),ce().setValue(d+u*ce().PTR_SIZE,o[u][1],"*")}await ce()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&re(`Can't append execution provider: ${a}.`)}},Tc=async e=>{let t=ce(),s=0,r=[],n=e||{};kc(n);try{let a=bc(n.graphOptimizationLevel??"all"),o=xc(n.executionMode??"sequential"),i=typeof n.logId=="string"?Qe(n.logId,r):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof n.optimizedModelFilePath=="string"?Qe(n.optimizedModelFilePath,r):0;if(s=t._OrtCreateSessionOptions(a,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,i,l,c,d),s===0&&re("Can't create session options."),n.executionProviders&&await Ec(s,n,r),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);us(s,"enableGraphCapture",n.enableGraphCapture.toString(),r)}if(n.freeDimensionOverrides)for(let[u,_]of Object.entries(n.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let h=Qe(u,r);t._OrtAddFreeDimensionOverride(s,h,_)!==0&&re(`Can't set a free dimension override: ${u} - ${_}.`)}return n.extra!==void 0&&Pr(n.extra,"",new WeakSet,(u,_)=>{us(s,u,_,r)}),[s,r]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&re("Can't release session options."),r.forEach(o=>t._free(o)),a}}}),es,Fr,_s,Js,Ir,sa,ra,na,hs=Z(()=>{"use strict";es=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Fr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},_s=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t=="number"?t:t.reduce((n,a)=>n*a,1);return s>0?Math.ceil(r*s):void 0},Js=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ir=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},sa=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ra=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",na=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),aa,Ac=Z(()=>{"use strict";Un(),aa=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),r=s?parseInt(s,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),a;try{a=new ArrayBuffer(r)}catch(i){if(i instanceof RangeError){let l=Math.ceil(r/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Cc,Gf=Z(()=>{"use strict";hs(),Cc=(e,t)=>new(Js(t))(e)}),Sc,Pc,Fc,Ic,Lc,Oc,Ve,Nc=Z(()=>{"use strict";hs(),Sc=["V","I","W","E","F"],Pc=(e,t)=>{console.log(`[${Sc[e]},${new Date().toISOString()}]${t}`)},Lc=(e,t)=>{Fc=e,Ic=t},Oc=(e,t)=>{let s=Ir(e),r=Ir(Fc);s>=r&&Pc(s,typeof t=="function"?t():t)},Ve=(...e)=>{Ic&&Oc(...e)}}),oa,zc,ia,Dc,la,Bc,ca,da,ua,Rc,$c,Vf=Z(()=>{"use strict";hs(),Nc(),oa=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),zc=(e,t)=>{if(t==="int32")return e;let s=oa.get(t);if(!s)throw new Error(`WebNN backend does not support data type: ${t}`);let r=s/8;if(e.byteLength%r!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let n=e.byteLength/r,a=new(Js(t))(e.buffer,e.byteOffset,n);switch(t){case"int64":case"uint64":{let o=new Int32Array(n);for(let i=0;i<n;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},ia=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let s=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,s);switch(t){case"int64":{let n=BigInt64Array.from(r,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(r.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(r,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(r.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(r,Number);return new Uint8Array(n.buffer)}case"uint8":{if(r.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(r,Number)}case"uint32":{if(r.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(r,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Dc=1,la=()=>Dc++,Bc=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),ca=(e,t)=>{let s=oa.get(e);if(!s)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((r,n)=>r*n)*s/8):0},da=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:s,tensor:r,dataType:n,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=s,this.mlTensor=r,this.dataType=n,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return ca(this.dataType,this.tensorShape)}destroy(){Ve("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),s=ia(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(s);return}else return new Uint8Array(s).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((r,n)=>r===s[n])}setIsDataConverted(e){this.isDataConverted=e}},ua=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,s,r){let n=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Bc.get(t),!o||!a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);Ve("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,s))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==ca(t,s))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,s,i,!0,!0,o),r&&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=zc(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ve("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?ia(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Rc=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=la();return this.tensorTrackersById.set(e,new ua(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,s,r,n){Ve("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${s}, shape: ${r}, copyOld: ${n}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,s,r,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){Ve("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.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,s,r){let n=this.getMLContext(e),a=la(),o=new da({sessionId:e,context:n,tensor:t,dataType:s,shape:r});return this.tensorTrackersById.set(a,new ua(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,s,r,n,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,s)){Ve("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${s}`);let u=this.freeTensors.splice(c,1)[0];return u.sessionId=e,u}Ve("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${s}}`);let l=await i.createTensor({dataType:o??t,shape:s,dimensions:s,usage:r,writable:n,readable:a});return new da({sessionId:e,context:i,tensor:l,dataType:t,shape:s,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$c=(...e)=>new Rc(...e)}),Gc={};Er(Gc,{WebNNBackend:()=>Uc});var Zs,Vc,Uc,Uf=Z(()=>{"use strict";hs(),Zt(),Gf(),Vf(),Nc(),Zs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Vc=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),r=Object.keys(t).sort();return s.length===r.length&&s.every((n,a)=>n===r[a]&&e[n]===t[n])},Uc=class{constructor(e){this.tensorManager=$c(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,Lc(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ve("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ve("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Ve("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(r=>r.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:r}),r}}else if(e===void 0){let s=this.mlContextCache.findIndex(r=>r.options===void 0&&r.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let r=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:r}),r}}let t=this.mlContextCache.findIndex(s=>Vc(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.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 s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let r=this.mlContextCache.findIndex(n=>n.mlContext===t);r!==-1&&this.mlContextCache.splice(r,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ve("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,r,n){let a=Zs.get(s);if(!a)throw new Error(`Unsupported ONNX data type: ${s}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,n)}async createTemporaryTensor(e,t,s){Ve("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let r=Zs.get(t);if(!r)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,r,s,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!ce().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ve("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 s=await this.tensorManager.download(e);return Cc(s,t)}}registerMLTensor(e,t,s,r){let n=Zs.get(s);if(!n)throw new Error(`Unsupported ONNX data type: ${s}`);let a=this.tensorManager.registerTensor(e,t,n,r);return Ve("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let s=this.sessionGraphInputs.get(e);return s?s.includes(t):!1}isGraphOutput(e,t){let s=this.sessionGraphOutputs.get(e);return s?s.includes(t):!1}isGraphInputOutputTypeSupported(e,t,s=!0){let r=Zs.get(es(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>"u"?!1:s?!!n?.input.dataTypes.includes(r):!!n?.output.dataTypes.includes(r)}flush(){}}}),jc,_a,ha,zt,qc,pa,Lr,fa,ma,ga,wa,va,ya,Wc=Z(()=>{"use strict";Jt(),Rf(),$f(),hs(),Zt(),ta(),Ac(),jc=(e,t)=>{ce()._OrtInit(e,t)!==0&&re("Can't initialize onnxruntime.")},_a=async e=>{jc(e.wasm.numThreads,Ir(e.logLevel))},ha=async(e,t)=>{ce().asyncInit?.();let s=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=e.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:n}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&ce().webgpuInit(r=>{e.webgpu.device=r}),t==="webnn"){let r=new(Uf(),Dn(Gc)).WebNNBackend(e);ce().webnnInit([r,()=>r.reserveTensorId(),n=>r.releaseTensorId(n),async(n,a,o,i,l)=>r.ensureTensor(n,a,o,i,l),(n,a)=>{r.uploadTensor(n,a)},async(n,a)=>r.downloadTensor(n,a),(n,a)=>r.registerMLContext(n,a),!!e.trace])}},zt=new Map,qc=e=>{let t=ce(),s=t.stackSave();try{let r=t.PTR_SIZE,n=t.stackAlloc(2*r);t._OrtGetInputOutputCount(e,n,n+r)!==0&&re("Can't get session input/output count.");let a=r===4?"i32":"i64";return[Number(t.getValue(n,a)),Number(t.getValue(n+r,a))]}finally{t.stackRestore(s)}},pa=(e,t)=>{let s=ce(),r=s.stackSave(),n=0;try{let a=s.PTR_SIZE,o=s.stackAlloc(2*a);s._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&re("Can't get session input/output metadata.");let i=Number(s.getValue(o,"*"));n=Number(s.getValue(o+a,"*"));let l=s.HEAP32[n/4];if(l===0)return[i,0];let c=s.HEAPU32[n/4+1],d=[];for(let u=0;u<c;u++){let _=Number(s.getValue(n+8+u*a,"*"));d.push(_!==0?s.UTF8ToString(_):Number(s.getValue(n+8+(u+c)*a,"*")))}return[i,l,d]}finally{s.stackRestore(r),n!==0&&s._OrtFree(n)}},Lr=e=>{let t=ce(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},fa=async(e,t)=>{let s,r,n=ce();Array.isArray(e)?[s,r]=e:e.buffer===n.HEAPU8.buffer?[s,r]=[e.byteOffset,e.byteLength]:[s,r]=Lr(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await Tc(t),t?.externalData&&n.mountExternalData){let v=[];for(let M of t.externalData){let E=typeof M=="string"?M:M.path,A=typeof M=="string"?M:M.data;v.push(aa(A).then(S=>{n.mountExternalData(E,S)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v=="string"?v:v.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof v!="string"){let M=v,E=M?.context,A=M?.gpuDevice,S=M?.deviceType,C=M?.powerPreference;E?n.currentContext=E:A?n.currentContext=await n.webnnCreateMLContext(A):n.currentContext=await n.webnnCreateMLContext({deviceType:S,powerPreference:C})}else n.currentContext=await n.webnnCreateMLContext();break}a=await n._OrtCreateSession(s,r,o),n.webgpuOnCreateSession?.(a),a===0&&re("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(a,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[u,_]=qc(a),h=!!t?.enableGraphCapture,p=[],f=[],g=[],m=[],w=[];for(let v=0;v<u;v++){let[M,E,A]=pa(a,v);M===0&&re("Can't get an input name."),c.push(M);let S=n.UTF8ToString(M);p.push(S),g.push(E===0?{name:S,isTensor:!1}:{name:S,isTensor:!0,type:Fr(E),shape:A})}for(let v=0;v<_;v++){let[M,E,A]=pa(a,v+u);M===0&&re("Can't get an output name."),d.push(M);let S=n.UTF8ToString(M);f.push(S),m.push(E===0?{name:S,isTensor:!1}:{name:S,isTensor:!0,type:Fr(E),shape:A});{if(h&&t?.preferredOutputLocation===void 0){w.push("gpu-buffer");continue}let C=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[S]??"cpu",z=n.webnnIsGraphOutput;if(C==="cpu"&&z&&z(a,S)){w.push("ml-tensor-cpu-output");continue}if(C!=="cpu"&&C!=="cpu-pinned"&&C!=="gpu-buffer"&&C!=="ml-tensor")throw new Error(`Not supported preferred output location: ${C}.`);if(h&&C!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${C}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);w.push(C)}}let y=null;return w.some(v=>v==="gpu-buffer"||v==="ml-tensor"||v==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(a),i===0&&re("Can't create IO binding."),y={handle:i,outputPreferredLocations:w,outputPreferredLocationsEncoded:w.map(v=>v==="ml-tensor-cpu-output"?"ml-tensor":v).map(v=>na(v))}),zt.set(a,[a,c,d,y,h,!1]),[a,p,f,g,m]}catch(u){throw c.forEach(_=>n._OrtFree(_)),d.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&re("Can't release IO binding."),a!==0&&n._OrtReleaseSession(a)!==0&&re("Can't release session."),u}finally{n._free(s),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&re("Can't release session options."),l.forEach(u=>n._free(u)),n.unmountExternalData?.()}},ma=e=>{let t=ce(),s=zt.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,n,a,o,i]=s;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&re("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),n.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(r)!==0&&re("Can't release session."),zt.delete(e)},ga=async(e,t,s,r,n,a,o=!1)=>{if(!e){t.push(0);return}let i=ce(),l=i.PTR_SIZE,c=e[0],d=e[1],u=e[3],_=u,h,p;if(c==="string"&&(u==="gpu-buffer"||u==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&u!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(u==="gpu-buffer"){let m=e[2].gpuBuffer;p=_s(es(c),d);{let w=i.webgpuRegisterBuffer;if(!w)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=w(m,r)}}else if(u==="ml-tensor"){let m=e[2].mlTensor;p=_s(es(c),d);let w=i.webnnRegisterMLTensor;if(!w)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=w(r,m,es(c),d)}else{let m=e[2];if(Array.isArray(m)){p=l*m.length,h=i._malloc(p),s.push(h);for(let w=0;w<m.length;w++){if(typeof m[w]!="string")throw new TypeError(`tensor data at index ${w} is not a string`);i.setValue(h+w*l,Qe(m[w],s),"*")}}else{let w=i.webnnIsGraphInput,y=i.webnnIsGraphOutput;if(c!=="string"&&w&&y){let v=i.UTF8ToString(n);if(w(r,v)||y(r,v)){let M=es(c);p=_s(M,d),_="ml-tensor";let E=i.webnnCreateTemporaryTensor,A=i.webnnUploadTensor;if(!E||!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let S=await E(r,M,d);A(S,new Uint8Array(m.buffer,m.byteOffset,m.byteLength)),h=S}else p=m.byteLength,h=i._malloc(p),s.push(h),i.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,p),h)}else p=m.byteLength,h=i._malloc(p),s.push(h),i.HEAPU8.set(new Uint8Array(m.buffer,m.byteOffset,p),h)}}let f=i.stackSave(),g=i.stackAlloc(4*d.length);try{d.forEach((w,y)=>i.setValue(g+y*l,w,l===4?"i32":"i64"));let m=i._OrtCreateTensor(es(c),h,p,g,d.length,na(_));m===0&&re(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(m)}finally{i.stackRestore(f)}},wa=async(e,t,s,r,n,a)=>{let o=ce(),i=o.PTR_SIZE,l=zt.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],u=l[2],_=l[3],h=l[4],p=l[5],f=t.length,g=r.length,m=0,w=[],y=[],v=[],M=[],E=[],A=o.stackSave(),S=o.stackAlloc(f*i),C=o.stackAlloc(f*i),z=o.stackAlloc(g*i),R=o.stackAlloc(g*i);try{[m,w]=Mc(a),Ot("wasm prepareInputOutputTensor");for(let L=0;L<f;L++)await ga(s[L],y,M,e,d[t[L]],t[L],h);for(let L=0;L<g;L++)await ga(n[L],v,M,e,u[r[L]],f+r[L],h);Nt("wasm prepareInputOutputTensor");for(let L=0;L<f;L++)o.setValue(S+L*i,y[L],"*"),o.setValue(C+L*i,d[t[L]],"*");for(let L=0;L<g;L++)o.setValue(z+L*i,v[L],"*"),o.setValue(R+L*i,u[r[L]],"*");if(_&&!p){let{handle:L,outputPreferredLocations:D,outputPreferredLocationsEncoded:se}=_;if(d.length!==f)throw new Error(`input count from feeds (${f}) is expected to be always equal to model's input count (${d.length}).`);Ot("wasm bindInputsOutputs");for(let U=0;U<f;U++){let W=t[U];await o._OrtBindInput(L,d[W],y[U])!==0&&re(`Can't bind input[${U}] for session=${e}.`)}for(let U=0;U<g;U++){let W=r[U];n[U]?.[3]?(E.push(v[U]),o._OrtBindOutput(L,u[W],v[U],0)!==0&&re(`Can't bind pre-allocated output[${U}] for session=${e}.`)):o._OrtBindOutput(L,u[W],0,se[W])!==0&&re(`Can't bind output[${U}] to ${D[U]} for session=${e}.`)}Nt("wasm bindInputsOutputs"),zt.set(e,[c,d,u,_,h,!0])}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let N;_?N=await o._OrtRunWithBinding(c,_.handle,g,z,m):N=await o._OrtRun(c,C,S,f,R,g,z,m),N!==0&&re("failed to call OrtRun().");let O=[],$=[];Ot("wasm ProcessOutputTensor");for(let L=0;L<g;L++){let D=Number(o.getValue(z+L*i,"*"));if(D===v[L]||E.includes(v[L])){O.push(n[L]),D!==v[L]&&o._OrtReleaseTensor(D)!==0&&re("Can't release tensor.");continue}let se=o.stackSave(),U=o.stackAlloc(4*i),W=!1,x,k=0;try{o._OrtGetTensorData(D,U,U+i,U+2*i,U+3*i)!==0&&re(`Can't access output tensor data on index ${L}.`);let F=i===4?"i32":"i64",K=Number(o.getValue(U,F));k=o.getValue(U+i,"*");let H=o.getValue(U+i*2,"*"),Le=Number(o.getValue(U+i*3,F)),_e=[];for(let ve=0;ve<Le;ve++)_e.push(Number(o.getValue(H+ve*i,F)));o._OrtFree(H)!==0&&re("Can't free memory for tensor dims.");let de=_e.reduce((ve,ue)=>ve*ue,1);x=Fr(K);let Ce=_?.outputPreferredLocations[r[L]];if(x==="string"){if(Ce==="gpu-buffer"||Ce==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ve=[];for(let ue=0;ue<de;ue++){let Ke=o.getValue(k+ue*i,"*"),ds=o.getValue(k+(ue+1)*i,"*"),Qs=ue===de-1?void 0:ds-Ke;ve.push(o.UTF8ToString(Ke,Qs))}O.push([x,_e,ve,"cpu"])}else if(Ce==="gpu-buffer"&&de>0){let ve=o.webgpuGetBuffer;if(!ve)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ue=ve(k),Ke=_s(K,de);if(Ke===void 0||!sa(x))throw new Error(`Unsupported data type: ${x}`);W=!0;{o.webgpuRegisterBuffer(ue,e,k);let ds=o.webgpuCreateDownloader(ue,Ke,e);O.push([x,_e,{gpuBuffer:ue,download:async()=>{let Qs=await ds();return new(Js(x))(Qs)},dispose:()=>{o._OrtReleaseTensor(D)!==0&&re("Can't release tensor.")}},"gpu-buffer"])}}else if(Ce==="ml-tensor"&&de>0){let ve=o.webnnEnsureTensor,ue=o.webnnIsGraphInputOutputTypeSupported;if(!ve||!ue)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(_s(K,de)===void 0||!ra(x))throw new Error(`Unsupported data type: ${x}`);if(!ue(e,x,!1))throw new Error(`preferredLocation "ml-tensor" for ${x} output is not supported by current WebNN Context.`);let Ke=await ve(e,k,K,_e,!1);W=!0,O.push([x,_e,{mlTensor:Ke,download:o.webnnCreateMLTensorDownloader(k,x),dispose:()=>{o.webnnReleaseTensorId(k),o._OrtReleaseTensor(D)}},"ml-tensor"])}else if(Ce==="ml-tensor-cpu-output"&&de>0){let ve=o.webnnCreateMLTensorDownloader(k,x)(),ue=O.length;W=!0,$.push((async()=>{let Ke=[ue,await ve];return o.webnnReleaseTensorId(k),o._OrtReleaseTensor(D),Ke})()),O.push([x,_e,[],"cpu"])}else{let ve=Js(x),ue=new ve(de);new Uint8Array(ue.buffer,ue.byteOffset,ue.byteLength).set(o.HEAPU8.subarray(k,k+ue.byteLength)),O.push([x,_e,ue,"cpu"])}}finally{o.stackRestore(se),x==="string"&&k&&o._free(k),W||o._OrtReleaseTensor(D)}}_&&!h&&(o._OrtClearBoundOutputs(_.handle)!==0&&re("Can't clear bound outputs."),zt.set(e,[c,d,u,_,h,!1]));for(let[L,D]of await Promise.all($))O[L][2]=D;return Nt("wasm ProcessOutputTensor"),O}finally{o.webnnOnRunEnd?.(c),o.stackRestore(A),s.forEach(N=>{N&&N[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(N[2].gpuBuffer)}),n.forEach(N=>{N&&N[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(N[2].gpuBuffer)}),y.forEach(N=>o._OrtReleaseTensor(N)),v.forEach(N=>o._OrtReleaseTensor(N)),M.forEach(N=>o._free(N)),m!==0&&o._OrtReleaseRunOptions(m),w.forEach(N=>o._free(N))}},va=e=>{let t=ce(),s=zt.get(e);if(!s)throw new Error("invalid session id");let r=s[0],n=t._OrtEndProfiling(r);n===0&&re("Can't get an profile file name."),t._OrtFree(n)},ya=e=>{let t=[];for(let s of e){let r=s[2];!Array.isArray(r)&&"buffer"in r&&t.push(r.buffer)}return t}}),Dt,Je,ps,er,tr,Or,Ma,Nr,ts,ss,Hc,Qc,Xc,Yc,Kc,Jc,Zc,ed,td=Z(()=>{"use strict";Jt(),Wc(),Zt(),Kn(),Dt=()=>!!me.wasm.proxy&&typeof document<"u",ps=!1,er=!1,tr=!1,Nr=new Map,ts=(e,t)=>{let s=Nr.get(e);s?s.push(t):Nr.set(e,[t])},ss=()=>{if(ps||!er||tr||!Je)throw new Error("worker not ready")},Hc=e=>{switch(e.data.type){case"init-wasm":ps=!1,e.data.err?(tr=!0,Ma[1](e.data.err)):(er=!0,Ma[0]()),Or&&(URL.revokeObjectURL(Or),Or=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Nr.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Qc=async()=>{if(!er){if(ps)throw new Error("multiple calls to 'initWasm()' detected.");if(tr)throw new Error("previous call to 'initWasm()' failed.");if(ps=!0,Dt())return new Promise((e,t)=>{Je?.terminate(),mc().then(([s,r])=>{try{Je=r,Je.onerror=a=>t(a),Je.onmessage=Hc,Ma=[e,t];let n={type:"init-wasm",in:me};if(!n.in.wasm.wasmPaths&&s){let a=Hn();a&&(n.in.wasm.wasmPaths=a)}Je.postMessage(n),Or=s}catch(n){t(n)}},t)});try{await ea(me.wasm),await _a(me),er=!0}catch(e){throw tr=!0,e}finally{ps=!1}}},Xc=async e=>{if(Dt())return ss(),new Promise((t,s)=>{ts("init-ep",[t,s]);let r={type:"init-ep",in:{epName:e,env:me}};Je.postMessage(r)});await ha(me,e)},Yc=async e=>Dt()?(ss(),new Promise((t,s)=>{ts("copy-from",[t,s]);let r={type:"copy-from",in:{buffer:e}};Je.postMessage(r,[e.buffer])})):Lr(e),Kc=async(e,t)=>{if(Dt()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ss(),new Promise((s,r)=>{ts("create",[s,r]);let n={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Je.postMessage(n,a)})}else return fa(e,t)},Jc=async e=>{if(Dt())return ss(),new Promise((t,s)=>{ts("release",[t,s]);let r={type:"release",in:e};Je.postMessage(r)});ma(e)},Zc=async(e,t,s,r,n,a)=>{if(Dt()){if(s.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return ss(),new Promise((o,i)=>{ts("run",[o,i]);let l=s,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:r,options:a}};Je.postMessage(c,ya(l))})}else return wa(e,t,s,r,n,a)},ed=async e=>{if(Dt())return ss(),new Promise((t,s)=>{ts("end-profiling",[t,s]);let r={type:"end-profiling",in:e};Je.postMessage(r)});va(e)}}),ba,sd,rd,jf=Z(()=>{"use strict";Jt(),td(),hs(),Un(),Ac(),ba=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},sd=e=>{switch(e[3]){case"cpu":return new nt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!sa(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:r,dispose:n}=e[2];return nt.fromGpuBuffer(s,{dataType:t,dims:e[1],download:r,dispose:n})}case"ml-tensor":{let t=e[0];if(!ra(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:r,dispose:n}=e[2];return nt.fromMLTensor(s,{dataType:t,dims:e[1],download:r,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},rd=class{async fetchModelAndCopyToWasmMemory(e){return Yc(await aa(e))}async loadModel(e,t){Yt();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Kc(s,t),Kt()}async dispose(){return Jc(this.sessionId)}async run(e,t,s){Yt();let r=[],n=[];Object.entries(e).forEach(u=>{let _=u[0],h=u[1],p=this.inputNames.indexOf(_);if(p===-1)throw new Error(`invalid input '${_}'`);r.push(h),n.push(p)});let a=[],o=[];Object.entries(t).forEach(u=>{let _=u[0],h=u[1],p=this.outputNames.indexOf(_);if(p===-1)throw new Error(`invalid output '${_}'`);a.push(h),o.push(p)});let i=r.map((u,_)=>ba(u,()=>`input "${this.inputNames[n[_]]}"`)),l=a.map((u,_)=>u?ba(u,()=>`output "${this.outputNames[o[_]]}"`):null),c=await Zc(this.sessionId,n,i,o,l,s),d={};for(let u=0;u<c.length;u++)d[this.outputNames[o[u]]]=a[u]??sd(c[u]);return Kt(),d}startProfiling(){}endProfiling(){ed(this.sessionId)}}}),nd={};Er(nd,{OnnxruntimeWebAssemblyBackend:()=>ka,initializeFlags:()=>xa,wasmBackend:()=>ad});var xa,ka,ad,qf=Z(()=>{"use strict";Jt(),td(),jf(),xa=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.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.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?xf("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ka=class{async init(e){xa(),await Qc(),await Xc(e)}async createInferenceSessionHandler(e,t){let s=new rd;return await s.loadModel(e,t),s}},ad=new ka});Jt(),Jt(),Jt();var Wf="1.31.0-dev.20260914-8d85527a0",Hf=lc;{let e=(qf(),Dn(nd)).wasmBackend;Qt("webgpu",e,5),Qt("webnn",e,5),Qt("cpu",e,10),Qt("wasm",e,10)}Object.defineProperty(me.versions,"web",{value:Wf,enumerable:!0});var Qf=Object.freeze({__proto__:null,get InferenceSession(){return Vn},get TRACE(){return Ar},get TRACE_EVENT_BEGIN(){return Ot},get TRACE_EVENT_END(){return Nt},get TRACE_FUNC_BEGIN(){return Yt},get TRACE_FUNC_END(){return Kt},get Tensor(){return nt},default:Hf,get env(){return me},get registerBackend(){return Qt}});const Xf=(e,t)=>{const s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];const r=s.getContext("2d");if(r!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);const o=t?.format!==void 0?t.format:"RGB",i=t?.norm;let l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));const d=a*n;let u=0,_=d,h=d*2,p=-1;o==="RGBA"?(u=0,_=d,h=d*2,p=d*3):o==="RGB"?(u=0,_=d,h=d*2):o==="RBG"&&(u=0,h=d,_=d*2);for(let f=0;f<a;f++)for(let g=0;g<n;g++){const m=(e.data[u++]-c[0])*l[0],w=(e.data[_++]-c[1])*l[1],y=(e.data[h++]-c[2])*l[2],v=p===-1?255:(e.data[p++]-c[3])*l[3];r.fillStyle="rgba("+m+","+w+","+y+","+v+")",r.fillRect(g,f,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Yf=(e,t)=>{const s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(s!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm;let c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const u=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let h=0,p=1,f=2,g=3,m=0,w=u,y=u*2,v=-1;i==="RGBA"?(m=0,w=u,y=u*2,v=u*3):i==="RGB"?(m=0,w=u,y=u*2):i==="RBG"&&(m=0,y=u,w=u*2),r=s.createImageData(n,a);for(let M=0;M<a*n;h+=_,p+=_,f+=_,g+=_,M++)r.data[h]=(e.data[m++]-d[0])*c[0],r.data[p]=(e.data[w++]-d[1])*c[1],r.data[f]=(e.data[y++]-d[2])*c[2],r.data[g]=v===-1?255:(e.data[v++]-d[3])*c[3]}else throw new Error("Can not access image data");return r},Ea=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:s,width:r}=t,n=t.norm??{mean:255,bias:0};let a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=s*r,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let u=4,_=0,h=1,p=2,f=3,g=0,m=c,w=c*2,y=-1;i==="RGB"&&(u=3,_=0,h=1,p=2,f=-1),l==="RGBA"?y=c*3:l==="RBG"?(g=0,w=c,m=c*2):l==="BGR"&&(w=0,m=c,g=c*2);for(let M=0;M<c;M++,_+=u,p+=u,h+=u,f+=u)d[g++]=(e[_]+o[0])/a[0],d[m++]=(e[h]+o[1])/a[1],d[w++]=(e[p]+o[2])/a[2],y!==-1&&f!==-1&&(d[y++]=(e[f]+o[3])/a[3]);return l==="RGBA"?new Ze("float32",d,[1,4,s,r]):new Ze("float32",d,[1,3,s,r])},Kf=async(e,t)=>{const s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let o,i=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(s){const d=l();d.width=e.width,d.height=e.height;const u=c(d);if(u!=null){let _=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=h}else i.tensorFormat="RGBA",i.height=_,i.width=h;u.drawImage(e,0,0),o=u.getImageData(0,0,h,_).data}else throw new Error("Can not access image data")}else if(r){let d,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,u=t.resizedWidth):(d=e.height,u=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=u,t!==void 0){const _=l();_.width=u,_.height=d;const h=c(_);if(h!=null)h.putImageData(e,0,0),o=h.getImageData(0,0,u,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const d=l();d.width=e.width,d.height=e.height;const u=c(d);if(u!=null){const _=e.height,h=e.width;return u.drawImage(e,0,0,h,_),o=u.getImageData(0,0,h,_).data,i.height=_,i.width=h,Ea(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,u)=>{const _=l(),h=c(_);if(!e||!h)return u();const p=new Image;p.crossOrigin="Anonymous",p.src=e,p.onload=()=>{_.width=p.width,_.height=p.height,h.drawImage(p,0,0,_.width,_.height);const f=h.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(Ea(f.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Ea(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Jf=(e,t)=>{const{width:s,height:r,download:n,dispose:a}=t,o=[1,r,s,4];return new Ze({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Zf=(e,t)=>{const{dataType:s,dims:r,download:n,dispose:a}=t;return new Ze({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:r,download:n,dispose:a})},em=(e,t)=>{const{dataType:s,dims:r,download:n,dispose:a}=t;return new Ze({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:r,download:n,dispose:a})},tm=(e,t,s)=>new Ze({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]}),fs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),zr=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let od=!1;const sm=()=>{if(!od){od=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,r=typeof s<"u"&&s.from;e&&(fs.set("int64",BigInt64Array),zr.set(BigInt64Array,"int64")),t&&(fs.set("uint64",BigUint64Array),zr.set(BigUint64Array,"uint64")),r?(fs.set("float16",s),zr.set(s,"float16")):fs.set("float16",Uint16Array)}},rm=e=>{let t=1;for(let s=0;s<e.length;s++){const r=e[s];if(typeof r!="number"||!Number.isSafeInteger(r))throw new TypeError(`dims[${s}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${r}`);t*=r}return t},nm=(e,t)=>{switch(e.location){case"cpu":return new Ze(e.type,e.data,t);case"cpu-pinned":return new Ze({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ze({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ze({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ze({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Ze=class{constructor(t,s,r){sm();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=fs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof t=="string")if(n=t,l=r,t==="string"){if(!Array.isArray(s))throw new TypeError("A string tensor's data must be a string array.");i=s}else{const c=fs.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(s)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(s,BigInt):i=c.from(s)}else if(s instanceof c)i=s;else if(s instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(s);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&s instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(s.buffer,s.byteOffset,s.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=s,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof t[0];if(c==="string")n="string",i=t;else if(c==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(t);else{const c=zr.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=c,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}const o=rm(a);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=o}static async fromImage(t,s){return Kf(t,s)}static fromTexture(t,s){return Jf(t,s)}static fromGpuBuffer(t,s){return Zf(t,s)}static fromMLTensor(t,s){return em(t,s)}static fromPinnedBuffer(t,s,r){return tm(t,s,r)}toDataURL(t){return Xf(this,t)}toImageData(t){return Yf(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const s=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=s,t&&this.disposer&&(this.disposer(),this.disposer=void 0),s}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return nm(this,t)}};const am=Ze;var Ta={},om=Object.defineProperty,sr=(e,t)=>{for(var s in t)om(e,s,{get:t[s],enumerable:!0})},Xe={},wt={},im={},lm="4.3.1",Aa=typeof self<"u",ms=!_d(Xe),id=!_d(wt),Dr=Aa&&"caches"in self,cm=typeof globalThis.Deno<"u",Br=cm&&Dr&&!ms,ld=typeof process<"u",cd=ld&&process?.release?.name==="node"&&!Br,Ca=typeof window<"u"&&typeof window.document<"u",Sa=Aa&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),dm=Ca||Sa||Br,um=cd||typeof navigator<"u"&&"gpu"in navigator,_m=typeof navigator<"u"&&"ml"in navigator,hm=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",pm=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",fm=typeof ServiceWorkerGlobalScope<"u"&&Aa&&self instanceof ServiceWorkerGlobalScope,mm=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent;if(!((navigator.vendor||"").indexOf("Apple")>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android")))return!1;const s=e.match(/Version\/(\d+)/);return s?parseInt(s[1],10)<26:!1},gm=mm(),Y=Object.freeze({IS_BROWSER_ENV:Ca,IS_WEBWORKER_ENV:Sa,IS_WEB_ENV:dm,IS_SERVICE_WORKER_ENV:fm,IS_DENO_WEB_RUNTIME:Br,IS_WEB_CACHE_AVAILABLE:Dr,IS_WEBGPU_AVAILABLE:um,IS_WEBNN_AVAILABLE:_m,IS_SAFARI_BELOW_26:gm,IS_PROCESS_AVAILABLE:ld,IS_NODE_ENV:cd,IS_FS_AVAILABLE:ms,IS_PATH_AVAILABLE:id,IS_CRYPTO_AVAILABLE:hm,IS_CHROME_AVAILABLE:pm}),Pa=ms&&id,Rr="./";if(Pa){const e=self.location.href;e?Rr=wt.dirname(wt.dirname(im.fileURLToPath(e))):typeof __dirname<"u"&&(Rr=wt.dirname(__dirname))}var wm=Pa?wt.join(Rr,"/.cache/"):null,dd="/models/",vm=Pa?wt.join(Rr,dd):dd,ym=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,at=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),ud=at.WARNING,ee={version:lm,backends:{onnx:{}},get logLevel(){return ud},set logLevel(e){ud=e,ee.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Ca||Sa||Br),localModelPath:vm,useFS:ms,useBrowserCache:Dr,useFSCache:ms,cacheDir:wm,useCustomCache:!1,customCache:null,useWasmCache:Dr||ms,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:ym};function _d(e){return Object.keys(e).length===0}var Ue=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 Bt(e,t){e&&e(t)}var $r=class extends Ue{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=new Map}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};const t=Object.values(this.files_loading).reduce((n,a)=>n+a.loaded,0),s=Object.values(this.files_loading).reduce((n,a)=>n+a.total,0),r=s>0?t/s*100:0;this.callback({status:"progress_total",name:e.name,progress:r,loaded:t,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function Mm(e){return Number.isInteger(e)||typeof e=="bigint"}function hd(e){return e==null||e===-1}function pd(e){const t=[];let s=e;for(;Array.isArray(s);)t.push(s.length),s=s[0];return t}function ot(...e){return Array.prototype.concat.apply([],e)}function bm(...e){return e.reduce((t,s)=>t.flatMap(r=>s.map(n=>[r,n])))}function Gr(e,t){return Math.abs((e+t)%(2*t)-t)}function Ie(e,t){return Object.assign({},...t.map(s=>{if(e[s]!==void 0)return{[s]:e[s]}}))}function xm(e,t){let s=0;for(const r of e)r===t&&++s;return s}var Q={error(...e){ee.logLevel<=at.ERROR&&console.error(...e)},warn(...e){ee.logLevel<=at.WARNING&&console.warn(...e)},info(...e){ee.logLevel<=at.INFO&&console.log(...e)},debug(...e){ee.logLevel<=at.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},km=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const s of e){let r=t;for(let n=0;n<s.length;++n){const a=s[n];r=r[a]??=Object.create(null)}r.end=s}return t}split(e){const t=[],s=e.length;let r=0,n=0;for(;n<s;){let a=this.trie,o=null,i=n;for(;i<s&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(n>r&&t.push(e.slice(r,n)),t.push(o),n+=o.length,r=n):++n}return r<s&&t.push(e.slice(r)),t}},fd=km,Em=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}},Tm=Em,md=(e,t)=>{try{return new RegExp(e,t)}catch(s){if(!(s instanceof SyntaxError))throw s;const r=new Map,n=e.replace(/(\\[pP])\{([^}=]+)\}/g,(a,o,i,l)=>{let c=0;for(let u=l-1;u>=0&&e[u]==="\\";--u)++c;if(c%2===1)return a;let d=r.get(i);if(d===void 0){try{new RegExp(`\\p{${i}}`,"u"),d=i}catch{d=`Script=${i}`}r.set(i,d)}return`${o}{${d}}`});if(n===e)throw s;try{return new RegExp(n,t)}catch{throw s}}},Fa=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"),Vr=(e,t=!0)=>{if(e.Regex!==void 0){const s=Um($m(e.Regex));return md(s,"gu")}else if(e.String!==void 0){const s=jm(e.String);return new RegExp(t?s:`(${s})`,"gu")}else return console.warn("Unknown pattern type:",e),null},gs="\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}",gd=`${gs}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,vt=`[${gd}]`,wd=`[^${gd}]`,Am=`(?:(?<!${vt})(?=${vt})|(?<=${vt})(?!${vt}))`,Cm=`(?:(?<!${vt})(?!${vt})|(?<=${vt})(?=${vt}))`,Sm="(?:(?<![\\s\\S])|(?<=\\n))",Pm="(?:(?=\\n)|(?![\\s\\S]))",rr="0-9A-Fa-f",Fm=new Map([["A","(?<![\\s\\S])"],["z","(?![\\s\\S])"],["Z","(?=\\n?(?![\\s\\S]))"],["h",`[${rr}]`],["H",`[^${rr}]`],["w",vt],["W",wd],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["b",Am],["B",Cm],["a","\\x07"],["e","\\x1B"]]),Im=new Map([["h",rr],["w",gs],["d","\\p{Nd}"],["D","\\P{Nd}"],["s","\\p{White_Space}"],["S","\\P{White_Space}"],["a","\\x07"],["e","\\x1B"]]),Lm=new Map([["W",`[^${gs}]`],["H",`[^${rr}]`]]),vd=new Map([[`
|
||
`,"\\n"],["\r","\\r"],[" ","\\t"],["\f","\\f"],["\v","\\v"]]),Om=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",gs],["xdigit",rr]]),yd="^$\\.*+?()[]{}|/",Nm=/^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,Md=/^\\([pPxu])\{([^}]*)\}/,zm=/^\{(\d+(?:,\d*)?|,\d+)\}/,Dm=/^\[:(\^?)(\p{Alphabetic}+):\]/u,Bm=/^\[:\^:\]/,Rm=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,bd=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,xd=e=>e>="A"&&e<="Z"||e>="a"&&e<="z",Ur=(e,t)=>String.fromCodePoint(e.codePointAt(t)),kd=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;const t=Number.parseInt(e,16);if(t>127)return null;const s=String.fromCharCode(t);return xd(s)?`[${s.toLowerCase()}${s.toUpperCase()}]`:null},$m=e=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,"[^()|\\s$1]"),Ed="[\\s\\S]",Td=256,Ad=()=>({fragment:"",alternatives:[],tail:null,contains_complex_set:!1}),Ia=e=>{throw new SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},jr=(e,t,s,r=!0)=>{e.tail==="range"&&Ia(s),e.alternatives.push(t),e.tail="set",e.contains_complex_set=e.contains_complex_set||r},Rt=(e,t,s=!1,r=-1)=>{if(s&&e.tail==="range"&&Ia(r),e.tail==="range"){e.fragment+=t,e.tail="complete_range";return}e.fragment+=t,e.tail=s?"set":"scalar",e.contains_complex_set=e.contains_complex_set||s},Gm=(e,t,s)=>{const r=Md.exec(e.slice(t));if(r){const[_,h,p]=r;if(h==="P"&&p==="Word")jr(s,`[^${gs}]`,t);else{const f=h==="x"?`\\u{${p}}`:h==="p"&&p==="Word"?gs:_;Rt(s,f,h==="p"||h==="P",t)}return t+_.length}const n=bd.exec(e.slice(t));if(n)return Rt(s,n[0]),t+n[0].length;if(t+1>=e.length)throw new SyntaxError(`Unterminated escape in character class at index ${t}`);const a=Ur(e,t+1),o=t+1+a.length,i=vd.get(a);if(i!==void 0)return Rt(s,i),o;const l=Lm.get(a);if(l!==void 0)return jr(s,l,t),o;const c=Im.get(a);let d,u=!1;return c!==void 0?(d=c,u=a!=="a"&&a!=="e"):/[A-Za-z0-9]/.test(a)?d=`\\${a}`:yd.includes(a)||a==="-"?d=`\\${a}`:d=a,Rt(s,d,u,t),o},Cd=e=>e.length===1?e[0]:`(?:(?=(?:${e.join("|")}))${Ed})`,Sd=e=>{const t=e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives];return Cd(t)},Vm=e=>{const t=md(`^(?:${e})$`,"u");let s="";for(let r=0;r<26;++r){const n=String.fromCharCode(65+r),a=String.fromCharCode(97+r),o=t.test(n),i=t.test(a);o!==i&&(s+=o?a:n)}return s},Pd=(e,t,s,r=!0,n=1)=>{if(n>Td)throw new SyntaxError(`Maximum character-class nesting depth of ${Td} exceeded at index ${t}`);let a=t+1;const o=e[a]==="^";o&&++a;const i=a,l=[Ad()];let c=l[0],d=!1;for(;a<e.length;){const u=Ur(e,a);if(u==="\\"){a=Gm(e,a,c);continue}if(u==="]"){if(a===i){Rt(c,"\\]"),++a;continue}if(c.tail===null)throw l.length>1?new SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):new SyntaxError(`Empty character class at index ${t}`);const _=l.some(w=>w.contains_complex_set);if(o&&l.length>1&&d)throw new SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);const h=Sd(l[0]);let p=h;if(l.length>1){let w="";for(let y=1;y<l.length;++y)w+=`(?=${Sd(l[y])})`;p=`(?:${w}${h})`}const f=l.length===1&&c.alternatives.length===0;let g=c.fragment;if(s&&r){const w=Vm(p);w.length>0&&(f?(g+=w,p=`[${g}]`):p=Cd([p,`[${w}]`]))}return{atom:o?f?`[^${g}]`:`(?:(?!${p})${Ed})`:p,end:a+1,negated:o,contains_complex_set:_,contains_nested_negated_complex_set:d}}if(e.startsWith("&&",a)){if(c.tail===null)throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);c=Ad(),l.push(c),a+=2;continue}if(u==="["){const _=e.slice(a);if(Bm.test(_))throw new SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);const h=Dm.exec(_);if(h){const[,f,g]=h,m=Om.get(g);if(m===void 0)throw new SyntaxError(`Unsupported POSIX character class "${g}" at index ${a}`);if(s&&f&&(g==="lower"||g==="upper"))throw new SyntaxError(`Unsupported negated POSIX ${g} class inside an inline case-insensitive group`);f?jr(c,`[^${m}]`,a):Rt(c,m,!0,a),a+=h[0].length;continue}if(Rm.test(_))throw new SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);const p=Pd(e,a,s,!1,n+1);jr(c,p.atom,a,p.contains_complex_set),d||=p.contains_nested_negated_complex_set||p.negated&&p.contains_complex_set,a=p.end;continue}if(u==="-"){const _=e[a+1]==="]"||e.startsWith("&&",a+1);c.tail==="set"&&!_&&Ia(a),c.tail===null||c.tail==="range"||c.tail==="complete_range"||_?Rt(c,"\\-"):(c.fragment+="-",c.tail="range"),++a;continue}Rt(c,u==="^"&&c.fragment.length===0?"\\^":u),a+=u.length}throw new SyntaxError(`${l.length>1?"Unterminated character-class intersection":"Unterminated character class"} at index ${t}`)},Um=e=>{let t="",s=-1,r=!1,n=!1;const a=[],o=i=>{s=t.length,t+=i,r=!1};for(let i=0;i<e.length;){const l=Ur(e,i);if(l==="\\"){const c=Md.exec(e.slice(i));if(c){const[f,g,m]=c;let w=f;if(g==="x"){const y=`\\u{${m}}`;w=n?kd(m)??y:y}else m==="Word"&&(w=g==="p"?vt:wd);o(w),i+=f.length;continue}const d=bd.exec(e.slice(i));if(d){const f=d[0],g=n&&f[1]!=="c"?kd(f.slice(2))??f:f;o(g),i+=f.length;continue}if(i+1>=e.length){t+=l;break}const u=Ur(e,i+1);if(i+=1+u.length,u==="G")continue;const _=vd.get(u);if(_!==void 0){o(_);continue}const h=Fm.get(u);let p;h!==void 0?p=h:/[A-Za-z0-9]/.test(u)?p=`\\${u}`:yd.includes(u)?p=`\\${u}`:p=u,o(p);continue}switch(l){case"[":{const c=Pd(e,i,n);o(c.atom),i=c.end;continue}case"]":o("\\]"),++i;continue;case".":o("[^\\n]"),++i;continue;case"^":o(Sm),++i;continue;case"$":o(Pm),++i;continue;case"(":{const c=e.startsWith("(?i:",i),d=c?"(?i:":Nm.exec(e.slice(i))?.[0]??"(",u=c||d==="(?>"?"(?:":d;a.push([t.length,n]),c&&(n=!0),t+=u,r=!1,i+=d.length;continue}case")":t+=l,[s,n]=a.pop()??[-1,!1],r=!1,++i;continue;case"|":t+=l,s=-1,r=!1,++i;continue;case"{":{const c=zm.exec(e.slice(i));if(!c||s<0){o("\\{"),++i;continue}const d=c[1].startsWith(",")?`0${c[1]}`:c[1];i+=c[0].length;const u=e[i];u==="+"||u==="*"?(t=`${t.slice(0,s)}(?:${t.slice(s)}{${d}})${u}`,++i):t+=`{${d}}`,r=!0;continue}case"}":o("\\}"),++i;continue;case"+":if(r){++i;continue}t+=l,r=!0,++i;continue;case"*":case"?":t+=l,r=!0,++i;continue;default:o(n&&xd(l)?`[${l.toLowerCase()}${l.toUpperCase()}]`:l),i+=l.length;continue}}return t},jm=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qm=(e,t,s)=>{const r=[];let n=0;for(;n<e.length;){if(r.push(e[n]),(t.get(e[n])??s)!==s){++n;continue}for(;++n<e.length&&(t.get(e[n])??s)===s;)t.get(r.at(-1))!==s&&(r[r.length-1]+=e[n])}return r},Wm=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,Hm=e=>Number.isInteger(e)||typeof e=="bigint",Qm=e=>{let t=0;for(const s of e)++t;return t},Xm=e=>Fd(e.toLowerCase()),it=(...e)=>Array.prototype.concat.apply([],e),La=e=>new Map(Object.entries(e)),Ym=(e,t)=>{const s=[];let r=0;for(const n of e.matchAll(t)){const a=n[0];r<n.index&&s.push(e.slice(r,n.index)),a.length>0&&s.push(a),r=n.index+a.length}return r<e.length&&s.push(e.slice(r)),s},Fd=e=>e.replace(/\p{M}/gu,""),Id=(e,t,s=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const r of s)if(!(r in e))return`${t} must contain a "${r}" property`;return null},Km=e=>e.match(/\S+/g)||[],Jm=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},nr=Jm,Zm=class extends nr{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},At=Zm,eg=class extends At{tokenize_chinese_chars(e){const t=[];for(let s=0;s<e.length;++s){const r=e[s],n=r.charCodeAt(0);Wm(n)?(t.push(" "),t.push(r),t.push(" ")):t.push(r)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case" ":case`
|
||
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){const t=[];for(const s of e){const r=s.charCodeAt(0);r===0||r===65533||this.is_control(s)||(/^\s$/.test(s)?t.push(" "):t.push(s))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},tg=eg,sg=class extends At{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("~")?e=e.split("~").map(s=>s.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},rg=sg,ng=class extends At{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Ld(t))}normalize(e){return this.normalizers.reduce((t,s)=>s?s.normalize(t):t,e)}},ag=ng,og=class extends At{constructor(e){super(e),this.pattern=Vr(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??"")}},ig=og,lg=class extends At{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},qr=lg,cg=class extends qr{constructor(){super(...arguments),this.form="NFC"}},dg=cg,ug=class extends qr{constructor(){super(...arguments),this.form="NFD"}},_g=ug,hg=class extends qr{constructor(){super(...arguments),this.form="NFKC"}},pg=hg,fg=class extends qr{constructor(){super(...arguments),this.form="NFKD"}},mg=fg,gg=class extends At{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},wg=gg,vg=class extends At{normalize(e){return Fd(e)}},yg=vg,Mg=class extends At{normalize(e){return e.toLowerCase()}},bg=Mg,xg=class extends At{normalize(e){return e=this.config.prepend+e,e}},kg=xg;function Eg(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new tg(e);case"Precompiled":return new rg(e);case"Sequence":return new ag(e);case"Replace":return new ig(e);case"NFC":return new dg(e);case"NFD":return new _g(e);case"NFKC":return new pg(e);case"NFKD":return new mg(e);case"Strip":return new wg(e);case"StripAccents":return new yg(e);case"Lowercase":return new bg(e);case"Prepend":return new kg(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Ld=Eg,Tg=class extends nr{pre_tokenize(e,t){return(Array.isArray(e)?e.map(s=>this.pre_tokenize_text(s,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},lt=Tg,Od=(()=>{const e=[...Array.from({length:94},(n,a)=>a+33),...Array.from({length:12},(n,a)=>a+161),...Array.from({length:82},(n,a)=>a+174)],t=e.slice();let s=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+s),s+=1);const r=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,a)=>[n,r[a]]))})(),Ag=e=>Object.fromEntries(Object.entries(e).map(([t,s])=>[s,t])),Cg=Ag(Od),Wr="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Sg=class extends lt{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=Od,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(r=>Array.from(this.text_encoder.encode(r),n=>this.byte_encoder[n]).join(""))}},Pg=Sg,Fg=class extends lt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Ig=Fg,Lg=class extends lt{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:s=void 0}=t??{};let r=e.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&s===0)&&(r=this.str_rep+r),[r]}},Og=Lg,Ng=class extends lt{constructor(e){super(),this.config=e,this.pattern=Vr(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(t=>t):this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):Ym(e,this.pattern)}},zg=Ng,Dg=class extends lt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Wr}]+|[${Wr}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Bg=Dg,Rg=class extends lt{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},$g=Rg,Gg=class extends lt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Wr}]+|[${Wr}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Vg=Gg,Ug=class extends lt{constructor(e){super(),this.config=e,this.pattern=Vr(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},jg=Ug,qg=class extends lt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Nd(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((s,r)=>r?r.pre_tokenize(s,t):s,[e])}},Wg=qg,Hg=class extends lt{pre_tokenize_text(e){return Km(e)}},Qg=Hg,Xg=class extends lt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let s=0;s<e.length;s+=this._length)t.push(e.slice(s,s+this._length));return t}},Yg=Xg;function Kg(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new Vg;case"Sequence":return new Wg(e);case"Whitespace":return new Ig;case"WhitespaceSplit":return new Qg;case"Metaspace":return new Og(e);case"ByteLevel":return new Pg(e);case"Split":return new zg(e);case"Punctuation":return new Bg(e);case"Digits":return new $g(e);case"Replace":return new jg(e);case"FixedLength":return new Yg(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var Nd=Kg,Jg=class extends nr{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=qm(t,this.tokens_to_ids,this.unk_token_id)),t}},Hr=Jg,Zg=class extends Hr{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=La(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,s]of this.tokens_to_ids)this.vocab[s]=t}encode(e){const t=[];for(const s of e){const r=[...s];if(r.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,a=0;const o=[];for(;a<r.length;){let i=r.length,l=null;for(;a<i;){let c=r.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}o.push(l),a=i}n?t.push(this.unk_token):t.push(...o)}return t}},zd=Zg,Dd=class mf{constructor(t,s){this.is_leaf=t,this.children=s}static default(){return new mf(!1,new Map)}},ew=class{constructor(){this.root=Dd.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const s of e){let r=t.children.get(s);r===void 0&&(r=Dd.default(),t.children.set(s,r)),t=r}t.is_leaf=!0}*common_prefix_search(e,t=0){let s=this.root;if(s===void 0)return;let r="";for(let n=t;n<e.length;++n){const a=e[n];if(r+=a,s=s.children.get(a),s===void 0)return;s.is_leaf&&(yield r)}}},tw=ew,Oa=class gf{constructor(t,s,r,n,a){this.token_id=t,this.node_id=s,this.pos=r,this.length=n,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new gf(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},sw=class{constructor(e,t,s){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=s,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);const r=new Oa(this.bos_token_id??0,0,0,0,0),n=new Oa(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(r)}insert(e,t,s,r){const n=this.nodes.length,a=new Oa(r,n,e,t,s);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let c of this.end_nodes[t]){const d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.clone(),i=d)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}const s=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let a=n.clone();for(;a.prev!==null;)s.push(a.clone()),a=a.clone().prev.clone();return s.reverse(),s}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)}},rw=sw;function nw(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],s=r);return[t,s]}var aw=class extends Hr{constructor(e,t){super(e);const s=e.vocab.length;this.vocab=new Array(s),this.scores=new Array(s);for(let r=0;r<s;++r)[this.vocab[r],this.scores[r]]=e.vocab[r];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,n)=>[r,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=nw(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new tw,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,s=1;let r=0;for(;r<t.length;){let n=!1;const a=this.trie.common_prefix_search(t,r);for(const o of a){const i=this.tokens_to_ids.get(o),l=this.scores[i],c=Qm(o);e.insert(r,c,l,i),!n&&c===s&&(n=!0)}n||e.insert(r,s,this.unk_score,this.unk_token_id),r+=s}}tokenize(e){const t=new rw(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const s of e){const r=this.tokenize(s);t.push(...r)}return t}},Bd=aw,ow=class{constructor(e=(s,r)=>s>r,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{const s=this._smallest();this._comparator(t,this._heap[s])&&(this._heap[s]=t,this._sift_up_from(s))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const s=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=s}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},iw=ow,lw=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},cw=lw,dw=class extends Hr{constructor(e){super(e),this.tokens_to_ids=La(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[s,r]of this.tokens_to_ids)this.vocab[r]=s;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(s=>s.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((s,r)=>[JSON.stringify(s),r])),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 cw(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const s=Array.from(e);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let r=[];if(s.length>1){const n=new iw((i,l)=>i.score<l.score);let a={token:s[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<s.length;++i){const l={bias:i/s.length,token:s[i],prev:o,next:null};o.next=l,this.add_node(n,o),o=l}for(;!n.is_empty();){const i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){const c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}const l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=a;i!==null;i=i.next)r.push(i.token)}else r=s;if(this.continuing_subword_suffix)for(let n=0;n<r.length-1;++n)r[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,r),r}add_node(e,t){const s=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));s!==void 0&&(t.score=s+t.bias,e.push(t))}encode(e){const t=[];for(const s of e){if(this.ignore_merges&&this.tokens_to_ids.has(s)){t.push(s);continue}const r=this.bpe(s);for(const n of r)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(n)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Rd=dw,uw=class extends Hr{constructor(e,t){super(e);const s=e.vocab;this.tokens_to_ids=La(t.target_lang?s[t.target_lang]:s),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r}encode(e){return e}},_w=uw;function hw(e,t){switch(e.type){case"WordPiece":return new zd(e);case"Unigram":return new Bd(e,t.eos_token);case"BPE":return new Rd(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Bd(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Rd(e):new zd(e):new _w(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var pw=hw,fw=class extends nr{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ar=fw,mw=class extends ar{post_process(e,t=null,s=!0){const r=t===null?this.config.single:this.config.pair;let n=[],a=[];for(const o of r)"SpecialToken"in o?s&&(n.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(n=it(n,e),a=it(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(n=it(n,t),a=it(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:n,token_type_ids:a}}},gw=mw,ww=class extends ar{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},vw=ww,yw=class extends ar{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,s=!0){s&&(e=it([this.cls[0]],e,[this.sep[0]]));let r=new Array(e.length).fill(0);if(t){const n=[],a=s?[this.sep[0]]:[];e=it(e,n,t,a),r=it(r,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Mw=yw,bw=class extends ar{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,s=!0){s&&(e=it([this.cls[0]],e,[this.sep[0]]));let r=new Array(e.length).fill(0);if(t){const n=s?[this.sep[0]]:[],a=s?[this.sep[0]]:[];e=it(e,n,t,a),r=it(r,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},xw=bw,kw=class extends ar{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>$d(t))}post_process(e,t=null,s=!0){let r={tokens:e,tokens_pair:t};for(const n of this.processors)r=n.post_process(r.tokens,r.tokens_pair,s);return r}},Ew=kw;function Tw(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new gw(e);case"ByteLevel":return new vw(e);case"BertProcessing":return new Mw(e);case"RobertaProcessing":return new xw(e);case"Sequence":return new Ew(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var $d=Tw,Aw=class extends nr{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("")}},ct=Aw,Cw=class extends ct{constructor(e){super(e),this.byte_decoder=Cg,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),s=new Uint8Array([...t].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(s)}decode_chain(e){const t=[];let s=[];for(const r of e)this.added_tokens.find(n=>n.content===r)!==void 0?(s.length>0&&(t.push(this.convert_tokens_to_string(s)),s=[]),t.push(r)):s.push(r);return s.length>0&&t.push(this.convert_tokens_to_string(s)),t}},Sw=Cw,Pw=class extends ct{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,s)=>{if(s!==0){const r=this.config.prefix;r&&t.startsWith(r)?t=t.replace(r,""):t=" "+t}return this.cleanup&&(t=Fa(t)),t})}},Fw=Pw,Iw=class extends ct{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let s=0;s<e.length;++s){let r=e[s].replaceAll(this.replacement," ");s==0&&r.startsWith(" ")&&(r=r.substring(1)),t.push(r)}return t}},Lw=Iw,Ow=class extends ct{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,s)=>t.replaceAll(this.suffix,s===e.length-1?"":" "))}},Nw=Ow,zw=class extends ct{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let r=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(r=Fa(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Dw=zw,Bw=class extends ct{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Gd(t))}decode_chain(e){return this.decoders.reduce((t,s)=>s.decode_chain(t),e)}},Rw=Bw,$w=class extends ct{constructor(e){super(e),this.pattern=Vr(this.config.pattern)}decode_chain(e){const t=this.config.content??"",s=this.pattern;return s===null?e:e.map(r=>r.replaceAll(s,t))}},Gw=$w,Vw=class extends ct{decode_chain(e){return[e.join("")]}},Uw=Vw,jw=class extends ct{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 s=0;for(let n=0;n<this.start&&t[n]===this.content;++n){s=n+1;continue}let r=t.length;for(let n=0;n<this.stop;++n){const a=t.length-n-1;if(t[a]===this.content){r=a;continue}else break}return t.slice(s,r)})}},qw=jw,Ww=class extends ct{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let s=[];for(const r of e){let n=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){const a=parseInt(r.slice(3,5),16);isNaN(a)||(n=a)}if(n!==null)s.push(n);else{if(s.length>0){const a=this.text_decoder.decode(Uint8Array.from(s));t.push(a),s=[]}t.push(r)}}if(s.length>0){const r=this.text_decoder.decode(Uint8Array.from(s));t.push(r),s=[]}return t}},Hw=Ww;function Qw(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Sw(e);case"WordPiece":return new Fw(e);case"Metaspace":return new Lw(e);case"BPEDecoder":return new Nw(e);case"CTC":return new Dw(e);case"Sequence":return new Rw(e);case"Replace":return new Gw(e);case"Fuse":return new Uw(e);case"Strip":return new qw(e);case"ByteFallback":return new Hw(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Gd=Qw,Xw=class{constructor(e,t){const s=Id(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(s)throw new Error(s);const r=Id(t,"Config");if(r)throw new Error(r);this.tokenizer=e,this.config=t,this.normalizer=Ld(this.tokenizer.normalizer),this.pre_tokenizer=Nd(this.tokenizer.pre_tokenizer),this.model=pw(this.tokenizer.model,this.config),this.post_processor=$d(this.tokenizer.post_processor),this.decoder=Gd(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const n=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new Tm(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new fd(n),this.splitter_normalized=new fd(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:s=!0,return_token_type_ids:r=null}={}){const{tokens:n,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:s}),o=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:n,attention_mask:new Array(o.length).fill(1)};return r&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Hm(e[0]))throw Error("token_ids must be a non-empty array of integers.");let s=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(s=s.filter(n=>!this.special_tokens.includes(n)));let r=this.decoder?this.decoder(s):s.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Fa(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:s=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:s}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((s,r)=>{const n=this.added_tokens_map.get(s);n&&(n.lstrip&&r>0&&(t[r-1]=t[r-1].trimEnd()),n.rstrip&&r<t.length-1&&(t[r+1]=t[r+1].trimStart()))}),t.flatMap((s,r)=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];if(this.remove_space===!0&&(s=s.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(s=Xm(s)),this.normalizer!==null&&(s=this.normalizer(s)),s.length===0)return[];const n=this.splitter_normalized.split(s);return n.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(n[o-1]=n[o-1].trimEnd()),i.rstrip&&o<n.length-1&&(n[o+1]=n[o+1].trimStart()))}),n.flatMap(a=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:r}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:s=!0}){const r=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(r,n,s):{tokens:it(r??[],n??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let s=0;s<this.model.vocab.length;++s){const r=this.model.vocab[s];(e||!this.added_tokens_map.has(r))&&t.set(r,s)}return t}},Yw=Xw,Kw=Object.defineProperty,Jw=(e,t,s)=>t in e?Kw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,Zw=(e,t,s)=>(Jw(e,t+"",s),s),T=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"}),et=class{constructor(e,t){this.value=e,this.type=t}};function Vd(e){return/\w/.test(e)}function rs(e){return/[0-9]/.test(e)}function Ud(e){return/\s/.test(e)}var ev=[["{%",T.OpenStatement],["%}",T.CloseStatement],["{{",T.OpenExpression],["}}",T.CloseExpression],["(",T.OpenParen],[")",T.CloseParen],["{",T.OpenCurlyBracket],["}",T.CloseCurlyBracket],["[",T.OpenSquareBracket],["]",T.CloseSquareBracket],[",",T.Comma],[".",T.Dot],[":",T.Colon],["|",T.Pipe],["<=",T.ComparisonBinaryOperator],[">=",T.ComparisonBinaryOperator],["==",T.ComparisonBinaryOperator],["!=",T.ComparisonBinaryOperator],["<",T.ComparisonBinaryOperator],[">",T.ComparisonBinaryOperator],["+",T.AdditiveBinaryOperator],["-",T.AdditiveBinaryOperator],["~",T.AdditiveBinaryOperator],["**",T.ExponentiationBinaryOperator],["*",T.MultiplicativeBinaryOperator],["//",T.MultiplicativeBinaryOperator],["/",T.MultiplicativeBinaryOperator],["%",T.MultiplicativeBinaryOperator],["=",T.Equals]],tv=new Map([["n",`
|
||
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function sv(e,t={}){return e.endsWith(`
|
||
`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(s,r,n,a,o)=>(n?"":r)+(a?"":o))}function rv(e,t={}){const s=[],r=sv(e,t);let n=0,a=0;const o=c=>{let d="";for(;c(r[n]);){if(r[n]==="\\"){if(++n,n>=r.length)throw new SyntaxError("Unexpected end of input");const u=r[n++],_=tv.get(u);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${u}`);d+=_;continue}if(d+=r[n++],n>=r.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{const c=s.at(-1);c&&c.type===T.Text&&(c.value=c.value.trimEnd(),c.value===""&&s.pop())},l=()=>{for(;n<r.length&&Ud(r[n]);)++n};e:for(;n<r.length;){const c=s.at(-1)?.type;if(c===void 0||c===T.CloseStatement||c===T.CloseExpression||c===T.Comment){let u="";for(;n<r.length&&!(r[n]==="{"&&(r[n+1]==="%"||r[n+1]==="{"||r[n+1]==="#"));)u+=r[n++];if(u.length>0){s.push(new et(u,T.Text));continue}}if(r[n]==="{"&&r[n+1]==="#"){n+=2;const u=r[n]==="-";u&&++n;let _="";for(;r[n]!=="#"||r[n+1]!=="}";){if(n+2>=r.length)throw new SyntaxError("Missing end of comment tag");_+=r[n++]}const h=_.endsWith("-");h&&(_=_.slice(0,-1)),u&&i(),s.push(new et(_,T.Comment)),n+=2,h&&l();continue}if(r.slice(n,n+3)==="{%-"){i(),s.push(new et("{%",T.OpenStatement)),n+=3;continue}if(r.slice(n,n+3)==="{{-"){i(),s.push(new et("{{",T.OpenExpression)),a=0,n+=3;continue}if(o(Ud),r.slice(n,n+3)==="-%}"){s.push(new et("%}",T.CloseStatement)),n+=3,l();continue}if(r.slice(n,n+3)==="-}}"){s.push(new et("}}",T.CloseExpression)),n+=3,l();continue}const d=r[n];if(d==="-"||d==="+"){const u=s.at(-1)?.type;if(u===T.Text||u===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(u){case T.Identifier:case T.NumericLiteral:case T.StringLiteral:case T.CloseParen:case T.CloseSquareBracket:break;default:{++n;let _=o(rs);if(_.length>0&&r[n]==="."&&rs(r[n+1])){++n;const h=o(rs);_=`${_}.${h}`}s.push(new et(`${d}${_}`,_.length>0?T.NumericLiteral:T.UnaryOperator));continue}}}for(const[u,_]of ev){if(u==="}}"&&a>0)continue;if(r.slice(n,n+u.length)===u){s.push(new et(u,_)),_===T.OpenExpression?a=0:_===T.OpenCurlyBracket?++a:_===T.CloseCurlyBracket&&--a,n+=u.length;continue e}}if(d==="'"||d==='"'){++n;const u=o(_=>_!==d);s.push(new et(u,T.StringLiteral)),++n;continue}if(rs(d)){let u=o(rs);if(s.at(-1)?.type!==T.Dot&&r[n]==="."&&rs(r[n+1])){++n;const _=o(rs);u=`${u}.${_}`}s.push(new et(u,T.NumericLiteral));continue}if(Vd(d)){const u=o(Vd);s.push(new et(u,T.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return s}var tt=class{type="Statement"},nv=class extends tt{constructor(e){super(),this.body=e}type="Program"},av=class extends tt{constructor(e,t,s){super(),this.test=e,this.body=t,this.alternate=s}type="If"},ov=class extends tt{constructor(e,t,s,r){super(),this.loopvar=e,this.iterable=t,this.body=s,this.defaultBlock=r}type="For"},iv=class extends tt{type="Break"},lv=class extends tt{type="Continue"},cv=class extends tt{constructor(e,t,s){super(),this.assignee=e,this.value=t,this.body=s}type="Set"},dv=class extends tt{constructor(e,t,s){super(),this.name=e,this.args=t,this.body=s}type="Macro"},uv=class extends tt{constructor(e){super(),this.value=e}type="Comment"},je=class extends tt{type="Expression"},_v=class extends je{constructor(e,t,s){super(),this.object=e,this.property=t,this.computed=s}type="MemberExpression"},jd=class extends je{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},$t=class extends je{constructor(e){super(),this.value=e}type="Identifier"},ws=class extends je{constructor(e){super(),this.value=e}type="Literal"},hv=class extends ws{type="IntegerLiteral"},pv=class extends ws{type="FloatLiteral"},qd=class extends ws{type="StringLiteral"},fv=class extends ws{type="ArrayLiteral"},Wd=class extends ws{type="TupleLiteral"},mv=class extends ws{type="ObjectLiteral"},vs=class extends je{constructor(e,t,s){super(),this.operator=e,this.left=t,this.right=s}type="BinaryExpression"},gv=class extends je{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},wv=class extends tt{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},vv=class extends je{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},yv=class extends je{constructor(e,t,s){super(),this.operand=e,this.negate=t,this.test=s}type="TestExpression"},Hd=class extends je{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},Mv=class extends je{constructor(e=void 0,t=void 0,s=void 0){super(),this.start=e,this.stop=t,this.step=s}type="SliceExpression"},Na=class extends je{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},bv=class extends je{constructor(e){super(),this.argument=e}type="SpreadExpression"},xv=class extends je{constructor(e){super(),this.argument=e}type="KeywordSpreadExpression"},kv=class extends tt{constructor(e,t,s){super(),this.call=e,this.callerArgs=t,this.body=s}type="CallStatement"},Ev=class extends je{constructor(e,t,s){super(),this.condition=e,this.trueExpr=t,this.falseExpr=s}type="Ternary"};function Tv(e){const t=new nv([]);let s=0;function r(x,k){const F=e[s++];if(!F||F.type!==x)throw new Error(`Parser Error: ${k}. ${F.type} !== ${x}.`);return F}function n(x){if(!l(x))throw new SyntaxError(`Expected ${x}`);++s}function a(){switch(e[s].type){case T.Comment:return new uv(e[s++].value);case T.Text:return c();case T.OpenStatement:return d();case T.OpenExpression:return u();default:throw new SyntaxError(`Unexpected token type: ${e[s].type}`)}}function o(...x){return s+x.length<=e.length&&x.every((k,F)=>k===e[s+F].type)}function i(...x){return e[s]?.type===T.OpenStatement&&e[s+1]?.type===T.Identifier&&x.includes(e[s+1]?.value)}function l(...x){return s+x.length<=e.length&&x.every((k,F)=>e[s+F].type==="Identifier"&&k===e[s+F].value)}function c(){return new qd(r(T.Text,"Expected text token").value)}function d(){if(r(T.OpenStatement,"Expected opening statement token"),e[s].type!==T.Identifier)throw new SyntaxError(`Unknown statement, got ${e[s].type}`);const x=e[s].value;let k;switch(x){case"set":++s,k=_();break;case"if":++s,k=h(),r(T.OpenStatement,"Expected {% token"),n("endif"),r(T.CloseStatement,"Expected %} token");break;case"macro":++s,k=p(),r(T.OpenStatement,"Expected {% token"),n("endmacro"),r(T.CloseStatement,"Expected %} token");break;case"for":++s,k=g(),r(T.OpenStatement,"Expected {% token"),n("endfor"),r(T.CloseStatement,"Expected %} token");break;case"call":{++s;let F=null;o(T.OpenParen)&&(F=z("parameters"));const K=W();if(K.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const H=z("call");r(T.CloseStatement,"Expected closing statement token");const Le=[];for(;!i("endcall");)Le.push(a());r(T.OpenStatement,"Expected '{%'"),n("endcall"),r(T.CloseStatement,"Expected closing statement token");const _e=new jd(K,H);k=new kv(_e,F,Le);break}case"break":++s,r(T.CloseStatement,"Expected closing statement token"),k=new iv;break;case"continue":++s,r(T.CloseStatement,"Expected closing statement token"),k=new lv;break;case"filter":{++s;let F=W();F instanceof $t&&o(T.OpenParen)&&(F=C(F)),r(T.CloseStatement,"Expected closing statement token");const K=[];for(;!i("endfilter");)K.push(a());r(T.OpenStatement,"Expected '{%'"),n("endfilter"),r(T.CloseStatement,"Expected '%}'"),k=new wv(F,K);break}default:throw new SyntaxError(`Unknown statement type: ${x}`)}return k}function u(){r(T.OpenExpression,"Expected opening expression token");const x=m();return r(T.CloseExpression,"Expected closing expression token"),x}function _(){const x=f();let k=null;const F=[];if(o(T.Equals))++s,k=f();else{for(r(T.CloseStatement,"Expected %} token");!i("endset");)F.push(a());r(T.OpenStatement,"Expected {% token"),n("endset")}return r(T.CloseStatement,"Expected closing statement token"),new cv(x,k,F)}function h(){const x=m();r(T.CloseStatement,"Expected closing statement token");const k=[],F=[];for(;!i("elif","else","endif");)k.push(a());if(i("elif")){++s,++s;const K=h();F.push(K)}else if(i("else"))for(++s,++s,r(T.CloseStatement,"Expected closing statement token");!i("endif");)F.push(a());return new av(x,k,F)}function p(){const x=W();if(x.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const k=z("parameters");r(T.CloseStatement,"Expected closing statement token");const F=[];for(;!i("endmacro");)F.push(a());return new dv(x,k,F)}function f(x=!1){const k=x?W:m,F=[k()],K=o(T.Comma);for(;K&&(++s,F.push(k()),!!o(T.Comma)););return K?new Wd(F):F[0]}function g(){const x=f(!0);if(!(x instanceof $t||x instanceof Wd))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${x.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++s;const k=m();r(T.CloseStatement,"Expected closing statement token");const F=[];for(;!i("endfor","else");)F.push(a());const K=[];if(i("else"))for(++s,++s,r(T.CloseStatement,"Expected closing statement token");!i("endfor");)K.push(a());return new ov(x,k,F,K)}function m(){return w()}function w(){const x=y();if(l("if")){++s;const k=y();if(l("else")){++s;const F=w();return new Ev(k,x,F)}else return new vv(x,k)}return x}function y(){let x=v();for(;l("or");){const k=e[s];++s;const F=v();x=new vs(k,x,F)}return x}function v(){let x=M();for(;l("and");){const k=e[s];++s;const F=M();x=new vs(k,x,F)}return x}function M(){let x;for(;l("not");){const k=e[s];++s;const F=M();x=new Hd(k,F)}return x??E()}function E(){let x=A();for(;;){let k;if(l("not","in"))k=new et("not in",T.Identifier),s+=2;else if(l("in"))k=e[s++];else if(o(T.ComparisonBinaryOperator))k=e[s++];else break;const F=A();x=new vs(k,x,F)}return x}function A(){let x=$();for(;o(T.AdditiveBinaryOperator);){const k=e[s];++s;const F=$();x=new vs(k,x,F)}return x}function S(){const x=O(W());return o(T.OpenParen)?C(x):x}function C(x){let k=new jd(x,z("call"));return k=O(k),o(T.OpenParen)&&(k=C(k)),k}function z(x){r(T.OpenParen,"Expected opening parenthesis for arguments list");const k=R(x);return r(T.CloseParen,"Expected closing parenthesis for arguments list"),k}function R(x){const k=[],F=new Set;let K=!1,H=!1;for(;!o(T.CloseParen);){const Le=o(T.ExponentiationBinaryOperator),_e=o(T.MultiplicativeBinaryOperator)&&e[s].value==="*";if(x==="parameters"&&(Le||_e))throw new SyntaxError("Argument unpacking is not allowed in parameter declarations");if(Le){if(++s,k.push(new xv(m())),o(T.Comma)&&++s,!o(T.CloseParen))throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let de;if(_e){if(H)throw new SyntaxError("Only one `*` argument unpacking is allowed");H=!0,++s;const Ce=m();de=new bv(Ce)}else{if(de=m(),o(T.Equals)){if(++s,!(de instanceof $t))throw new SyntaxError(x==="parameters"?"Expected identifier for parameter declaration":"Expected identifier for keyword argument");const Ce=m();de=new Na(de,Ce)}if(x==="parameters"){if(!(de instanceof $t||de instanceof Na))throw new SyntaxError("Expected identifier for parameter declaration");const Ce=de instanceof $t?de.value:de.key.value;if(F.has(Ce))throw new SyntaxError(`Duplicate parameter name: ${Ce}`);F.add(Ce)}if(de instanceof Na)K=!0;else{if(K)throw new SyntaxError(x==="call"?"Positional arguments must come before keyword arguments":"Non-default argument follows default argument");if(H)throw new SyntaxError("Positional arguments must not follow `*` argument unpacking")}}k.push(de),o(T.Comma)&&++s}return k}function N(){const x=[];let k=!1;for(;!o(T.CloseSquareBracket);)o(T.Colon)?(x.push(void 0),++s,k=!0):(x.push(m()),o(T.Colon)&&(++s,k=!0));if(x.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(k){if(x.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Mv(...x)}return x[0]}function O(x){for(;o(T.Dot)||o(T.OpenSquareBracket);){const k=e[s];++s;let F;const K=k.type===T.OpenSquareBracket;if(K)F=N(),r(T.CloseSquareBracket,"Expected closing square bracket");else if(F=W(),F.type!=="Identifier"&&F.type!=="IntegerLiteral")throw new SyntaxError("Expected identifier or integer following dot operator");x=new _v(x,F,K)}return x}function $(){let x=L();for(;o(T.MultiplicativeBinaryOperator);){const k=e[s++],F=L();x=new vs(k,x,F)}return x}function L(){let x=D();for(;o(T.ExponentiationBinaryOperator);){const k=e[s++],F=D();x=new vs(k,x,F)}return x}function D(){let x=se();for(;l("is");){++s;const k=l("not");k&&++s;const F=W();if(!(F instanceof $t))throw new SyntaxError("Expected identifier for the test");x=new yv(x,k,F)}return x}function se(){let x=U();for(;o(T.Pipe);){++s;let k=W();if(!(k instanceof $t))throw new SyntaxError("Expected identifier for the filter");o(T.OpenParen)&&(k=C(k)),x=new gv(x,k)}return x}function U(){const x=e[s];if(x&&(x.type===T.UnaryOperator||x.type===T.AdditiveBinaryOperator)&&(x.value==="-"||x.value==="+")){const k=e[s++],F=U();return new Hd(k,F)}return S()}function W(){const x=e[s++];switch(x.type){case T.NumericLiteral:{const k=x.value;return k.includes(".")?new pv(Number(k)):new hv(Number(k))}case T.StringLiteral:{let k=x.value;for(;o(T.StringLiteral);)k+=e[s++].value;return new qd(k)}case T.Identifier:return new $t(x.value);case T.OpenParen:{const k=f();return r(T.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),k}case T.OpenSquareBracket:{const k=[];for(;!o(T.CloseSquareBracket);)k.push(m()),o(T.Comma)&&++s;return++s,new fv(k)}case T.OpenCurlyBracket:{const k=new Map;for(;!o(T.CloseCurlyBracket);){const F=m();r(T.Colon,"Expected colon between key and value in object literal");const K=m();k.set(F,K),o(T.Comma)&&++s}return++s,new mv(k)}default:throw new SyntaxError(`Unexpected token: ${x.type}`)}}for(;s<e.length;)t.body.push(a());return t}function Av(e,t,s=1){if(t===void 0&&(t=e,e=0),s===0)throw new Error("range() step must not be zero");const r=[];if(s>0)for(let n=e;n<t;n+=s)r.push(n);else for(let n=e;n>t;n+=s)r.push(n);return r}function Qd(e,t,s,r=1){const n=Math.sign(r);n>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),s=(s??=e.length)<0?Math.max(e.length+s,0):Math.min(s,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),s=(s??=-1)<-1?Math.max(e.length+s,-1):Math.min(s,e.length-1));const a=[];for(let o=t;n*o<n*s;o+=r)a.push(e[o]);return a}function Cv(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function Sv(e){return Pv(new Date,e)}function Pv(e,t){const s=new Intl.DateTimeFormat(void 0,{month:"long"}),r=new Intl.DateTimeFormat(void 0,{month:"short"}),n=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return n(e.getMonth()+1);case"%d":return n(e.getDate());case"%b":return r.format(e);case"%B":return s.format(e);case"%H":return n(e.getHours());case"%M":return n(e.getMinutes());case"%%":return"%";default:return a}})}function Fv(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Iv(e,t,s,r){if(r===0)return e;let n=r==null||r<0?1/0:r;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(Fv(t),"gu");return e.replaceAll(a,o=>n>0?(--n,s):o)}var Xd=class extends Error{},Yd=class extends Error{},Lv=new Map,dt=class{type="RuntimeValue";value;get builtins(){return Lv}constructor(e=void 0){this.value=e}__bool__(){return new G(!!this.value)}toString(){return String(this.value)}},j=class extends dt{type="IntegerValue"},ae=class extends dt{type="FloatValue";toString(){return Object.is(this.value,-0)?"-0.0":this.value%1===0?this.value.toFixed(1):this.value.toString()}},B=class extends dt{type="StringValue";_builtins;get builtins(){return this._builtins??=new Map([["upper",new he(()=>new B(this.value.toUpperCase()))],["lower",new he(()=>new B(this.value.toLowerCase()))],["strip",new he(()=>new B(this.value.trim()))],["title",new he(()=>new B(Cv(this.value)))],["capitalize",new he(()=>new B(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new j(this.value.length)],["rstrip",new he(()=>new B(this.value.trimEnd()))],["lstrip",new he(()=>new B(this.value.trimStart()))],["startswith",new he(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof B)return new G(this.value.startsWith(t.value));if(t instanceof J){for(const s of t.value){if(!(s instanceof B))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new G(!0)}return new G(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new he(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof B)return new G(this.value.endsWith(t.value));if(t instanceof J){for(const s of t.value){if(!(s instanceof B))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new G(!0)}return new G(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new he(e=>{const t=e[0]??new ge;if(!(t instanceof B||t instanceof ge))throw new Error("sep argument must be a string or null");const s=e[1]??new j(-1);if(!(s instanceof j))throw new Error("maxsplit argument must be a number");let r=[];if(t instanceof ge){const n=this.value.trimStart();for(const{0:a,index:o}of n.matchAll(/\S+/g)){if(s.value!==-1&&r.length>=s.value&&o!==void 0){r.push(a+n.slice(o+a.length));break}r.push(a)}}else{if(t.value==="")throw new Error("empty separator");r=this.value.split(t.value),s.value!==-1&&r.length>s.value&&r.push(r.splice(s.value).join(t.value))}return new J(r.map(n=>new B(n)))})],["replace",new he(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],s=e[1];if(!(t instanceof B&&s instanceof B))throw new Error("replace() arguments must be strings");let r;if(e.length>2?e[2].type==="KeywordArgumentsValue"?r=e[2].value.get("count")??new ge:r=e[2]:r=new ge,!(r instanceof j||r instanceof ge))throw new Error("replace() count argument must be a number or null");return new B(Iv(this.value,t.value,s.value,r.value))})]])}},G=class extends dt{type="BooleanValue"},Ov=/[\x7f-\uffff]/g;function Kd(e){return e.replace(Ov,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Gt(e,t={},s=0,r=!0){const{indent:n=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,c;switch(o?[l,c]=o:n?(l=",",c=": "):(l=", ",c=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return r?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let d=JSON.stringify(e.value);return a&&(d=Kd(d)),d}case"ArrayValue":case"NamespaceValue":case"ObjectValue":{const d=n?" ".repeat(n):"",u=`
|
||
`+d.repeat(s),_=u+d;if(e.type==="ArrayValue"){const h=e.value.map(p=>Gt(p,t,s+1,r));return n?`[${_}${h.join(`${l}${_}`)}${u}]`:`[${h.join(l)}]`}else{let h=Array.from(e.value.entries());i&&(h=h.sort(([f],[g])=>f.localeCompare(g)));const p=h.map(([f,g])=>{let m=JSON.stringify(f);a&&(m=Kd(m));const w=`${m}${c}${Gt(g,t,s+1,r)}`;return n?`${_}${w}`:w});return n?`{${p.join(l)}${u}}`:`{${p.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var Be=class extends dt{type="ObjectValue";_builtins;__bool__(){return new G(this.value.size>0)}get builtins(){return this._builtins??=new Map([["get",new he(([e,t])=>{if(!(e instanceof B))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new ge})],["items",new he(()=>this.items())],["keys",new he(()=>this.keys())],["values",new he(()=>this.values())],["dictsort",new he(e=>{let t=new Map;const s=e.filter(i=>i instanceof ns?(t=i.value,!1):!0),r=s.at(0)??t.get("case_sensitive")??new G(!1);if(!(r instanceof G))throw new Error("case_sensitive must be a boolean");const n=s.at(1)??t.get("by")??new B("key");if(!(n instanceof B))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");const a=s.at(2)??t.get("reverse")??new G(!1);if(!(a instanceof G))throw new Error("reverse must be a boolean");const o=Array.from(this.value.entries()).map(([i,l])=>new J([new B(i),l])).sort((i,l)=>{const c=n.value==="key"?0:1,d=i.value[c],u=l.value[c],_=Da(d,u,r.value);return a.value?-_:_});return new J(o)})]])}items(){return new J(Array.from(this.value.entries()).map(([e,t])=>new J([new B(e),t])))}keys(){return new J(Array.from(this.value.keys()).map(e=>new B(e)))}values(){return new J(Array.from(this.value.values()))}toString(){return Gt(this,{},0,!1)}},ns=class extends Be{type="KeywordArgumentsValue"},za=class extends dt{type="NamespaceValue";toString(){return Gt(this,{},0,!1)}},J=class extends dt{type="ArrayValue";_builtins;get builtins(){return this._builtins??=new Map([["length",new j(this.value.length)]])}__bool__(){return new G(this.value.length>0)}toString(){return Gt(this,{},0,!1)}},Jd=class extends J{type="TupleValue"},he=class extends dt{type="FunctionValue"},ge=class extends dt{type="NullValue"},pe=class extends dt{type="UndefinedValue"};function Nv(e){let t;if(e instanceof J?t=e.value:e instanceof B&&(t=Array.from(e.value,n=>new B(n))),!t||t.length!==2)throw new Error("namespace expected an object or an iterable of [key, value] pairs");const[s,r]=t;if(!(s instanceof B))throw new Error("namespace keys must be strings");return[s,r]}var Zd=class{constructor(e){this.parent=e}variables=new Map([["namespace",new he(e=>{const t=e.slice();let s;if(t.at(-1)instanceof ns&&(s=t.pop()),t.length>1)throw new Error(`namespace expected at most 1 argument, got ${t.length}`);const r=new Map;if(t.length===1){const n=t[0];if(n instanceof Be)for(const[a,o]of n.value)r.set(a,o);else if(n instanceof J)for(const a of n.value){const[o,i]=Nv(a);r.set(o.value,i)}else throw new Error(`'${n.type}' object is not iterable`)}if(s)for(const[n,a]of s.value)r.set(n,a);return new za(r)})]]);tests=Zd.TESTS;set(e,t){return this.declareVariable(e,Kr(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new pe}catch{return new pe}}},Vt=Zd;Zw(Vt,"TESTS",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof he],["odd",e=>{if(!(e instanceof j))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof j))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof j||e instanceof ae],["integer",e=>e instanceof j],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof Be],["sequence",e=>e instanceof J||e instanceof Be||e instanceof B],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));function zv(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",Av),e.set("strftime_now",Sv),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Qr(e){return e instanceof Be||e instanceof za}function Xr(e){return e instanceof j||e instanceof ae||e instanceof G}function Yr(e){return e instanceof G?Number(e.value):e.value}function eu(e,t){const s=t.split(".");let r=e;for(const n of s)if(Qr(r))r=r.value.get(n)??new pe;else if(r instanceof J){const a=parseInt(n,10);if(!isNaN(a)&&a>=0&&a<r.value.length)r=r.value[a];else return new pe}else return new pe;return r}function Da(e,t,s=!1){if(e instanceof ge&&t instanceof ge)return 0;if(e instanceof ge||t instanceof ge)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof pe&&t instanceof pe)return 0;if(e instanceof pe||t instanceof pe)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(Xr(e)&&Xr(t)){const r=Yr(e),n=Yr(t);return r<n?-1:r>n?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let r=e.value,n=t.value;return s||(r=r.toLowerCase(),n=n.toLowerCase()),r<n?-1:r>n?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}function Ba(e){if(e.type==="Identifier")return{name:e.value};const t=e;return{name:t.key.value,defaultValue:t.value}}function tu(e){return e==="kwargs"||e==="varargs"}function su(e,t){const s=new Set,r=new Set,n=d=>{tu(d)&&s.add(d)},a=d=>{if(d.type==="Identifier")n(d.value);else if(d.type==="TupleLiteral")for(const u of d.value)a(u)},o=d=>{n(Ba(d).name)},i=d=>{for(const u of d){const _=Ba(u);_.defaultValue&&c(_.defaultValue)}},l=d=>{d.type==="CallExpression"&&c(d.args)},c=d=>{if(Array.isArray(d)){for(const u of d)c(u);return}if(d instanceof Map){for(const[u,_]of d)c(u),c(_);return}if(d instanceof tt)switch(d.type){case"For":{const u=d;if(a(u.loopvar),u.iterable.type==="SelectExpression"){const _=u.iterable;c(_.lhs),c(u.body),c(u.defaultBlock),c(_.test);return}c(u.iterable),c(u.body),c(u.defaultBlock);return}case"Set":{const u=d;a(u.assignee),c(u.value),c(u.body);return}case"Macro":{const u=d;for(const _ of u.args)o(_);i(u.args),c(u.body);return}case"CallStatement":{const u=d;c(u.call);for(const _ of u.callerArgs??[])o(_);i(u.callerArgs??[]),c(u.body);return}case"FilterStatement":{const u=d;c(u.body),l(u.filter);return}case"Identifier":{const u=d.value;tu(u)&&!s.has(u)&&r.add(u);return}case"MemberExpression":{const u=d;c(u.object),u.computed&&c(u.property);return}case"FilterExpression":{const u=d;c(u.operand),l(u.filter);return}case"TestExpression":c(d.operand);return;case"SelectExpression":{const u=d;c(u.test),c(u.lhs);return}case"KeywordArgumentExpression":c(d.value);return;default:for(const u of Object.values(d))c(u)}};for(const d of e)o(d);return c(t),r}var Dv=class{global;constructor(e){this.global=e??new Vt}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const s=this.evaluate(e.left,t);switch(e.operator.value){case"and":return s.__bool__().value?this.evaluate(e.right,t):s;case"or":return s.__bool__().value?s:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new G(s.value==r.value);case"!=":return new G(s.value!=r.value)}if(s instanceof pe||r instanceof pe){if(r instanceof pe&&["in","not in"].includes(e.operator.value))return new G(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(s instanceof ge||r instanceof ge)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new B(s.value.toString()+r.value.toString());if(e.operator.value==="**"&&Xr(s)&&Xr(r)){const n=Yr(s),a=Yr(r);if(n===0&&a<0)throw new Error("0.0 cannot be raised to a negative power");const o=n**a;if(!Number.isFinite(o))throw new Error("Exponentiation result is not a finite real number");return s instanceof ae||r instanceof ae||a<0?new ae(o):new j(o)}else if((s instanceof j||s instanceof ae)&&(r instanceof j||r instanceof ae)){const n=s.value,a=r.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?n+a:e.operator.value==="-"?n-a:n*a;return s instanceof ae||r instanceof ae?new ae(o):new j(o)}case"/":return new ae(n/a);case"//":{const o=Math.floor(n/a);return s instanceof ae||r instanceof ae?new ae(o):new j(o)}case"%":{const o=n%a;return s instanceof ae||r instanceof ae?new ae(o):new j(o)}case"<":return new G(n<a);case">":return new G(n>a);case">=":return new G(n>=a);case"<=":return new G(n<=a)}}else if(s instanceof J&&r instanceof J)switch(e.operator.value){case"+":return new J(s.value.concat(r.value))}else if(r instanceof J){const n=r.value.find(a=>a.value===s.value)!==void 0;switch(e.operator.value){case"in":return new G(n);case"not in":return new G(!n)}}}if(s instanceof B||r instanceof B)switch(e.operator.value){case"+":return new B(s.value.toString()+r.value.toString())}if(s instanceof B&&r instanceof B)switch(e.operator.value){case"in":return new G(r.value.includes(s.value));case"not in":return new G(!r.value.includes(s.value))}if(s instanceof B&&r instanceof Be)switch(e.operator.value){case"in":return new G(r.value.has(s.value));case"not in":return new G(!r.value.has(s.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${s.type} and ${r.type}`)}evaluateArguments(e,t){const s=[],r=new Map,n=(a,o)=>{if(r.has(a))throw new Error(`Got multiple values for keyword argument '${a}'`);r.set(a,o)};for(const a of e)if(a.type==="SpreadExpression"){const o=a,i=this.evaluate(o.argument,t);if(!(i instanceof J))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(const l of i.value)s.push(l)}else a.type!=="KeywordArgumentExpression"&&a.type!=="KeywordSpreadExpression"&&s.push(this.evaluate(a,t));for(const a of e)if(a.type==="KeywordArgumentExpression"){const o=a;n(o.key.value,this.evaluate(o.value,t))}else if(a.type==="KeywordSpreadExpression"){const o=a,i=this.evaluate(o.argument,t);if(!(i instanceof Be))throw new Error(`Argument after ** must be a mapping, not ${i.type}`);for(const[l,c]of i.value)n(l,c)}return[s,r]}applyFilter(e,t,s){if(t.type==="Identifier"){const r=t;if(r.value==="safe")return e;if(r.value==="tojson")return new B(Gt(e,{}));if(e instanceof J)switch(r.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new j(e.value.length);case"reverse":return new J(e.value.slice().reverse());case"sort":return new J(e.value.slice().sort((n,a)=>Da(n,a,!1)));case"join":return new B(e.value.map(n=>n.value).join(""));case"string":return new B(Gt(e,{},0,!1));case"unique":{const n=new Set,a=[];for(const o of e.value)n.has(o.value)||(n.add(o.value),a.push(o));return new J(a)}default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof B)switch(r.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const n=e.builtins.get(r.value);if(n instanceof he)return n.value([],s);if(n instanceof j)return n;throw new Error(`Unknown StringValue filter: ${r.value}`)}case"trim":return new B(e.value.trim());case"indent":return new B(e.value.split(`
|
||
`).map((n,a)=>a===0||n.length===0?n:" "+n).join(`
|
||
`));case"join":case"string":return e;case"int":{const n=parseInt(e.value,10);return new j(isNaN(n)?0:n)}case"float":{const n=parseFloat(e.value);return new ae(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof j||e instanceof ae)switch(r.value){case"abs":return e instanceof j?new j(Math.abs(e.value)):new ae(Math.abs(e.value));case"int":return new j(Math.floor(e.value));case"float":return new ae(e.value);case"string":return new B(e.toString());default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof Be)switch(r.value){case"items":return new J(Array.from(e.value.entries()).map(([n,a])=>new J([new B(n),a])));case"length":return new j(e.value.size);default:{const n=e.builtins.get(r.value);if(n)return n instanceof he?n.value([],s):n;throw new Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof G)switch(r.value){case"bool":return new G(e.value);case"int":return new j(e.value?1:0);case"float":return new ae(e.value?1:0);case"string":return new B(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${r.value}`)}throw new Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const r=t;if(r.callee.type!=="Identifier")throw new Error(`Unknown filter: ${r.callee.type}`);const n=r.callee.value;if(n==="tojson"){const[,a]=this.evaluateArguments(r.args,s),o=a.get("indent")??new ge;if(!(o instanceof j||o instanceof ge))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new G(!1);if(!(i instanceof G))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new G(!1);if(!(l instanceof G))throw new Error("If set, sort_keys must be a boolean");const c=a.get("separators")??new ge;let d=null;if(c instanceof J||c instanceof Jd){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");const[u,_]=c.value;if(!(u instanceof B)||!(_ instanceof B))throw new Error("separators must be a tuple of two strings");d=[u.value,_.value]}else if(!(c instanceof ge))throw new Error("If set, separators must be a tuple of two strings");return new B(Gt(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let a;if(e instanceof B)a=Array.from(e.value);else if(e instanceof J)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(r.args,s),l=o.at(0)??i.get("separator")??new B("");if(!(l instanceof B))throw new Error("separator must be a string");return new B(a.join(l.value))}else if(n==="int"||n==="float"){const[a,o]=this.evaluateArguments(r.args,s),i=a.at(0)??o.get("default")??(n==="int"?new j(0):new ae(0));if(e instanceof B){const l=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:n==="int"?new j(l):new ae(l)}else{if(e instanceof j||e instanceof ae)return e;if(e instanceof G)return n==="int"?new j(e.value?1:0):new ae(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){const[a,o]=this.evaluateArguments(r.args,s),i=a[0]??new B(""),l=a[1]??o.get("boolean")??new G(!1);if(!(l instanceof G))throw new Error("`default` filter flag must be a boolean");return e instanceof pe||l.value&&!e.__bool__().value?i:e}if(e instanceof J){switch(n){case"sort":{const[a,o]=this.evaluateArguments(r.args,s),i=a.at(0)??o.get("reverse")??new G(!1);if(!(i instanceof G))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new G(!1);if(!(l instanceof G))throw new Error("case_sensitive must be a boolean");const c=a.at(2)??o.get("attribute")??new ge;if(!(c instanceof B||c instanceof j||c instanceof ge))throw new Error("attribute must be a string, integer, or null");const d=u=>{if(c instanceof ge)return u;const _=c instanceof j?String(c.value):c.value;return eu(u,_)};return new J(e.value.slice().sort((u,_)=>{const h=d(u),p=d(_),f=Da(h,p,l.value);return i.value?-f:f}))}case"selectattr":case"rejectattr":{const a=n==="selectattr";if(e.value.some(u=>!Qr(u)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(r.args.some(u=>u.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,l]=r.args.map(u=>this.evaluate(u,s));let c;if(i){const u=s.tests.get(i.value);if(!u)throw new Error(`Unknown test: ${i.value}`);c=u}else c=(...u)=>u[0].__bool__().value;const d=e.value.filter(u=>{const _=u.value.get(o.value),h=_?c(_,l):!1;return a?h:!h});return new J(d)}case"map":{const[,a]=this.evaluateArguments(r.args,s);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof B))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(c=>{if(!Qr(c))throw new Error("items in map must be an object");const d=eu(c,o.value);return d instanceof pe?i??new pe:d});return new J(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof B){switch(n){case"indent":{const[a,o]=this.evaluateArguments(r.args,s),i=a.at(0)??o.get("width")??new j(4);if(!(i instanceof j))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new G(!1),c=a.at(2)??o.get("blank")??new G(!1),d=e.value.split(`
|
||
`),u=" ".repeat(i.value),_=d.map((h,p)=>!l.value&&p===0||!c.value&&h.length===0?h:u+h);return new B(_.join(`
|
||
`))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof he))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(r.args,s);return a.value([...o,new ns(i)],s)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof Be){const a=e.builtins.get(n);if(a&&a instanceof he){const[o,i]=this.evaluateArguments(r.args,s);return i.size>0&&o.push(new ns(i)),a.value(o,s)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const s=this.evaluate(e.operand,t);return this.applyFilter(s,e.filter,t)}evaluateTestExpression(e,t){const s=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const n=r(s);return new G(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new pe}evaluateUnaryExpression(e,t){const s=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new G(!s.value);case"+":case"-":{const r=e.operator.value==="-"?-1:1;if(s instanceof j||s instanceof ae||s instanceof G){const n=s instanceof G?s.value?1:0:s.value,a=r*n;return s instanceof ae?new ae(a):new j(a)}throw new SyntaxError(`Unknown operator "${e.operator.value}" for ${s.type}`)}default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let s="";for(const r of e){const n=this.evaluate(r,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(s+=n.toString())}return new B(s)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[s,r]=this.evaluateArguments(e.args,t);r.size>0&&s.push(new ns(r));const n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(s,t)}evaluateSliceExpression(e,t,s){if(!(e instanceof J||e instanceof B))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,s),n=this.evaluate(t.stop,s),a=this.evaluate(t.step,s);if(!(r instanceof j||r instanceof pe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof j||n instanceof pe))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof j||a instanceof pe))throw new Error("Slice step must be numeric or undefined");return e instanceof J?new J(Qd(e.value,r.value,n.value,a.value)):new B(Qd(Array.from(e.value),r.value,n.value,a.value).join(""))}evaluateMemberExpression(e,t){const s=this.evaluate(e.object,t);let r;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(s,e.property,t);r=this.evaluate(e.property,t)}else e.property.type==="IntegerLiteral"?r=new j(e.property.value):r=new B(e.property.value);let n;if(Qr(s)){if(!(r instanceof B))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.value.get(r.value)??(s instanceof Be?s.builtins.get(r.value):void 0)}else if(s instanceof J||s instanceof B)if(r instanceof j)n=s.value.at(r.value),s instanceof B&&(n=new B(s.value.at(r.value)));else if(r instanceof B)n=s.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof B))throw new Error(`Cannot access property with non-string: got ${r.type}`);n=s.builtins.get(r.value)}return n instanceof dt?n:new pe}evaluateSet(e,t){const s=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const r=e.assignee.value;t.setVariable(r,s)}else if(e.assignee.type==="TupleLiteral"){const r=e.assignee;if(!(s instanceof J))throw new Error(`Cannot unpack non-iterable type in set: ${s.type}`);const n=s.value;if(n.length!==r.value.length)throw new Error(`Too ${r.value.length>n.length?"few":"many"} items to unpack in set`);for(let a=0;a<r.value.length;++a){const o=r.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,n[a])}}else if(e.assignee.type==="MemberExpression"){const r=e.assignee,n=this.evaluate(r.object,t);if(!(n instanceof za))throw new Error("cannot assign attribute on non-namespace object");if(r.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(r.property.value,s)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new ge}evaluateIf(e,t){const s=this.evaluate(e.test,t);return this.evaluateBlock(s.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const s=new Vt(t);let r,n;if(e.iterable.type==="SelectExpression"){const c=e.iterable;n=this.evaluate(c.lhs,s),r=c.test}else n=this.evaluate(e.iterable,s);if(!(n instanceof J||n instanceof Be))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof Be&&(n=n.keys());const a=[],o=[];for(let c=0;c<n.value.length;++c){const d=new Vt(s),u=n.value[c];let _;if(e.loopvar.type==="Identifier")_=h=>h.setVariable(e.loopvar.value,u);else if(e.loopvar.type==="TupleLiteral"){const h=e.loopvar;if(u.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${u.type}`);const p=u;if(h.value.length!==p.value.length)throw new Error(`Too ${h.value.length>p.value.length?"few":"many"} items to unpack`);_=f=>{for(let g=0;g<h.value.length;++g){if(h.value[g].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[g].type}`);f.setVariable(h.value[g].value,p.value[g])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);r&&(_(d),!this.evaluate(r,d).__bool__().value)||(a.push(u),o.push(_))}let i="",l=!0;for(let c=0;c<a.length;++c){const d=new Map([["index",new j(c+1)],["index0",new j(c)],["revindex",new j(a.length-c)],["revindex0",new j(a.length-c-1)],["first",new G(c===0)],["last",new G(c===a.length-1)],["length",new j(a.length)],["previtem",c>0?a[c-1]:new pe],["nextitem",c<a.length-1?a[c+1]:new pe]]);s.setVariable("loop",new Be(d)),o[c](s);try{const u=this.evaluateBlock(e.body,s);i+=u.value}catch(u){if(u instanceof Yd)continue;if(u instanceof Xd)break;throw u}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,s);i+=c.value}return new B(i)}bindMacroArguments(e,t,s,r,n){const a=r.slice();let o=new Map;a.at(-1)instanceof ns&&(o=new Map(a.pop().value));const i=[];for(let l=0;l<t.length;++l){const{name:c,defaultValue:d}=Ba(t[l]);let u=a[l];u===void 0&&o.has(c)&&(u=o.get(c),o.delete(c)),u===void 0&&d!==void 0&&i.push([c,d]),n.setVariable(c,u??new pe)}if(s.has("kwargs"))n.setVariable("kwargs",new Be(o));else if(o.size>0)throw new Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(s.has("varargs"))n.setVariable("varargs",new J(a.slice(t.length)));else if(a.length>t.length)throw new Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(const[l,c]of i)n.setVariable(l,this.evaluate(c,n))}evaluateMacro(e,t){const s=su(e.args,e.body);return t.setVariable(e.name.value,new he((r,n)=>{const a=new Vt(n);return this.bindMacroArguments(`'${e.name.value}'`,e.args,s,r,a),this.evaluateBlock(e.body,a)})),new ge}evaluateCallStatement(e,t){const s=e.callerArgs??[],r=su(s,e.body),n=new he(c=>{const d=new Vt(t);return this.bindMacroArguments("None",s,r,c,d),this.evaluateBlock(e.body,d)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new ns(o));const i=this.evaluate(e.call.callee,t);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);const l=new Vt(t);return l.setVariable("caller",n),i.value(a,l)}evaluateFilterStatement(e,t){const s=this.evaluateBlock(e.body,t);return this.applyFilter(s,e.filter,t)}evaluate(e,t){if(!e)return new pe;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 Xd;case"Continue":throw new Yd;case"IntegerLiteral":return new j(e.value);case"FloatLiteral":return new ae(e.value);case"StringLiteral":return new B(e.value);case"ArrayLiteral":return new J(e.value.map(s=>this.evaluate(s,t)));case"TupleLiteral":return new Jd(e.value.map(s=>this.evaluate(s,t)));case"ObjectLiteral":{const s=new Map;for(const[r,n]of e.value){const a=this.evaluate(r,t);if(!(a instanceof B))throw new Error(`Object keys must be strings: got ${a.type}`);s.set(a.value,this.evaluate(n,t))}return new Be(s)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new ge;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Kr(e){switch(typeof e){case"number":return Number.isInteger(e)?new j(e):new ae(e);case"string":return new B(e);case"boolean":return new G(e);case"undefined":return new pe;case"object":return e===null?new ge:Array.isArray(e)?new J(e.map(Kr)):new Be(new Map(Object.entries(e).map(([t,s])=>[t,Kr(s)])));case"function":return new he((t,s)=>{const r=e(...t.map(n=>n.value))??null;return Kr(r)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Se=`
|
||
`,Bv="{%- ",Rv=" -%}",ye=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 ru(e){switch(e.operator.type){case"ExponentiationBinaryOperator":return ye.EXPONENTIATION;case"MultiplicativeBinaryOperator":return ye.MULTIPLICATIVE;case"AdditiveBinaryOperator":return ye.ADDITIVE;case"ComparisonBinaryOperator":return ye.COMPARISON;case"Identifier":return e.operator.value==="and"?ye.LOGICAL_AND:e.operator.value==="in"||e.operator.value==="not in"?ye.COMPARISON:ye.LOGICAL_OR}return ye.LOGICAL_OR}function nu(e){switch(e.type){case"SelectExpression":case"Ternary":return ye.CONDITIONAL;case"BinaryExpression":return ru(e);case"UnaryExpression":return e.operator.value==="not"?ye.LOGICAL_NOT:ye.UNARY_SIGN;case"TestExpression":return ye.TEST;case"FilterExpression":return ye.FILTER;default:return ye.ATOM}}function ut(e,t){const s=we(e);return nu(e)<t?`(${s})`:s}function $v(e,t=" "){const s=typeof t=="number"?" ".repeat(t):t;return _t(e.body,0,s).replace(/\n$/,"")}function Oe(...e){return Bv+e.join(" ")+Rv}function _t(e,t,s){return e.map(r=>Gv(r,t,s)).join(Se)}function Jr(e){return e.map(t=>we(t)).join(", ")}function Gv(e,t,s){const r=s.repeat(t);switch(e.type){case"Program":return _t(e.body,t,s);case"If":return Vv(e,t,s);case"For":return Uv(e,t,s);case"Set":return jv(e,t,s);case"Macro":return qv(e,t,s);case"Break":return r+Oe("break");case"Continue":return r+Oe("continue");case"CallStatement":return Wv(e,t,s);case"FilterStatement":return Hv(e,t,s);case"Comment":return r+"{# "+e.value+" #}";default:return r+"{{- "+we(e)+" -}}"}}function Vv(e,t,s){const r=s.repeat(t),n=[];let a=e;for(;a&&(n.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=r+Oe("if",we(n[0].test))+Se+_t(n[0].body,t+1,s);for(let i=1;i<n.length;++i)o+=Se+r+Oe("elif",we(n[i].test))+Se+_t(n[i].body,t+1,s);return a&&a.alternate.length>0&&(o+=Se+r+Oe("else")+Se+_t(a.alternate,t+1,s)),o+=Se+r+Oe("endif"),o}function Uv(e,t,s){const r=s.repeat(t);let n="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;n=`${we(o.lhs)} if ${we(o.test)}`}else n=we(e.iterable);let a=r+Oe("for",we(e.loopvar),"in",n)+Se+_t(e.body,t+1,s);return e.defaultBlock.length>0&&(a+=Se+r+Oe("else")+Se+_t(e.defaultBlock,t+1,s)),a+=Se+r+Oe("endfor"),a}function jv(e,t,s){const r=s.repeat(t),n=we(e.assignee),a=e.value?we(e.value):"",o=r+Oe("set",`${n}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Se+_t(e.body,t+1,s)+Se+r+Oe("endset")}function qv(e,t,s){const r=s.repeat(t),n=Jr(e.args);return r+Oe("macro",`${e.name.value}(${n})`)+Se+_t(e.body,t+1,s)+Se+r+Oe("endmacro")}function Wv(e,t,s){const r=s.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${Jr(e.callerArgs)})`:"",a=we(e.call);let o=r+Oe(`call${n}`,a)+Se;return o+=_t(e.body,t+1,s)+Se,o+=r+Oe("endcall"),o}function Hv(e,t,s){const r=s.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:we(e.filter);let a=r+Oe("filter",n)+Se;return a+=_t(e.body,t+1,s)+Se,a+=r+Oe("endfilter"),a}function we(e){switch(e.type){case"SpreadExpression":return`*${we(e.argument)}`;case"KeywordSpreadExpression":return`**${we(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":{const t=e.value;return Object.is(t,-0)?"-0.0":t%1===0?t.toFixed(1):t.toString()}case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const t=e,s=ru(t),r=ut(t.left,s),n=ut(t.right,s+1);return`${r} ${t.operator.value} ${n}`}case"UnaryExpression":{const t=e,s=t.argument.type==="UnaryExpression"?nu(t):ye.ATOM;return t.operator.value+(t.operator.value==="not"?" ":"")+ut(t.argument,s)}case"CallExpression":{const t=e,s=Jr(t.args);return`${we(t.callee)}(${s})`}case"MemberExpression":{const t=e,s=ut(t.object,ye.ATOM);let r=we(t.property);return!t.computed&&t.property.type!=="Identifier"&&t.property.type!=="IntegerLiteral"&&(r=`(${r})`),t.computed?`${s}[${r}]`:`${s}.${r}`}case"FilterExpression":{const t=e,s=ut(t.operand,ye.FILTER);return t.filter.type==="CallExpression"?`${s} | ${we(t.filter)}`:`${s} | ${t.filter.value}`}case"SelectExpression":{const t=e;return`${ut(t.lhs,ye.LOGICAL_OR)} if ${ut(t.test,ye.LOGICAL_OR)}`}case"TestExpression":{const t=e;return`${ut(t.operand,ye.TEST)} is${t.negate?" not":""} ${t.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const t=Jr(e.value),s=e.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${t}${s[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([s,r])=>`${we(s)}: ${we(r)}`).join(", ")}}`;case"SliceExpression":{const t=e,s=t.start?we(t.start):"",r=t.stop?we(t.stop):"",n=t.step?`:${we(t.step)}`:"";return`${s}:${r}${n}`}case"KeywordArgumentExpression":{const t=e;return`${t.key.value}=${we(t.value)}`}case"Ternary":{const t=e;return`${ut(t.trueExpr,ye.LOGICAL_OR)} if ${ut(t.condition,ye.LOGICAL_OR)} else ${ut(t.falseExpr,ye.CONDITIONAL)}`}default:throw new Error(`Unknown expression type: ${e.type}`)}}var Qv=class{parsed;constructor(e){const t=rv(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Tv(t)}render(e){const t=new Vt;if(zv(t),e)for(const[n,a]of Object.entries(e))t.set(n,a);return new Dv(t).run(this.parsed).value}format(e){return $v(this.parsed,e?.indent||" ")}},Xv={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"},Zr=class wf{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=Xe.existsSync(t),this.exists){this.status=200,this.statusText="OK";let s=Xe.statSync(t);this.headers.set("content-length",s.size.toString()),this.updateContentType();const r=Xe.createReadStream(t);this.body=new ReadableStream({start(n){r.on("data",a=>n.enqueue(a)),r.on("end",()=>n.close()),r.on("error",a=>n.error(a))},cancel(){r.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Xv[t]??"application/octet-stream")}clone(){let t=new wf(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 Xe.promises.readFile(this.filePath)).buffer}async blob(){const t=await Xe.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await Xe.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},en=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(Y.IS_CRYPTO_AVAILABLE){const o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;const t=this._mt,s=(o,i)=>Math.imul(o,i)>>>0,r=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))r.push(o&4294967295);r.length||r.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=s(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let n=1,a=0;for(let o=Math.max(624,r.length);o>0;--o,++n,++a)n>=624&&(t[0]=t[623],n=1),a>=r.length&&(a=0),t[n]=(t[n]^s(t[n-1]^t[n-1]>>>30,1664525))+r[a]+a>>>0;for(let o=623;o>0;--o,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^s(t[n-1]^t[n-1]>>>30,1566083941))-n>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){const r=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^r>>>1^(r&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 s=this._gauss_next;if(this._gauss_next=null,s===null){const r=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(r)*n,this._gauss_next=Math.sin(r)*n}return e+s*t}shuffle(e){for(let t=e.length-1;t>0;--t){const s=32-Math.clz32(t+1);let r=this._int32()>>>32-s;for(;r>t;)r=this._int32()>>>32-s;const n=e[t];e[t]=e[r],e[r]=n}}choices(e,t){return e[au(this._random_fn,t)]}};function au(e,t){let s=0;for(let n=0;n<t.length;++n)s+=t[n];let r=e()*s;for(let n=0;n<t.length;++n)if(r-=t[n],r<0)return n;return t.length-1}var yt=new en,Ra=Object.freeze({Random:en,seed:yt.seed.bind(yt),random:yt.random.bind(yt),gauss:yt.gauss.bind(yt),shuffle:yt.shuffle.bind(yt),choices:yt.choices.bind(yt)}),Yv=e=>au(Ra.random,e),Kv=new en,ou=class{constructor(e){this.path=e}async match(e){let t=wt.join(this.path,e),s=new Zr(t);if(s.exists)return s}async put(e,t,s=void 0){const r=wt.join(this.path,e),n=Y.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Kv._int32().toString(36),o=r+`.tmp.${n}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let c=0;await Xe.promises.mkdir(wt.dirname(r),{recursive:!0});const d=Xe.createWriteStream(o),u=t.body.getReader();for(;;){const{done:_,value:h}=await u.read();if(_)break;await new Promise((f,g)=>{d.write(h,m=>{if(m){g(m);return}f()})}),c+=h.length;const p=l?c/l*100:0;s?.({progress:p,loaded:c,total:l})}await new Promise((_,h)=>{d.close(p=>p?h(p):_())}),await Xe.promises.rename(o,r)}catch(i){try{await Xe.promises.unlink(o)}catch{}throw i}}async delete(e){let t=wt.join(this.path,e);try{return await Xe.promises.unlink(t),!0}catch{return!1}}},Jv={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"},iu=100,Zv=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function tn(...e){return e=e.map((t,s)=>(s&&(t=t.replace(new RegExp("^/"),"")),s!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function as(e,t=null,s=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||s&&!s.includes(r.hostname))}function ey(e){return!(!Zv.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function $a(e,t={},...s){return JSON.stringify([e,t.revision??"main",t.cache_dir??null,t.local_files_only??!1,...s])}var Ga=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name="ModelFileNotFoundError",this.status=t}},ty=new Set([401,403,404]);function lu(e,t,s){if(!s)return null;const n=`${Jv[e]??`Error (${e}) occurred while trying to load file`}: "${t}".`;throw ty.has(e)?new Ga(n,{status:e}):Error(n)}async function sy(e,t,s){const r=e.headers.get("Content-Length");let n=r?parseInt(r,10):s??0;r===null&&!s&&Q.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(n),o=0;const i=e.body.getReader();async function l(){const{done:c,value:d}=await i.read();if(c)return;const u=o+d.length;if(u>n){n=u;const h=new Uint8Array(n);h.set(a),a=h}a.set(d,o),o=u;const _=o/n*100;return t({progress:_,loaded:o,total:n}),l()}return await l(),a}function cu(e){return as(e,["blob:"])}function Va(e,{allowUnresolved:t=!1}={}){let s;if(typeof location<"u"&&location.href)s=location.href;else if(typeof{url:self.location.href}<"u"&&self.location.href)s=self.location.href;else return e;try{return new URL(e,s).href}catch(r){if(!t)throw r;return e}}var du="SHA-256",ry="experimental_transformers-hash-cache",uu=e=>({algorithm:du,value:e}),_u=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(ry),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{const t=await this._getFileHash(e);if(t)try{const r=await(await navigator.crossOriginStorage.requestFileHandle(uu(t))).getFile();return new Response(r,{headers:{"Content-Length":String(r.size)}})}catch{return}};put=async(e,t)=>{const s=await this._getFileHash(e);if(s){const r=await t.blob();await this._storeBlobInCOS(r,s)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{const r=await(await navigator.crossOriginStorage.requestFileHandle(uu(t),{create:!0,origins:"*"})).createWritable();await r.write(e),await r.close()};_processAndStore=async(e,t)=>{try{const s=[];for await(const a of t)s.push(a);const r=new Blob(s),n=await this._getBlobHash(r);await this._storeBlobInCOS(r,n);try{await(await this._getHashCache()).put(e,new Response(n))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{const t=await this._getHashCache(),s=await t.match(e);if(s)return s.text();const r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const r=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return r?r[1]:null}catch{return null}};_getBlobHash=async e=>{const t=await e.arrayBuffer(),s=await crypto.subtle.digest(du,t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}};async function Ua(e=null){let t=null;if(ee.useCustomCache){if(!ee.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ee.customCache.match||!ee.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=ee.customCache}if(!t&&ee.experimental_useCrossOriginStorage&&_u.isAvailable()&&(t=new _u),!t&&ee.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ee.cacheKey)}catch(s){Q.warn("An error occurred while opening the browser cache:",s)}}if(!t&&ee.useFSCache){if(!Y.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new ou(e??ee.cacheDir)}return t}async function ny(e,...t){for(let s of t)try{let r=await e.match(s);if(r)return r}catch{continue}}var ay=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;const t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,t),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}},oy=100,ja=new ay(oy);function hu(e,t){const s=ja.get(e);if(s!==void 0)return s;const r=t().then(n=>n,n=>(ja.delete(e),Promise.reject(n)));return ja.put(e,r),r}async function iy(e){if(!as(e,["http:","https:"]))return null;const t=pu(e);return t.set("Range","bytes=0-0"),ee.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function or(e,t,s={}){const r=$a(e,s,t);return hu(r,()=>ly(e,t,s))}async function ly(e,t,s){const r=await Ua(s?.cache_dir),{localPath:n,remoteURL:a,proposedCacheKey:o,validModelId:i}=fu(e,t,s,r),l=await mu(r,n,o);if(l!==void 0&&typeof l!="string"){const c=l.headers.get("content-length"),d=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:d||void 0,fromCache:!0}}if(ee.allowLocalModels&&!as(n,["http:","https:"]))try{const d=await ir(n);if(typeof d!="string"&&d.status!==404){const u=d.headers.get("content-length"),_=d.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(ee.allowRemoteModels&&!s.local_files_only&&i){const c=await iy(a);if(c&&c.status>=200&&c.status<300){let d;const u=c.headers.get("content-type");if(c.status===206){const _=c.headers.get("content-range");if(_){const h=_.match(/bytes \d+-\d+\/(\d+)/);h&&(d=parseInt(h[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(d===void 0){const _=c.headers.get("content-length");d=_?parseInt(_,10):void 0}return{exists:!0,size:d,contentType:u||void 0,fromCache:!1}}c&&c.status!==404&&c.status!==416&&lu(c.status,a,!0)}return{exists:!1,fromCache:!1}}async function ir(e){return ee.useFS&&!as(e,["http:","https:","blob:"])?new Zr(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ee.fetch(e,{headers:pu(e)})}function pu(e){const t=typeof process<"u"&&process?.release?.name==="node",s=new Headers;if(t){const r=!!Ta?.TESTING_REMOTELY,n=ee.version;if(s.set("User-Agent",`transformers.js/${n}; is_ci/${r};`),as(e,["http:","https:"],["huggingface.co","hf.co"])){const o=Ta?.HF_TOKEN??Ta?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}}return s}function fu(e,t,s={},r=null){const n=s.revision??"main",a=tn(e,t),o=ey(e),i=o?tn(ee.localModelPath,a):a,l=tn(ee.remoteHost,ee.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),c=r instanceof ou?n==="main"?a:tn(e,n,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function mu(e,t,s){if(e)return await ny(e,t,s)}async function cy(e,t,s,r,n,a,o={}){if(await s.match(r)===void 0&&!(typeof Cache<"u"&&s instanceof Cache&&!as(Va(r,{allowUnresolved:!0}),["http:","https:"])))if(a){if(typeof n!="string"){const i=new Headers(n.headers);i.set("content-length",a.byteLength.toString()),await s.put(r,new Response(a,{headers:i})).catch(l=>{Q.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>Bt(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await s.put(r,n,i)}}async function dy(e,t,s=!0,r={},n=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=fu(e,t,r,a);let u,_=!1,h;h=await mu(a,i,c);const p=h!==void 0;if(p)u=c;else{if(ee.allowLocalModels)if(as(o,["http:","https:"])){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!ee.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{h=await ir(i),u=i}catch(w){Q.warn(`Unable to load from local path "${i}": "${w}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(r.local_files_only||!ee.allowRemoteModels){if(s)throw new Ga(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw new Ga(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(h=await ir(l),h.status!==200)return lu(h.status,l,s);u=c}_=a&&typeof Response<"u"&&h instanceof Response&&h.status===200}Bt(r.progress_callback,{status:"download",name:e,file:t});let f;if(!(Y.IS_NODE_ENV&&n)){let m;if(typeof h!="string")if(!r.progress_callback)m=new Uint8Array(await h.arrayBuffer());else if(p&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))m=new Uint8Array(await h.arrayBuffer()),Bt(r.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:m.length,total:m.length});else{let w;const y=h.headers.get("content-length");if(y)w=parseInt(y,10);else try{const v=await or(e,t,r);v.size&&(w=v.size)}catch{}m=await sy(h,v=>{Bt(r.progress_callback,{status:"progress",name:e,file:t,...v})},w)}f=m}if(_&&u&&typeof h!="string"&&await cy(e,t,a,u,h,f,r),Y.IS_NODE_ENV&&n&&r.progress_callback&&typeof h!="string"){const m=parseInt(h.headers.get("content-length"),10)||0;Bt(r.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:m,total:m})}if(Bt(r.progress_callback,{status:"done",name:e,file:t}),f){if(!Y.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return f}if(h instanceof Zr)return h.filePath;const g=await a?.match(u);if(g instanceof Zr)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g=="string")return g;throw new Error("Unable to get model file path or buffer.")}var qa=new Map;async function sn(e,t,s=!0,r={},n=!1){if(!ee.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!ee.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}const a=$a(e,r,t,s,n),{progress_callback:o}=r,i=o instanceof $r?o.loads:qa;let l=i.get(a);return l||(Bt(o,{status:"initiate",name:e,file:t}),l=Ua(r.cache_dir).then(c=>dy(e,t,s,r,n,c)),i===qa&&(l=l.finally(()=>qa.delete(a))),i.set(a,l)),await l}async function Wa(e,t,s=!0,r={}){const n=await sn(e,t,s,r,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function Mt(e,t,s=!0,r={}){const n=await Wa(e,t,s,r);return n===null?{}:JSON.parse(n)}function uy(e,[t,s,r],[n,a],o="bilinear",i=!1){const l=a/r,c=n/s,d=new e.constructor(n*a*t),u=s*r,_=n*a;for(let h=0;h<n;++h)for(let p=0;p<a;++p){const f=h*a+p,g=(p+.5)/l-.5,m=(h+.5)/c-.5;let w=Math.floor(g),y=Math.floor(m);const v=Math.min(w+1,r-1),M=Math.min(y+1,s-1);w=Math.max(w,0),y=Math.max(y,0);const E=g-w,A=m-y,S=(1-E)*(1-A),C=E*(1-A),z=(1-E)*A,R=E*A,N=y*r,O=M*r,$=N+w,L=N+v,D=O+w,se=O+v;for(let U=0;U<t;++U){const W=U*u;d[U*_+f]=S*e[W+$]+C*e[W+L]+z*e[W+D]+R*e[W+se]}}return d}function _y(e,t,s){const r=new Array(s.length),n=new Array(s.length);for(let i=s.length-1,l=1;i>=0;--i)n[i]=l,r[i]=t[s[i]],l*=r[i];const a=s.map((i,l)=>n[s.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,r]}function Ne(e){const t=ke(e)[0],s=e.map(a=>Math.exp(a-t)),r=s.reduce((a,o)=>a+o,0);return s.map(a=>a/r)}function hy(e){const t=ke(e)[0];let s=0;for(let a=0;a<e.length;++a)s+=Math.exp(e[a]-t);const r=Math.log(s);return e.map(a=>a-t-r)}function Ha(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],s=r);return[t,s]}function ke(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],s=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],s=r);return[t,s]}function gu(e){return e>0&&(e&e-1)===0}var wu=class{constructor(e){if(this.size=e|0,this.size<=1||!gu(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;s<this.table.length;s+=2){const r=Math.PI*s/this.size;this.table[s]=Math.cos(r),this.table[s+1]=-Math.sin(r)}let t=0;for(let s=1;this.size>s;s<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let r=0;r<this._width;r+=2){const n=this._width-r-2;this._bitrev[s]|=(s>>>r&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const s=t||new Array(e.length>>>1);for(let r=0;r<e.length;r+=2)s[r>>>1]=e[r];return s}toComplexArray(e,t){const s=t||this.createComplexArray();for(let r=0;r<s.length;r+=2)s[r]=e[r>>>1],s[r+1]=0;return s}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let s=0;s<e.length;++s)e[s]/=this.size}_transform4(e,t,s){const r=this._csize;let a=1<<this._width,o=r/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<r;i+=o,++l){const u=c[l];this._singleTransform2(t,e,i,u,a)}else for(i=0,l=0;i<r;i+=o,++l){const u=c[l];this._singleTransform4(t,e,i,u,a,s)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=r/a<<1;const u=o>>>2;for(i=0;i<r;i+=o){const _=i+u-1;for(let h=i,p=0;h<_;h+=2,p+=a){const f=h,g=f+u,m=g+u,w=m+u,y=e[f],v=e[f+1],M=e[g],E=e[g+1],A=e[m],S=e[m+1],C=e[w],z=e[w+1],R=d[p],N=s*d[p+1],O=M*R-E*N,$=M*N+E*R,L=d[2*p],D=s*d[2*p+1],se=A*L-S*D,U=A*D+S*L,W=d[3*p],x=s*d[3*p+1],k=C*W-z*x,F=C*x+z*W,K=y+se,H=v+U,Le=y-se,_e=v-U,de=O+k,Ce=$+F,ve=s*(O-k),ue=s*($-F);e[f]=K+de,e[f+1]=H+Ce,e[g]=Le+ue,e[g+1]=_e-ve,e[m]=K-de,e[m+1]=H-Ce,e[w]=Le-ue,e[w+1]=_e+ve}}}}_singleTransform2(e,t,s,r,n){const a=e[r],o=e[r+1],i=e[r+n],l=e[r+n+1];t[s]=a+i,t[s+1]=o+l,t[s+2]=a-i,t[s+3]=o-l}_singleTransform4(e,t,s,r,n,a){const o=n*2,i=n*3,l=e[r],c=e[r+1],d=e[r+n],u=e[r+n+1],_=e[r+o],h=e[r+o+1],p=e[r+i],f=e[r+i+1],g=l+_,m=c+h,w=l-_,y=c-h,v=d+p,M=u+f,E=a*(d-p),A=a*(u-f);t[s]=g+v,t[s+1]=m+M,t[s+2]=w+A,t[s+3]=y-E,t[s+4]=g-v,t[s+5]=m-M,t[s+6]=w-A,t[s+7]=y+E}_realTransform4(e,t,s){const r=this._csize;let a=1<<this._width,o=r/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<r;i+=o,++l){const _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<r;i+=o,++l){const _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,s)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=r/a<<1;const _=o>>>1,h=_>>>1,p=h>>>1;for(i=0;i<r;i+=o)for(let f=0,g=0;f<=p;f+=2,g+=a){const m=i+f,w=m+h,y=w+h,v=y+h,M=e[m],E=e[m+1],A=e[w],S=e[w+1],C=e[y],z=e[y+1],R=e[v],N=e[v+1],O=M,$=E,L=d[g],D=s*d[g+1],se=A*L-S*D,U=A*D+S*L,W=d[2*g],x=s*d[2*g+1],k=C*W-z*x,F=C*x+z*W,K=d[3*g],H=s*d[3*g+1],Le=R*K-N*H,_e=R*H+N*K,de=O+k,Ce=$+F,ve=O-k,ue=$-F,Ke=se+Le,ds=U+_e,Qs=s*(se-Le),_f=s*(U-_e);if(e[m]=de+Ke,e[m+1]=Ce+ds,e[w]=ve+_f,e[w+1]=ue-Qs,f===0){e[y]=de-Ke,e[y+1]=Ce-ds;continue}if(f===p)continue;const hf=i+h-f,pf=i+_-f;e[hf]=ve-s*_f,e[hf+1]=-ue-s*Qs,e[pf]=de-s*Ke,e[pf+1]=-Ce+s*ds}}const u=r>>>1;for(let _=2;_<u;_+=2)e[r-_]=e[_],e[r-_+1]=-e[_+1]}_singleRealTransform2(e,t,s,r,n){const a=e[r],o=e[r+n];t[s]=a+o,t[s+1]=0,t[s+2]=a-o,t[s+3]=0}_singleRealTransform4(e,t,s,r,n,a){const o=n*2,i=n*3,l=e[r],c=e[r+n],d=e[r+o],u=e[r+i],_=l+d,h=l-d,p=c+u,f=a*(c-u);t[s]=_+p,t[s+1]=0,t[s+2]=h,t[s+3]=-f,t[s+4]=_-p,t[s+5]=0,t[s+6]=h,t[s+7]=f}},py=class{constructor(e){const t=2*(e-1),s=2*(2*e-1),r=2**Math.ceil(Math.log2(s));this.bufferSize=r,this._a=t;const n=new Float64Array(s),a=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<s>>1;++c){const d=(c+1-e)**2/2,u=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),h=2*c;n[h]=u*Math.cos(_),n[h+1]=u*Math.sin(_),a[h]=n[h],a[h+1]=-n[h+1]}this._slicedChirpBuffer=n.subarray(t,s),this._f=new wu(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,s){const r=this._buffer1,n=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(s)for(let d=0;d<l.length;d+=2){const u=d+1,_=d>>1,h=t[_];r[d]=h*l[d],r[u]=h*l[u]}else for(let d=0;d<l.length;d+=2){const u=d+1;r[d]=t[d]*l[d]-t[u]*l[u],r[u]=t[d]*l[u]+t[u]*l[d]}this._f.transform(a,r);for(let d=0;d<i.length;d+=2){const u=d+1;n[d]=a[d]*i[d]-a[u]*i[u],n[u]=a[d]*i[u]+a[u]*i[d]}this._f.inverseTransform(o,n);for(let d=0;d<o.length;d+=2){const u=o[d+c],_=o[d+c+1],h=l[d],p=l[d+1];e[d]=u*h-_*p,e[d+1]=u*p+_*h}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},fy=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=gu(e),this.isPowerOfTwo?(this.fft=new wu(e),this.outputBufferSize=2*e):(this.fft=new py(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function my(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const s=new e.constructor(e.length),r=new e.constructor(t),n=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-n;i<=n;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),r[o++]=e[l]}r.sort(),s[a]=r[n]}return s}function lr(e,t){const s=Math.pow(10,t);return Math.round(e*s)/s}function gy(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function wy(e){const t=e.length,s=e[0].length,r=[t+1,s+1],n=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));n[0][0]=0;const a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let d=1;d<r[1];++d)for(let u=1;u<r[0];++u){const _=n[u-1][d-1],h=n[u-1][d],p=n[u][d-1];let f,g;_<h&&_<p?(f=_,g=0):h<_&&h<p?(f=h,g=1):(f=p,g=2),n[u][d]=e[u-1][d-1]+f,a[u][d]=g}for(let d=0;d<r[1];++d)a[0][d]=2;for(let d=0;d<r[0];++d)a[d][0]=1;let o=t,i=s,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var vy=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0;const d=(l&32768)<<16,u=(l&31744)>>10;let _=l&1023;if(u===31)c=d|2139095040|_<<13;else if(u===0)if(_===0)c=d;else{let h=113;for(;(_&1024)===0;)_<<=1,--h;_&=-1025,c=d|h<<23|_<<13}else c=d|u+112<<23|_<<13;o[0]=c,e[l]=i[0]}}const s=t.length,r=e,n=new Float32Array(s);for(let a=0;a<s;++a)n[a]=r[t[a]];return n}})(),yy={};async function vu(e){const t=e.split("/").pop();let s;try{if(s=await Ua(),s){const n=await s.match(e);if(n)return n}}catch(n){Q.warn(`Failed to load ${t} from cache:`,n)}const r=await ee.fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(s)try{await s.put(e,r.clone())}catch(n){Q.warn(`Failed to cache ${t}:`,n)}return r}async function My(e){const t=await vu(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(s){return Q.warn("Failed to read WASM binary:",s),null}}async function by(e){if(Y.IS_SERVICE_WORKER_ENV||Y.IS_CHROME_AVAILABLE)return e;const t=await vu(e);if(!t||typeof t=="string")return null;try{let s=await t.text();s=s.replaceAll("globalThis.process?.versions?.node","false");const r=new Blob([s],{type:"text/javascript"});return URL.createObjectURL(r)}catch(s){return Q.warn("Failed to read WASM factory:",s),null}}var xy=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 yu(e){return e<=at.DEBUG?0:e<=at.INFO?2:e<=at.WARNING||e<=at.ERROR?3:4}var ky={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},st=[],Qa,ys,Mu=Symbol.for("onnxruntime");if(Mu in globalThis)ys=globalThis[Mu];else if(Y.IS_NODE_ENV){switch(ys=yy,process.platform){case"win32":st.push("dml");break;case"linux":process.arch==="x64"&&st.push("cuda");break;case"darwin":st.push("coreml");break}st.push("webgpu"),st.push("cpu"),Qa=["cpu"]}else ys=Qf,Y.IS_WEBNN_AVAILABLE&&st.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Y.IS_WEBGPU_AVAILABLE&&st.push("webgpu"),st.push("wasm"),Qa=["wasm"];var Ey=ys.InferenceSession;function Ty(e=null){if(!e)return Qa;switch(e){case"auto":return st;case"gpu":return st.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(st.includes(e))return[xy[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${st.join(", ")}.`)}var bu=Promise.resolve(),Ms=null;async function Ay(){if(Ms)return Ms;if(!(ee.useWasmCache&&typeof Pe?.wasm?.wasmPaths=="object"&&Pe?.wasm?.wasmPaths?.wasm&&Pe?.wasm?.wasmPaths?.mjs)){if(Y.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Ms=Promise.resolve(),Ms}return Ms=(async()=>{const t=Pe.wasm.wasmPaths;let s=!1;await Promise.all([t.wasm&&!cu(t.wasm)?(async()=>{try{const r=await My(Va(t.wasm));r&&(Pe.wasm.wasmBinary=r,s=!0)}catch(r){Q.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),t.mjs&&!cu(t.mjs)?(async()=>{try{const r=await by(Va(t.mjs));r&&(Pe.wasm.wasmPaths.mjs=r)}catch(r){Q.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()]),s||(Pe.wasm.wasmPaths.mjs=t.mjs)})(),Ms}async function xu(e,t,s){await Ay();const r=yu(ee.logLevel??at.WARNING),n=()=>Ey.create(e,{logSeverityLevel:r,...t}),a=await(Y.IS_WEB_ENV?bu=bu.then(n):n());return a.config=s,a}var ku=Promise.resolve();async function Eu(e,t){const s=()=>e.run(t);return Y.IS_WEB_ENV?ku=ku.then(s):s()}function Tu(e){return e instanceof ys.Tensor}var Pe=ys?.env;function Xa(){return Pe?.wasm?.proxy}if(Pe){let e=function(t){const s=yu(t);Pe.logLevel=ky[s]};if(Pe.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Pe.versions?.web&&!Pe.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Pe.versions.web}/dist/`;let s=".asyncify";Y.IS_SAFARI_BELOW_26&&!Y.IS_WEBGPU_AVAILABLE&&(s=""),Pe.wasm.wasmPaths={mjs:`${t}ort-wasm-simd-threaded${s}.mjs`,wasm:`${t}ort-wasm-simd-threaded${s}.wasm`}}Pe.wasm.proxy=!1}Pe.webgpu&&(Pe.webgpu.powerPreference="high-performance"),e(ee.logLevel??at.WARNING),ee.backends.onnx={...Pe,setLogLevel:e}}var Ut=async(e,t,s)=>{const r=await xu(new Uint8Array(e),t);return(async n=>{const a=Xa(),o=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await Eu(r,o);return Array.isArray(s)?s.map(l=>new P(i[l])):new P(i[s])})},bs=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ut([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Ut([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Ut([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Ut([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Ut([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Ut([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Ut([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Ut([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}},Cy=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"}),Ya=Y.IS_NODE_ENV?"cpu":"wasm";function Au(e,t,{warn:s}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(s&&s(`device not specified for "${t}". Using the default device (${Ya}).`),Ya):Ya}var Sy=(function(){let e;return async function(){if(e===void 0)if(!Y.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),Te=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"}),Cu=Te.fp32,Su=Object.freeze({[Cy.wasm]:Te.q8}),Ka=Object.freeze({[Te.fp32]:"",[Te.fp16]:"_fp16",[Te.int8]:"_int8",[Te.uint8]:"_uint8",[Te.q8]:"_quantized",[Te.q4]:"_q4",[Te.q2]:"_q2",[Te.q1]:"_q1",[Te.q4f16]:"_q4f16",[Te.q2f16]:"_q2f16",[Te.q1f16]:"_q1f16",[Te.bnb4]:"_bnb4"});function Pu(e,t,s,{configDtype:r=null,warn:n}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===Te.auto){if(r){const l=typeof r=="string"?r:r?.[t];if(l&&l!==Te.auto&&Te.hasOwnProperty(l))return l}i=Su[s]??Cu}else a&&Te.hasOwnProperty(a)?i=a:i=Su[s]??Cu;return o&&n&&n(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${s}).`),i}var cr=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}),P=class xe{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...t){return Tu(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new am(t[0],t[1],t[2]),new Proxy(this,{get:(s,r)=>{if(typeof r=="string"){let n=Number(r);if(Number.isInteger(n))return s._getitem(n)}return s[r]},set:(s,r,n)=>s[r]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...s]=this.dims;if(s.length>0){const r=s.reduce((n,a)=>n*a);for(let n=0;n<t;++n)yield this._subarray(n,r,s)}else yield*this.data}_getitem(t){const[s,...r]=this.dims;if(t=bt(t,s),r.length>0){const n=r.reduce((a,o)=>a*o);return this._subarray(t,n,r)}else return new xe(this.type,[this.data[t]],r)}_subarray(t,s,r){const n=t*s,a=(t+1)*s,o="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new xe(this.type,o,r)}item(){const t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return Py(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const t=this.data;for(let s=0;s<t.length;++s)t[s]=1/(1+Math.exp(-t[s]));return this}map(t){return this.clone().map_(t)}map_(t){const s=this.data;for(let r=0;r<s.length;++r)s[r]=t(s[r],r,s);return this}mul(t){return this.clone().mul_(t)}mul_(t){const s=this.data;for(let r=0;r<s.length;++r)s[r]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const s=this.data;for(let r=0;r<s.length;++r)s[r]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const s=this.data;for(let r=0;r<s.length;++r)s[r]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const s=this.data;for(let r=0;r<s.length;++r)s[r]-=t;return this}remainder(t){return this.clone().remainder_(t)}remainder_(t){const s=this.data,n=s instanceof BigInt64Array||s instanceof BigUint64Array?BigInt(t):Number(t);if((n===0||n===0n)&&(this.type.includes("int")||this.type==="bool"))throw new RangeError("Division by zero");if(n<0&&(this.type.startsWith("uint")||this.type==="bool"))throw new RangeError("Negative divisors are not supported for unsigned or boolean tensors");for(let a=0;a<s.length;++a){const o=s[a]%n,i=o<0&&n>0||o>0&&n<0;s[a]=i?o+n:o}return this}clone(){return new xe(this.type,this.data.slice(),this.dims.slice())}slice(...t){const s=[],r=[];for(let d=0;d<this.dims.length;++d){let u=t[d];if(u==null)r.push([0,this.dims[d]]),s.push(this.dims[d]);else if(typeof u=="number")u=bt(u,this.dims[d],d),r.push([u,u+1]);else if(Array.isArray(u)&&u.length===2){let[_,h]=u;if(_=_===null?0:bt(_,this.dims[d],d,!1),h=h===null?this.dims[d]:bt(h,this.dims[d],d,!1),_>h)throw new Error(`Invalid slice: ${u}`);const p=[Math.max(_,0),Math.min(h,this.dims[d])];r.push(p),s.push(p[1]-p[0])}else throw new Error(`Invalid slice: ${u}`)}const n=r.map(([d,u])=>u-d),a=n.reduce((d,u)=>d*u),o=this.data,i=new o.constructor(a),l=this.stride();let c=!0;for(let d=1;d<n.length;++d)if(r[d][0]!==0||r[d][1]!==this.dims[d]){c=!1;break}if(c){const d=r[0][0]*l[0],u=r[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,u));else if(Array.isArray(o)){const _=o.slice(d,u);for(let h=0;h<_.length;++h)i[h]=_[h]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let u=0;for(let _=n.length-1,h=d;_>=0;--_){const p=n[_];u+=(h%p+r[_][0])*l[_],h=Math.floor(h/p)}i[d]=o[u]}return new xe(this.type,i,s)}permute(...t){return Fy(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,s=!1){return this.norm(1,t,s)}norm(t="fro",s=null,r=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const n=this.data,a=n instanceof BigInt64Array||n instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a?(o=(u,_)=>u+_,i=0n):(o=(u,_)=>u+_**t,i=0),s===null){let u=n.reduce(o,i);return t!==1&&(u=u**(1/t)),new xe(this.type,[u],[])}const[l,c,d]=dr(o,this,s,r);if(t!==1)for(let u=0;u<c.length;++u)c[u]=c[u]**(1/t);return new xe(l,c,d)}normalize_(t=2,s=1){s=bt(s,this.dims.length);const r=this.norm(t,s,!0),n=this.data,a=r.data;for(let o=0;o<n.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){const u=this.dims[l];if(l!==s){const _=c%u;i+=_*d,d*=this.dims[l]}c=Math.floor(c/u)}n[o]/=a[i]}return this}normalize(t=2,s=1){return this.clone().normalize_(t,s)}stride(){return Za(this.dims)}squeeze(t=null){return new xe(this.type,this.data,Lu(this.dims,t))}squeeze_(t=null){return this.dims=Lu(this.dims,t),this}unsqueeze(t){return new xe(this.type,this.data,Ou(this.dims,t))}unsqueeze_(t){return this.dims=Ou(this.dims,t),this}flatten_(t=0,s=-1){s=(s+this.dims.length)%this.dims.length;let r=this.dims.slice(0,t),n=this.dims.slice(t,s+1),a=this.dims.slice(s+1);return this.dims=[...r,n.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,s=-1){return this.clone().flatten_(t,s)}view(...t){let s=-1;for(let n=0;n<t.length;++n)if(t[n]===-1){if(s!==-1)throw new Error("Only one dimension can be inferred");s=n}const r=this.data;if(s!==-1){const n=t.reduce((a,o,i)=>i!==s?a*o:a,1);t[s]=r.length/n}return new xe(this.type,r,t)}neg_(){const t=this.data;for(let s=0;s<t.length;++s)t[s]=-t[s];return this}neg(){return this.clone().neg_()}gt(t){const s=new Uint8Array(this.data.length),r=this.data;for(let n=0;n<r.length;++n)s[n]=r[n]>t?1:0;return new xe("bool",s,this.dims)}lt(t){const s=new Uint8Array(this.data.length),r=this.data;for(let n=0;n<r.length;++n)s[n]=r[n]<t?1:0;return new xe("bool",s,this.dims)}clamp_(t,s){const r=this.data;for(let n=0;n<r.length;++n)r[n]=Math.min(Math.max(r[n],t),s);return this}clamp(t,s){return this.clone().clamp_(t,s)}round_(){const t=this.data;for(let s=0;s<t.length;++s)t[s]=Math.round(t[s]);return this}round(){return this.clone().round_()}mean(t=null,s=!1){return Ja(this,t,s)}min(t=null,s=!1){if(t===null){const o=Ha(this.data)[0];return new xe(this.type,[o],[])}const[r,n,a]=dr((o,i)=>Math.min(o,i),this,t,s,1/0);return new xe(r,n,a)}max(t=null,s=!1){if(t===null){const o=ke(this.data)[0];return new xe(this.type,[o],[])}const[r,n,a]=dr((o,i)=>Math.max(o,i),this,t,s,-1/0);return new xe(r,n,a)}argmin(t=null,s=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const r=Ha(this.data)[1];return new xe("int64",[BigInt(r)],[])}argmax(t=null,s=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const r=ke(this.data)[1];return new xe("int64",[BigInt(r)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(d=>d===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,u=Array(d).fill(1).concat(this.dims);return new xe(this.type,this.data.slice(),u)}const s=t.length-this.dims.length,r=Array(s).fill(1).concat(this.dims),n=r.map((d,u)=>d*t[u]),a=n.reduce((d,u)=>d*u,1),o=this.data,i=new o.constructor(a),l=Za(r),c=Za(n);for(let d=0;d<a;++d){let u=d,_=0;for(let h=0;h<n.length;++h){const p=Math.floor(u/c[h]);u=u%c[h];const f=p%r[h];_+=f*l[h]}i[d]=o[_]}return new xe(this.type,i,n)}tile(...t){if(t.length<this.dims.length){const s=this.dims.length-t.length;t=Array(s).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!cr.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let s;const r=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(r&&!n)s=Number;else if(!r&&n)["float16","float32","float64"].includes(this.type)?s=a=>BigInt(Math.floor(a)):s=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new xe(t,vy(this.data),this.dims);return new xe(t,cr[t].from(this.data,s),this.dims)}};function Py(e,t){const s=e.length,r=t.length===0?1:t.reduce((a,o)=>a*o);if(s!==r)throw Error(`cannot reshape array of size ${s} into shape (${t})`);let n=e;for(let a=t.length-1;a>=0;a--)n=n.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return n[0]}function Fy(e,t){const[s,r]=_y(e.data,e.dims,t);return new P(e.type,s,r)}function Fu(e,[t,s],r="bilinear",n=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=uy(e.data,[a,o,i],[t,s],r,n);return new P(e.type,l,[a,t,s])}async function ht(e,{size:t=null,mode:s="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let r;if(t.length===2)r=[...e.dims.slice(0,2),...t];else if(t.length===3)r=[e.dims[0],...t];else if(t.length===4)r=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(s==="nearest")n=await bs.nearest_interpolate_4d;else if(s==="bilinear")n=await bs.bilinear_interpolate_4d;else if(s==="bicubic")n=await bs.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${s}`);const a=new P("int64",new BigInt64Array(r.map(BigInt)),[r.length]);return await n({x:e,s:a})}async function Iy(e,t){return await(await bs.matmul)({a:e,b:t})}async function xs(e,t){const s=await bs.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await s({x:e,k:new P("int64",[BigInt(t)],[1])})}var rn=e=>new P("int64",e,[e.length]);async function Iu(e,t,s,r,n){return await(await bs.slice)({x:e,s:rn(t),e:rn(s),a:rn(r),t:rn(new Array(r.length).fill(1))})}function Ly(e,t){const s=e.data,r=t.data,n=[e.dims[0],e.dims[2]],a=new s.constructor(n[0]*n[1]),[o,i,l]=e.dims;let c=0;for(let d=0;d<o;++d){const u=d*l*i;for(let _=0;_<l;++_){let h=0,p=0;const f=d*i,g=u+_;for(let w=0;w<i;++w){const y=Number(r[f+w]);p+=y,h+=s[g+w*l]*y}const m=h/p;a[c++]=m}}return new P(e.type,a,n)}function Lu(e,t){return e=e.slice(),t===null?e=e.filter(s=>s!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((s,r)=>s!==1||!t.includes(r))),e}function Ou(e,t){return t=bt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function bt(e,t,s=null,r=!0){if(e<-t||e>=t){if(r)throw new Error(`IndexError: index ${e} is out of bounds for dimension${s===null?"":" "+s} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function fe(e,t=0){t=bt(t,e[0].dims.length);const s=e[0].dims.slice();s[t]=e.reduce((o,i)=>o+i.dims[t],0);const r=s.reduce((o,i)=>o*i,1),n=new e[0].data.constructor(r),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;n.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){const{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let u=0;for(let _=c.length-1,h=d,p=1;_>=0;--_){const f=c[_];let g=h%f;_===t&&(g+=o),u+=g*p,p*=s[_],h=Math.floor(h/f)}n[u]=l[d]}o+=c[t]}}return new P(a,n,s)}function Ct(e,t=0){return fe(e.map(s=>s.unsqueeze(t)),t)}function dr(e,t,s,r=!1,n=null){const a=t.data,o=t.dims;s=bt(s,o.length);const i=o.slice();i[s]=1;const l=new a.constructor(a.length/o[s]);n!==null&&l.fill(n);for(let c=0;c<a.length;++c){let d=0;for(let u=o.length-1,_=c,h=1;u>=0;--u){const p=o[u];if(u!==s){const f=_%p;d+=f*h,h*=i[u]}_=Math.floor(_/p)}l[d]=e(l[d],a[c],c,d)}return r||i.splice(s,1),[t.type,l,i]}function Oy(e,t=null,s=1,r=!1){const n=e.data,a=e.dims;if(t===null){const h=n.reduce((m,w)=>m+w,0)/n.length,p=Math.sqrt(n.reduce((m,w)=>m+(w-h)**2,0)/(n.length-s)),f=new P(e.type,[h],[]);return[new P(e.type,[p],[]),f]}t=bt(t,a.length);const o=Ja(e,t,r),i=o.data,[l,c,d]=dr((_,h,p,f)=>_+(h-i[f])**2,e,t,r);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-s));return[new P(l,c,d),o]}function Ja(e,t=null,s=!1){const r=e.dims,n=e.data;if(t===null){const l=n.reduce((c,d)=>c+d,0);return new P(e.type,[l/n.length],[])}t=bt(t,r.length);const[a,o,i]=dr((l,c)=>l+c,e,t,s);if(r[t]!==1)for(let l=0;l<o.length;++l)o[l]/=r[t];return new P(a,o,i)}function Za(e){const t=new Array(e.length);for(let s=e.length-1,r=1;s>=0;--s)t[s]=r,r*=e[s];return t}function eo(e,t,s,r){const n=e.reduce((a,o)=>a*o,1);return new P(s,new r(n).fill(t),e)}function Re(e,t){let s,r;if(typeof t=="number")s="float32",r=Float32Array;else if(typeof t=="bigint")s="int64",r=BigInt64Array;else if(typeof t=="boolean")s="bool",r=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return eo(e,t,s,r)}function to(e,t){return Re(e.dims,t)}function qe(e){return eo(e,1n,"int64",BigInt64Array)}function so(e){return qe(e.dims)}function Nu(e){return eo(e,0n,"int64",BigInt64Array)}function ro(e){return Nu(e.dims)}function Ny(e){const t=e.reduce((s,r)=>s*r,1);return new P("float32",Float32Array.from({length:t},()=>Ra.gauss()),e)}function zy(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const s=t==="binary",r=s?"int8":"uint8",n=s?Int8Array:Uint8Array,a=e.data,o=new n(a.length/8);for(let i=0;i<a.length;++i){const l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,s&&d===0&&(o[c]-=128)}return new P(r,o,[e.dims[0],e.dims[1]/8])}async function zu(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await or(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Du(e,t){const s=await zu(e);return await Promise.all(s.map(r=>Mt(e,r,!0,t)))}function no(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Dy=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function By(e,t,s,r){for(const n of Object.keys(e)){const a=t-e[n].length,o=s(n),i=new Array(a).fill(o);e[n]=r==="right"?ot(e[n],i):ot(i,e[n])}}function Ry(e,t){for(const s of Object.keys(e))e[s].length=t}function os(e,...t){for(const s of t){if(!Object.hasOwn(e,s))continue;const r=e[s];if(r)if(typeof r=="object"){if(r.__type==="AddedToken")return r.content;throw Error(`Unknown token: ${r}`)}else return r}return null}function $y(e){const t=[];for(const s of e.get_added_tokens_decoder().values())s.special&&t.push(s);return t}var q=class extends Ue{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Yw(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=os(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=os(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=os(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=os(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=os(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=os(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const r=Object.create(null);for(const{name:n,template:a}of this.chat_template){if(typeof n!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');r[n]=a}this.chat_template=r}this._compiled_template_cache=new Map;const s=$y(this._tokenizer);this.all_special_ids=s.map(r=>r.id),this.all_special_tokens=s.map(r=>r.content)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:a="main"}={}){const o=await Du(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(t=>this._tokenizer.token_to_id(t))}_call(e,t={}){const{text_pair:s=null,add_special_tokens:r=!0,padding:n=!1,return_token_type_ids:a=null}=t;let{truncation:o=null,max_length:i=null}=t;const l=t.return_tensor??!0,c=Array.isArray(e);let d;if(c){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((_,h)=>this._encode_plus(_,{text_pair:s[h],add_special_tokens:r,return_token_type_ids:a}))}else d=e.map(_=>this._encode_plus(_,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))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:s,add_special_tokens:r,return_token_type_ids:a})]}if(i===null?i=this.model_max_length:o===null&&(n===!0?(Q.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),i=this.model_max_length):n===!1&&(Q.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(i=Math.min(ke(d.map(_=>_.input_ids.length))[0],i??1/0)),i=Math.min(i,this.model_max_length??1/0),n||o)for(let _=0;_<d.length;++_)d[_].input_ids.length!==i&&(d[_].input_ids.length>i?o&&Ry(d[_],i):n&&By(d[_],i,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));const u={};if(l){if(!(n&&o)&&d.some(h=>{for(const p of Object.keys(h))if(h[p].length!==d[0][p]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const _=[d.length,d[0].input_ids.length];for(const h of Object.keys(d[0]))u[h]=new P("int64",BigInt64Array.from(d.flatMap(p=>p[h]).map(BigInt)),_)}else{for(const _ of Object.keys(d[0]))u[_]=d.map(h=>h[_]);if(!c)for(const _ of Object.keys(u))u[_]=u[_][0]}return u}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){const{ids:n,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:n,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:s})}encode(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof P&&(e=e.tolist()),e.map(s=>this.decode(s,t))}decode(e,t={}){if(e instanceof P&&(e=no(e)),!Array.isArray(e)||e.length===0||!Mm(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:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(t!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.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(s).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:s=null,documents:r=null,chat_template:n=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:d=!0,return_dict:u=!0,tokenizer_kwargs:_={},...h}=t;if(n=this.get_chat_template({chat_template:n,tools:s}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let p=this._compiled_template_cache.get(n);p===void 0&&(p=new Qv(n),this._compiled_template_cache.set(n,p));const f=Object.create(null);for(const m of Dy){const w=os(this.config,m);w&&(f[m]=w)}const g=p.render({messages:e,add_generation_prompt:a,tools:s,documents:r,...f,...h});if(o){const m=this._call(g,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:d,..._});return u?m:m.input_ids}return g}};function ao(e,t,s,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const n=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);const o=e._tokenizer.post_processor?.config;if(o&&"single"in o){for(const i of o.single)if("SpecialToken"in i&&e.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=e.lang_to_token(n);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,s)}var Bu={};sr(Bu,{AlbertTokenizer:()=>Gy,AutoTokenizer:()=>ne,BartTokenizer:()=>Vy,BertTokenizer:()=>Uy,BlenderbotSmallTokenizer:()=>jy,BlenderbotTokenizer:()=>qy,BloomTokenizer:()=>Wy,CLIPTokenizer:()=>Qy,CamembertTokenizer:()=>Hy,CodeGenTokenizer:()=>Yy,CodeLlamaTokenizer:()=>Xy,CohereAsrTokenizer:()=>Jy,CohereTokenizer:()=>Ky,ConvBertTokenizer:()=>Zy,DebertaTokenizer:()=>tM,DebertaV2Tokenizer:()=>eM,DistilBertTokenizer:()=>sM,ElectraTokenizer:()=>rM,EsmTokenizer:()=>nM,FalconTokenizer:()=>aM,GPT2Tokenizer:()=>lM,GPTNeoXTokenizer:()=>iM,GemmaTokenizer:()=>oM,HerbertTokenizer:()=>cM,LlamaTokenizer:()=>dM,M2M100Tokenizer:()=>uM,MBart50Tokenizer:()=>hM,MBartTokenizer:()=>Ru,MPNetTokenizer:()=>mM,MarianTokenizer:()=>_M,MgpstrTokenizer:()=>pM,MobileBertTokenizer:()=>fM,NllbTokenizer:()=>gM,NougatTokenizer:()=>wM,PreTrainedTokenizer:()=>q,Qwen2Tokenizer:()=>vM,RoFormerTokenizer:()=>MM,RobertaTokenizer:()=>yM,SiglipTokenizer:()=>bM,SpeechT5Tokenizer:()=>xM,SqueezeBertTokenizer:()=>kM,T5Tokenizer:()=>EM,TokenizersBackend:()=>q,VitsTokenizer:()=>AM,Wav2Vec2CTCTokenizer:()=>CM,WhisperTokenizer:()=>LM,XLMRobertaTokenizer:()=>OM,XLMTokenizer:()=>NM});var Gy=class extends q{return_token_type_ids=!0},Vy=class extends q{},Uy=class extends q{return_token_type_ids=!0},jy=class extends q{},qy=class extends q{},Wy=class extends q{},Hy=class extends q{},Qy=class extends q{},Xy=class extends q{},Yy=class extends q{},Ky=class extends q{},Jy=class extends q{},Zy=class extends q{return_token_type_ids=!0},eM=class extends q{return_token_type_ids=!0},tM=class extends q{return_token_type_ids=!0},sM=class extends q{},rM=class extends q{return_token_type_ids=!0},nM=class extends q{},aM=class extends q{},oM=class extends q{},iM=class extends q{},lM=class extends q{},cM=class extends q{return_token_type_ids=!0},dM=class extends q{padding_side="left"},uM=class extends q{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,t,s){return ao(this,e,t,s)}},_M=class extends q{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),Q.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(t);if(s.length===2){const[r,n]=s;return this.supported_language_codes.includes(r)||Q.warn(`Unsupported language code "${r}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ot([r],super._encode_text(n))}}},Ru=class extends q{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,t,s){return ao(this,e,t,s)}},hM=class extends Ru{},pM=class extends q{},fM=class extends q{return_token_type_ids=!0},mM=class extends q{},gM=class extends q{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,t,s){return ao(this,e,t,s)}},wM=class extends q{},vM=class extends q{},yM=class extends q{},MM=class extends q{return_token_type_ids=!0},bM=class extends q{},xM=class extends q{},kM=class extends q{return_token_type_ids=!0},EM=class extends q{},TM=class extends ct{decode_chain(e){let t="";for(let s=1;s<e.length;s+=2)t+=e[s];return[t]}},AM=class extends q{constructor(e,t){super(e,t),this._tokenizer.decoder=new TM({type:"VitsDecoder"})}},CM=class extends q{},$u=[["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"]],nn=new Map($u),SM=new Map([...$u.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 PM(e){e=e.toLowerCase();let t=SM.get(e);if(t===void 0){const s=e.match(/^<\|([a-z]{2})\|>$/);if(s&&(e=s[1]),nn.has(e))t=e;else{const n=e.length===2?nn.keys():nn.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}var FM="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Gu=new RegExp(`^[${FM}]+$`,"gu"),IM=.1,LM=class extends q{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:s=!1,time_precision:r=null,force_full_sequences:n=!0}={}){if(r===null)throw Error("Must specify time_precision");let a=null;const o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let c=i(),d=0;const u=this.timestamp_begin,h=u+1500;let p=[],f=[],g=!1,m=null;const w=new Set(this.all_special_ids);for(const M of e){const E=M.tokens,A=o?M.token_timestamps:null;let S=null,C=u;if("stride"in M){const[N,O,$]=M.stride;if(d-=O,m=N-$,O&&(C=O/r+u),$)for(let L=E.length-1;L>=0;--L){const D=Number(E[L]);if(D>=u){if(S!==null&&(D-u)*r<m)break;S=D}}}let z=[],R=[];for(let N=0;N<E.length;++N){const O=Number(E[N]);if(w.has(O)){const $=this.decode([O]),L=nn.get($.slice(2,-2));if(L!==void 0){if(a!==null&&L!==a&&!t){p.push(z);const D=this.findLongestCommonSequence(p)[0],se=this.decode(D);c.text=se,l.push(c),p=[],z=[],c=i()}a=c.language=L}}else if(O>=u&&O<=h){const $=(O-u)*r+d,L=lr($,2);if(S!==null&&O>=S)g=!0;else if(g||p.length>0&&O<C)g=!1;else if(c.timestamp[0]===null)c.timestamp[0]=L;else if(L!==c.timestamp[0]){c.timestamp[1]=L,p.push(z),o&&f.push(R);const[D,se]=this.findLongestCommonSequence(p,f),U=this.decode(D);if(c.text=U,o&&(c.words=this.collateWordTimestamps(D,se,a),c.words.length>0&&c.timestamp[1]!==null))for(const W of c.words)W.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=W.timestamp[0]&&(W.timestamp[1]=c.timestamp[1]);l.push(c),p=[],z=[],f=[],R=[],c=i()}}else if(z.push(O),o){let $=lr(A[N]+d,2),L;if(N+1<A.length){L=lr(A[N+1]+d,2);const D=this.decode([O]);Gu.test(D)&&(L=lr(Math.min($+r,L),2))}else L=null;R.push([$,L])}}if("stride"in M){const[N,O,$]=M.stride;d+=N-$}z.length>0?(p.push(z),o&&f.push(R)):p.every(N=>N.length===0)&&(c=i(),p=[],z=[],f=[],R=[])}if(p.length>0){if(n&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[M,E]=this.findLongestCommonSequence(p,f),A=this.decode(M);c.text=A,o&&(c.words=this.collateWordTimestamps(M,E,a)),l.push(c)}let y=Object.create(null);const v=l.map(M=>M.text).join("");if(t||s){for(let M=0;M<l.length;++M){const E=l[M];t||delete E.timestamp,s||delete E.language}if(o){const M=[];for(const E of l)for(const A of E.words)M.push(A);y={chunks:M}}else y={chunks:l}}return[v,y]}findLongestCommonSequence(e,t=null){let s=e[0],r=s.length,n=[];const a=Array.isArray(t)&&t.length>0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,u=[r,r,0,0];const _=c.length;for(let y=1;y<r+_;++y){const v=Math.max(0,r-y),M=Math.min(r,r+_-y),E=s.slice(v,M),A=Math.max(0,y-r),S=Math.min(_,y),C=c.slice(A,S);if(E.length!==C.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let z;a?z=E.filter((O,$)=>O===C[$]&&i[v+$][0]-IM<=t[l][A+$][0]).length:z=E.filter((O,$)=>O===C[$]).length;const R=y/1e4,N=z/y+R;z>1&&N>d&&(d=N,u=[v,M,A,S])}const[h,p,f,g]=u,m=Math.floor((p+h)/2);let w=Math.floor((g+f)/2);if(a&&d===0&&r>0){const y=i[r-1][0],v=t[l].findIndex(M=>M[0]>=y);w=v===-1?c.length:v}n.push(...s.slice(0,m)),s=c.slice(w),r=s.length,a&&(o.push(...i.slice(0,m)),i=t[l].slice(w))}return n.push(...s),a?(o.push(...i),[n,o]):[n,[]]}collateWordTimestamps(e,t,s){const[r,n,a]=this.combineTokensIntoWords(e,s),o=[];for(let i=0;i<r.length;++i){const l=a[i];o.push({text:r[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,s=`"'“¡¿([{-`,r=`"'.。,,!!??::”)]}、`){t=t??"english";let n,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,a,o]=this.splitTokensOnUnicode(e):[n,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,a,o,s,r)}decode(e,t){let s;return t?.decode_with_timestamps?(e instanceof P&&(e=no(e)),s=this.decodeWithTimestamps(e,t)):s=super.decode(e,t),s}decodeWithTimestamps(e,t){const s=t?.time_precision??.02,r=this.all_special_ids.at(-1)+1;let n=[[]];for(let a of e)if(a=Number(a),a>=r){const o=((a-r)*s).toFixed(2);n.push(`<|${o}|>`),n.push([])}else n[n.length-1].push(a);return n=n.map(a=>typeof a=="string"?a:super.decode(a,t)),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),s="�",r=[],n=[],a=[];let o=[],i=[],l=0;for(let c=0;c<e.length;++c){const d=e[c];o.push(d),i.push(c);const u=this.decode(o,{decode_with_timestamps:!0});(!u.includes(s)||t[l+u.indexOf(s)]===s)&&(r.push(u),n.push(o),a.push(i),o=[],i=[],l+=u.length)}return[r,n,a]}splitTokensOnSpaces(e){const[t,s,r]=this.splitTokensOnUnicode(e),n=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],c=s[i],d=r[i],u=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),h=l.trim(),p=Gu.test(h);if(u||_||p||n.length===0)n.push(l),a.push(c),o.push(d);else{const f=n.length-1;n[f]+=l,a[f].push(...c),o[f].push(...d)}}return[n,a,o]}mergePunctuations(e,t,s,r,n){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(s);let l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&r.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=ot(o[l],o[c]),i[c]=ot(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&n.includes(a[c])?(a[l]+=a[c],o[l]=ot(o[l],o[c]),i[l]=ot(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},OM=class extends q{},NM=class extends q{return_token_type_ids=!0;constructor(e,t){super(e,t),Q.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},ne=class{static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:a="main"}={}){const[o,i]=await Du(e,{progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let c=Bu[l];return c||(Q.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=q),new c(o,i)}},an="https://github.com/huggingface/transformers.js/issues/new/choose",Vu="preprocessor_config.json",ur="preprocessor_config.json",Uu="processor_config.json",ju="chat_template.jinja",oe=class extends Ue{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,s){super(),this.config=e,this.components=t,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(const s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[s,r,n]=await Promise.all([this.uses_processor_config?Mt(e,Uu,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?Wa(e,ju,!0,t):null]);return new this(s,r,n)}},oo={};sr(oo,{ChatterboxProcessor:()=>db,CohereAsrProcessor:()=>_b,EmbeddingGemma2Processor:()=>wb,EmbeddingGemma2VideoProcessor:()=>n_,Florence2Processor:()=>fx,Gemma3Processor:()=>mx,Gemma3nProcessor:()=>gx,Gemma4Processor:()=>r_,Glm46VProcessor:()=>wx,GraniteSpeechProcessor:()=>vx,GroundingDinoProcessor:()=>Mx,Idefics3Processor:()=>C_,JinaCLIPProcessor:()=>Tx,Lfm2VlProcessor:()=>Ax,LlavaProcessor:()=>Cx,MgpstrProcessor:()=>Sx,MoonshineProcessor:()=>Px,OwlViTProcessor:()=>Fx,PaliGemmaProcessor:()=>Lx,Phi3VProcessor:()=>Nx,PixtralProcessor:()=>zx,Processor:()=>oe,PyAnnoteProcessor:()=>Dx,Qwen2VLProcessor:()=>yo,Qwen2_5_VLProcessor:()=>F_,Qwen3VLProcessor:()=>Bx,Sam2Processor:()=>L_,Sam2VideoProcessor:()=>Rx,SamProcessor:()=>I_,SmolVLMProcessor:()=>C_,SpeechT5Processor:()=>$x,UltravoxProcessor:()=>Gx,VLChatProcessor:()=>Ex,VoxtralProcessor:()=>qx,VoxtralRealtimeProcessor:()=>Qx,Wav2Vec2Processor:()=>Xx,Wav2Vec2ProcessorWithLM:()=>Yx,WhisperProcessor:()=>Kx});var $e=class extends Ue{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const s=await Mt(e,Vu,!0,t);return new this(s)}};function ze(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var io={};sr(io,{ASTFeatureExtractor:()=>YM,ChatterboxFeatureExtractor:()=>KM,ClapFeatureExtractor:()=>JM,CohereAsrFeatureExtractor:()=>eb,DacFeatureExtractor:()=>Ju,EncodecFeatureExtractor:()=>Yu,FeatureExtractor:()=>$e,Gemma3nAudioFeatureExtractor:()=>Zu,Gemma4AudioFeatureExtractor:()=>e_,GraniteSpeechFeatureExtractor:()=>tb,MoonshineFeatureExtractor:()=>sb,ParakeetFeatureExtractor:()=>Ku,PyAnnoteFeatureExtractor:()=>t_,SeamlessM4TFeatureExtractor:()=>rb,SnacFeatureExtractor:()=>nb,SpeechT5FeatureExtractor:()=>ab,VoxtralRealtimeFeatureExtractor:()=>lb,Wav2Vec2FeatureExtractor:()=>ob,WeSpeakerFeatureExtractor:()=>ib,WhisperFeatureExtractor:()=>cb});var zM=()=>{},DM=zM;async function qu(e,t){if(Y.IS_BROWSER_ENV){if(Y.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const s=URL.createObjectURL(t),r=document.createElement("a");r.href=s,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(s)}else if(Y.IS_FS_AVAILABLE)t.stream(),Xe.createWriteStream(e),await DM();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function BM(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const s=await(await ir(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});typeof t>"u"&&Q.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);const n=await r.decodeAudioData(s);let a;if(n.numberOfChannels===2){const o=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<n.length;++c)a[c]=o*(i[c]+l[c])/2}else a=n.getChannelData(0);return a}async function RM(e,t){return await BM(e,t)}function Wu(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const s=1-t,r=2*Math.PI/(e-1),n=new Float64Array(e);for(let a=0;a<e;++a)n[a]=t-s*Math.cos(a*r);return n}function Hu(e){return Wu(e,.5)}function $M(e){return Wu(e,.54)}var GM={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,s=15,r=27/Math.log(6.4))=>e>=t?s+Math.log(e/t)*r:3*e/200};function lo(e,t="htk"){const s=GM[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?s(e):e.map(r=>s(r))}var VM={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,s=15,r=Math.log(6.4)/27)=>e>=s?t*Math.exp(r*(e-s)):200*e/3};function UM(e,t="htk"){const s=VM[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?s(e):e.map(r=>s(r))}function jM(e,t){const s=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),r=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){const i=r[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const n=t.length-2,a=Array.from({length:n},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=r[o];for(let l=0;l<n;++l){const c=-i[l]/s[l],d=i[l+2]/s[l+1];a[l][o]=Math.max(0,Math.min(c,d))}}return a}function Qu(e,t,s){const r=(t-e)/(s-1);return Float64Array.from({length:s},(n,a)=>e+r*a)}function xt(e,t,s,r,n,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(s>r)throw new Error(`Require min_frequency: ${s} <= max_frequency: ${r}`);const l=lo(s,o),c=lo(r,o),d=Qu(l,c,t+2);let u=UM(d,o),_;if(i){const p=n/((e-1)*2);_=lo(Float64Array.from({length:e},(f,g)=>g*p),o),u=d}else _=Qu(0,Math.floor(n/2),e);const h=jM(_,u);if(a!==null&&a==="slaney")for(let p=0;p<t;++p){const f=h[p],g=2/(u[p+2]-u[p]);for(let m=0;m<e;++m)f[m]*=g}return h}function qM(e,t,s){const r=new e.constructor(e.length+t+s),n=e.length-1;for(let a=0;a<e.length;++a)r[t+a]=e[a];for(let a=1;a<=t;++a)r[t-a]=e[Gr(a,n)];for(let a=1;a<=s;++a)r[n+t+a]=e[Gr(n-a,n)];return r}function Xu(e,t,s,r,n){if(s<=0)throw new Error("reference must be greater than zero");if(r<=0)throw new Error("min_value must be greater than zero");s=Math.max(r,s);const a=Math.log10(s);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(r,e[o])-a);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");const o=ke(e)[0]-n;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function WM(e,t=1,s=1e-5,r=null){return Xu(e,20,t,s,r)}function HM(e,t=1,s=1e-10,r=null){return Xu(e,10,t,s,r)}async function kt(e,t,s,r,{fft_length:n=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:u=null,mel_floor:_=1e-10,log_mel:h=null,max_log_mel:p=null,reference:f=1,min_value:g=1e-10,db_range:m=null,remove_dc_offset:w=null,min_num_frames:y=null,max_num_frames:v=null,do_pad:M=!0,transpose:E=!1,mel_offset:A=0,mel_floor_mode:S="clamp"}={}){const C=t.length;if(n===null&&(n=s),s>n)throw Error(`frame_length (${s}) may not be larger than fft_length (${n})`);if(C!==s)throw new Error(`Length of the window (${C}) must equal frame_length (${s})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(a===null&&u!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){const k=Math.floor(s/2);switch(i){case"reflect":{e=qM(e,k,k);break}case"constant":{const F=new e.constructor(e.length+2*k);F.set(e,k),e=F;break}case"semicausal":{const F=new e.constructor(e.length+k);F.set(e,k),e=F;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let z=Math.floor(1+Math.floor((e.length-s)/r));y!==null&&z<y&&(z=y);const R=l?Math.floor(n/2)+1:n;let N=z,O=z;v!==null&&(v>z?M&&(O=v):O=N=v);const $=new fy(n),L=new Float64Array(n),D=new Float64Array($.outputBufferSize),se=new Float32Array(R*O);for(let k=0;k<N;++k){const F=k*r,K=Math.min(e.length-F,s);K!==s&&L.fill(0,0,s);for(let H=0;H<K;++H)L[H]=e[F+H];if(w){let H=0;for(let _e=0;_e<K;++_e)H+=L[_e];const Le=H/K;for(let _e=0;_e<K;++_e)L[_e]-=Le}if(c!==null){for(let H=K-1;H>=1;--H)L[H]-=c*L[H-1];L[0]*=1-c}for(let H=0;H<t.length;++H)L[H]*=t[H];$.realTransform(D,L);for(let H=0;H<R;++H){const Le=H<<1;se[H*O+k]=D[Le]**2+D[Le+1]**2}}if(a!==null&&a!==2){const k=a/2;for(let F=0;F<se.length;++F)se[F]**=k}const U=u.length;let W=await Iy(new P("float32",u.flat(),[U,R]),new P("float32",se,[R,O]));E&&(W=W.transpose(1,0));const x=W.data;if(S==="add")for(let k=0;k<x.length;++k)x[k]=A+x[k]+_;else for(let k=0;k<x.length;++k)x[k]=A+Math.max(_,x[k]);if(a!==null&&h!==null){const k=Math.min(x.length,N*U);switch(h){case"log":for(let F=0;F<k;++F)x[F]=Math.log(x[F]);break;case"log10":for(let F=0;F<k;++F)x[F]=Math.log10(x[F]);break;case"log10_max_norm":{for(let H=0;H<k;++H)x[H]=Math.log10(x[H]);const K=(p??ke(x)[0])-8;for(let H=0;H<k;++H)x[H]=(Math.max(x[H],K)+4)/4;break}case"dB":if(a===1)WM(x,f,g,m);else if(a===2)HM(x,f,g,m);else throw new Error(`Cannot use log_mel option '${h}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${h}'`)}}return W}function St(e,t,{periodic:s=!0,frame_length:r=null,center:n=!0}={}){const a=s?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=Hu(a);break;case"hamming":o=$M(a);break;case"povey":o=Hu(a).map(c=>Math.pow(c,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(s&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);const i=new Float64Array(r),l=n?Math.floor((r-e)/2):0;return i.set(o,l),i}function QM(e,t){const s=e.reduce((a,o)=>a+o.length,0),r=new ArrayBuffer(44),n=new DataView(r);return on(n,0,"RIFF"),n.setUint32(4,36+s*4,!0),on(n,8,"WAVE"),on(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,t*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),on(n,36,"data"),n.setUint32(40,s*4,!0),new Blob([r,...e.map(a=>a.buffer instanceof ArrayBuffer?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a.slice())],{type:"audio/wav"})}function on(e,t,s){for(let r=0;r<s.length;++r)e.setUint8(t+r,s.charCodeAt(r))}var XM=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];const e=this.audio.reduce((r,n)=>r+n.length,0),t=new Float32Array(e);let s=0;for(const r of this.audio)t.set(r,s),s+=r.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),QM(e,this.sampling_rate)}async save(e){return qu(e,this.toBlob())}},YM=class extends $e{constructor(e){super(e);const t=this.config.sampling_rate,s=xt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return kt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){ze(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const s=this.std*2,r=t.data;for(let n=0;n<r.length;++n)r[n]=(r[n]-this.mean)/s}return{input_values:t.unsqueeze_(0)}}},Yu=class extends $e{async _call(e){ze(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const s=[1,t,e.length/t];return{input_values:new P("float32",e,s)}}},KM=class extends $e{async _call(e){ze(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new P("float32",e,t)}}},JM=class extends $e{constructor(e){super(e),this.mel_filters=xt(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=xt(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=St(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,s,r){let n;const a=e.length-t;if(a>0)if(s==="rand_trunc"){const o=Math.floor(Ra.random()*(a+1));e=e.subarray(o,o+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(a<0){let o=new Float64Array(t);if(o.set(e),r==="repeat")for(let i=e.length;i<t;i+=e.length)o.set(e.subarray(0,Math.min(e.length,t-i)),i);else if(r==="repeatpad")for(let i=e.length;i<-a;i+=e.length)o.set(e,i);e=o}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,s=null){return kt(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return ze(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},ZM=1e-5,Ku=class extends $e{constructor(e){super(e),this.config.mel_filters??=xt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");const t=St(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,s)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let r=e.length-1;r>=1;--r)e[r]-=t*e[r-1];return await kt(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){ze(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,s*t.dims[1]);const[n,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d<s;++d){const u=d*a;for(let _=0;_<a;++_){const h=r[u+_];o[_]+=h,i[_]+=h*h}}const l=s>1?s-1:1;for(let d=0;d<a;++d){const u=o[d]/s,_=(i[d]-s*u*u)/l,p=1/(Math.sqrt(_)+ZM);for(let f=0;f<s;++f){const g=f*a+d;r[g]=(r[g]-u)*p}}const c=new BigInt64Array(n);return c.fill(1n,0,s),{input_features:t.unsqueeze_(0),attention_mask:new P("int64",c,[1,n])}}},eb=class extends Ku{_apply_dither(e){const t=this.config.dither??0;if(t<=0)return e;const s=new en(e.length);for(let r=0;r<e.length;++r)e[r]+=t*s.gauss();return e}split_audio(e){const t=this.config.max_audio_clip_s??35,s=this.config.overlap_chunk_second??5,r=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,a=Math.max(1,Math.round(t*n)),o=Math.max(1,Math.round(s*n));if(e.length<=a)return[e];const i=[];let l=0;const c=e.length;for(;l<c;){if(l+a>=c){i.push(e.slice(l,c));break}const d=Math.max(l,l+a-o),u=Math.min(l+a,c);let _;u<=d?_=l+a:_=this._find_split_point_energy(e,d,u,r),_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_}return i}_find_split_point_energy(e,t,s,r){const n=s-t;if(n<=r)return Math.floor((t+s)/2);let a=1/0,o=t;const i=n-r;for(let l=0;l<=i;l+=r){let c=0;for(let d=0;d<r;++d){const u=e[t+l+d];c+=u*u}c=Math.sqrt(c/r),c<a&&(a=c,o=t+l)}return o}async _call(e){ze(e,"CohereAsrFeatureExtractor");const t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},Ju=class extends Yu{},Zu=class extends $e{constructor(e){super(e);const{fft_length:t,feature_size:s,min_frequency:r,max_frequency:n,sampling_rate:a,frame_length:o}=this.config,i=xt(Math.floor(1+t/2),s,r,n,a,null,"htk",!1);this.mel_filters=i,this.window=St(o,"hann")}async _extract_fbank_features(e,t){return kt(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:s=!0,padding:r=!0,pad_to_multiple_of:n=128}={}){if(ze(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>t&&(e=e.slice(0,t)),r&&e.length%n!==0){const i=n-e.length%n,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=Re([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},e_=class extends Zu{async _extract_fbank_features(e,t){const{frame_length:s,hop_length:r,fft_length:n}=this.config,a=Math.floor(s/2),o=Math.floor((e.length+a-(s+1))/r)+1;return kt(e,this.window,s,r,{fft_length:n,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){ze(e,"Gemma4AudioFeatureExtractor");const s=e.length,r=await super._call(e,t),{input_features:n}=r,[,a,o]=n.dims,{frame_length:i,hop_length:l}=this.config,c=Math.floor(i/2),d=i+1,u=new Uint8Array(s+c+(t.pad_to_multiple_of??128));u.fill(1,c,c+s);const _=new Uint8Array(a);for(let p=0;p<a;++p)_[p]=u[p*l+d-1]?1:0;const h=n.data;for(let p=0;p<a;++p)_[p]||h.fill(0,p*o,(p+1)*o);return r.input_features_mask=new P("bool",_,[1,a]),r}},tb=class extends $e{constructor(e){super(e);const{n_fft:t,win_length:s,n_mels:r,sample_rate:n}=e.melspec_kwargs;this.mel_filters=xt(Math.floor(1+t/2),r,0,n/2,n,null,"htk");const a=St(s,"hann");this.window=new Float64Array(t);const o=Math.floor((t-s)/2);this.window.set(a,o)}async _call(e){ze(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:s,n_mels:r}=this.config.melspec_kwargs,n=Math.floor(e.length/s)+1,a=n-n%2;return{input_features:(await kt(e,this.window,t,s,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},sb=class extends $e{async _call(e){ze(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new P("float32",e,t)}}},t_=class extends $e{async _call(e){ze(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new P("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const s=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(const n of e.tolist()){const a=[];let o=-1;for(let i=0;i<n.length;++i){const l=Ne(n[i]),[c,d]=ke(l),[u,_]=[i,i+1];d!==o?(o=d,a.push({id:d,start:u,end:_,score:c})):(a.at(-1).end=_,a.at(-1).score+=c)}r.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*s,end:c*s,confidence:d/(c-l)})))}return r}},rb=class extends $e{constructor(e){super(e);const t=this.config.sampling_rate,s=xt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(s=>s*32768),kt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:n=!0}={}){ze(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(r){const[h,p]=a.dims,f=a.data;for(let g=0;g<p;++g){let m=0;for(let M=0;M<h;++M)m+=f[M*p+g];const w=m/h;let y=0;for(let M=0;M<h;++M)y+=(f[M*p+g]-w)**2;y/=h-1;const v=Math.sqrt(y+1e-7);for(let M=0;M<h;++M){const E=M*p+g;f[E]=(f[E]-w)/v}}}let o;if(t){const[h,p]=a.dims,f=a.data,g=h%s;if(g>0){const m=new Float32Array(p*(h+g));m.set(f),m.fill(this.config.padding_value,f.length);const w=h+g;a=new P(a.type,m,[w,p]),n&&(o=new P("int64",new BigInt64Array(w),[1,w]),o.data.fill(1n,0,h))}}const[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const u=a.view(1,Math.floor(i/c),l*c),_={input_features:u};if(n){const h=u.dims[1],p=new BigInt64Array(h);if(o){const f=o.data;for(let g=1,m=0;g<i;g+=c,++m)p[m]=f[g]}else p.fill(1n);_.attention_mask=new P("int64",p,[1,h])}return _}},nb=class extends Ju{},ab=class extends $e{},ob=class extends $e{_zero_mean_unit_var_norm(e){const s=e.reduce((n,a)=>n+a,0)/e.length,r=e.reduce((n,a)=>n+(a-s)**2,0)/e.length;return e.map(n=>(n-s)/Math.sqrt(r+1e-7))}async _call(e){ze(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const s=[1,t.length];return{input_values:new P("float32",t,s),attention_mask:new P("int64",new BigInt64Array(t.length).fill(1n),s)}}},ib=class extends $e{constructor(e){super(e);const t=this.config.sampling_rate,s=xt(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=St(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),kt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){ze(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const s=t.mean(1).data,r=t.data,[n,a,o]=t.dims;for(let i=0;i<n;++i){const l=i*a*o,c=i*o;for(let d=0;d<a;++d){const u=l+d*o;for(let _=0;_<o;++_)r[u+_]-=s[c+_]}}}return{input_features:t}}},lb=class extends $e{constructor(e){super(e),this.config.mel_filters??=xt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=St(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){const{n_fft:s,hop_length:r,mel_filters:n,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/r:(e.length-s)/r);return await kt(e,this.window,s,r,{power:2,mel_filters:n,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return ze(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},cb=class extends $e{constructor(e){super(e),this.config.mel_filters??=xt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=St(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await kt(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}={}){ze(e,"WhisperFeatureExtractor");let s;const r=t??this.config.n_samples;return e.length>r?(e.length>this.config.n_samples&&Q.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`."),s=e.slice(0,r)):(s=new Float32Array(r),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}},rt=class{static async from_pretrained(e,t={}){const s=await Mt(e,Vu,!0,t),r=s.feature_extractor_type,n=io[r];if(!n)throw new Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${an}.`);return new n(s)}},db=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e,t=null){const s=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...s,...r}}},ub=new Set(["ja","zh"]),_b=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){const t=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){const s=e.filter(a=>a&&a.trim());if(s.length===0)return"";const r=ub.has(t)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},co={},is,s_,jt;if(Y.IS_WEB_ENV)is=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},jt=self.createImageBitmap,s_=self.ImageData;else if(co)jt=async e=>{const s=(await e.metadata()).channels,{data:r,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new pt(new Uint8ClampedArray(r),n.width,n.height,n.channels);return s!==void 0&&s!==n.channels&&a.convert(s),a};else throw new Error("Unable to load image processing library.");var hb={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},pb=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),pt=class Tt{constructor(t,s,r,n){this.data=t,this.width=s,this.height=r,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof Tt)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!Y.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const r=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new Tt(r,t.width,t.height,4)}static async fromURL(t){const s=await ir(t);if(s.status!==200)throw new Error(`Unable to read image from "${t}" (${s.status} ${s.statusText})`);const r=await s.blob();return this.fromBlob(r)}static async fromBlob(t){if(Y.IS_WEB_ENV){const s=await jt(t),r=is(s.width,s.height).getContext("2d");return r.drawImage(s,0,0),new this(r.getImageData(0,0,s.width,s.height).data,s.width,s.height,4)}else{const s=co(await t.arrayBuffer());return await jt(s)}}static fromTensor(t,s="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(s==="CHW")t=t.permute(1,2,0);else if(s!=="HWC")throw new Error(`Unsupported channel format: ${s}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new Tt(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let s=0,r=0;s<this.data.length;s+=this.channels){const n=this.data[s],a=this.data[s+1],o=this.data[s+2];t[r++]=Math.round(.2989*n+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let s=0,r=0;s<this.data.length;++s)t[r++]=this.data[s],t[r++]=this.data[s],t[r++]=this.data[s];break;case 4:for(let s=0,r=0;s<this.data.length;s+=4)t[r++]=this.data[s],t[r++]=this.data[s+1],t[r++]=this.data[s+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let s=0,r=0;s<this.data.length;++s)t[r++]=this.data[s],t[r++]=this.data[s],t[r++]=this.data[s],t[r++]=255;break;case 3:for(let s=0,r=0;s<this.data.length;s+=3)t[r++]=this.data[s],t[r++]=this.data[s+1],t[r++]=this.data[s+2],t[r++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);const s=this.data,r=t.data,n=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(n*4);for(let o=0,i=0,l=0;o<n;++o)a[l++]=s[i++],a[l++]=s[i++],a[l++]=s[i++],a[l++]=r[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<n;++a)s[4*a+3]=r[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,s,{resample:r=2}={}){if(this.width===t&&this.height===s)return this;let n=hb[r]??r;const a=hd(t),o=hd(s);if(a&&o)return this;if(a?t=s/this.height*this.width:o&&(s=t/this.width*this.height),Y.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=is(t,s).getContext("2d");return c.drawImage(l,0,0,t,s),new Tt(c.getImageData(0,0,t,s).data,t,s,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(Q.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,s/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:t,height:s,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await jt(i)}}async pad([t,s,r,n]){if(t=Math.max(t,0),s=Math.max(s,0),r=Math.max(r,0),n=Math.max(n,0),t===0&&s===0&&r===0&&n===0)return this;if(Y.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=this.width+t+s,l=this.height+r+n,c=is(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,r,this.width,this.height),new Tt(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:s,top:r,bottom:n});return await jt(a)}}async crop([t,s,r,n]){if(t=Math.max(t,0),s=Math.max(s,0),r=Math.min(r,this.width-1),n=Math.min(n,this.height-1),t===0&&s===0&&r===this.width-1&&n===this.height-1)return this;const a=r-t+1,o=n-s+1;if(Y.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=is(a,o).getContext("2d");return c.drawImage(l,t,s,a,o,0,0,a,o),new Tt(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{const i=this.toSharp().extract({left:t,top:s,width:a,height:o});return await jt(i)}}async center_crop(t,s){if(this.width===t&&this.height===s)return this;const r=(this.width-t)/2,n=(this.height-s)/2;if(Y.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=is(t,s).getContext("2d");let l=0,c=0,d=0,u=0;return r>=0?l=r:d=-r,n>=0?c=n:u=-n,i.drawImage(o,l,c,t,s,d,u,t,s),new Tt(i.getImageData(0,0,t,s).data,t,s,4).convert(a)}else{let a=this.toSharp();if(r>=0&&n>=0)a=a.extract({left:Math.floor(r),top:Math.floor(n),width:t,height:s});else if(r<=0&&n<=0){const o=Math.floor(-n),i=Math.floor(-r);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:s-this.height-o})}else{let o=[0,0],i=0;n<0?(o[0]=Math.floor(-n),o[1]=s-this.height-o[0]):i=Math.floor(n);let l=[0,0],c=0;r<0?(l[0]=Math.floor(-r),l[1]=t-this.width-l[0]):c=Math.floor(r),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:s})}return await jt(a)}}async toBlob(t="image/png",s=1){if(!Y.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:s})}toTensor(t="CHW"){let s=new P("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")s=s.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return s}toCanvas(){if(!Y.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),s=is(t.width,t.height),r=new s_(t.data,t.width,t.height);return s.getContext("2d").putImageData(r,0,0),s}split(){const{data:t,width:s,height:r,channels:n}=this,a=t.constructor,o=t.length/n,i=Array.from({length:n},()=>new a(o));for(let l=0;l<o;++l){const c=n*l;for(let d=0;d<n;++d)i[d][l]=t[c+d]}return i.map(l=>new Tt(l,s,r,1))}_update(t,s,r,n=null){return this.data=t,this.width=s,this.height=r,n!==null&&(this.channels=n),this}clone(){return new Tt(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(Y.IS_WEB_ENV){if(Y.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const s=t.split(".").pop().toLowerCase(),r=pb.get(s)??"image/png",n=await this.toBlob(r);return qu(t,n)}else if(Y.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Y.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return co(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};pt.read.bind(pt);function fb(e,t,s,r,n){const a=r*s**2,o=Math.sqrt(a/(e*t)),i=n*s;let l=Math.floor(o*e/i)*i,c=Math.floor(o*t/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);const d=Math.floor(r/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(t/e)*i,d)):c===0&&(c=i,l=Math.min(Math.floor(e/t)*i,d)),[l,c]}function mb(e,t,s,r,n,a,o){const i=Math.floor(t/n),l=Math.floor(s/n),c=i*l,d=n*n*r,u=new Float32Array(a*d);let _=0;for(let f=0;f<i;++f)for(let g=0;g<l;++g)for(let m=0;m<n;++m){const w=(f*n+m)*s*r+g*n*r;for(let y=0;y<n;++y){const v=w+y*r;for(let M=0;M<r;++M)u[_++]=e[v+M]}}const h=new BigInt64Array(a*2).fill(-1n);let p=0;for(let f=0;f<i;++f)for(let g=0;g<l;++g)h[p++]=BigInt(g),h[p++]=BigInt(f);return{patches:new P("float32",u,[a,d]),positions:new P("int64",h,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var uo=class extends Ue{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);const{patch_size:t,pooling_kernel_size:s}=this,r=this.max_soft_tokens*s**2,n=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){const[_,h]=fb(i.height,i.width,t,r,s);(_!==i.height||h!==i.width)&&(i=await i.resize(h,_,{resample:this.resample}))}const l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;const{patches:c,positions:d,num_soft_tokens:u}=mb(l,i.height,i.width,i.channels,t,r,s);n.push(c),a.push(d),o.push(u)}return{pixel_values:Ct(n,0),image_position_ids:Ct(a,0),num_soft_tokens_per_image:o}}},r_=class extends oe{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,s),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;const{audio_token:r,boa_token:n,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=r,this.boa_token=n,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){const[s,r,n]=await Promise.all([Mt(e,Uu,!0,t),ne.from_pretrained(e,t),Wa(e,ju,!1,t)]),a={tokenizer:r};return s.image_processor&&(a.image_processor=new uo(s.image_processor)),s.feature_extractor&&(a.feature_extractor=new e_(s.feature_extractor)),new this(s,a,n)}_compute_audio_num_tokens(e,t){const s=Math.round(t*20/1e3),r=Math.round(t*10/1e3),n=Math.floor(s/2);let a=Math.floor((e+n-s-1)/r)+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,s=null,r={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,r);const o=n.num_soft_tokens_per_image;let i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>`
|
||
|
||
${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
|
||
|
||
`))}let a;if(s){const o=Array.isArray(s)?s:[s];a=await this.feature_extractor(o[0],r);const i=this.feature_extractor.config.sampling_rate??16e3;let l=0;e=e.map(c=>c.replaceAll(this.audio_token,()=>`
|
||
|
||
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
|
||
|
||
`))}return{...this.tokenizer(e,r),...n,...a}}},n_=class extends Ue{constructor(e){super(),this.config=e,this.frame_processor=new uo(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??"uniform"}sample_frames(e){const t=e.length,{max_frames:s}=this;if(t<=s)return e;if(this.overflow_strategy==="truncate")return e.slice(0,s);const r=s>1?(t-1)/(s-1):0;return Array.from({length:s},(n,a)=>e[a>0&&a===s-1?t-1:Math.floor(a*r)])}async _call(e){Array.isArray(e)||(e=[e]);const t=e.map(o=>this.sample_frames(o.frames.map(i=>i.image))),{pixel_values:s,image_position_ids:r,num_soft_tokens_per_image:n}=await this.frame_processor(t.flat());let a=0;return{pixel_values_videos:s,video_position_ids:r,num_frames_per_video:t.map(o=>o.length),num_soft_tokens_per_video:t.map(o=>n[(a+=o.length)-1])}}};function _o(e,t){return Array.isArray(e)?e.every(s=>Array.isArray(s))?e:t?[e]:e.map(s=>[s]):[[e]]}function gb(e,t,s){let r=0;if(e=e.map(n=>n.replaceAll(t,()=>s[r++]??"")),r!==s.length)throw new Error(`Found ${r} ${t} tokens in the text, but ${s.length} inputs were passed.`);return e}var wb=class extends r_{constructor(e,t,s){super(e,t,s),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new n_(e.video_processor)}async _call(e,t=null,s=null,r=null,n={}){const a=[[this.image_token,t&&_o(t,!0)],[this.video_token,r&&_o(r,!1)],[this.audio_token,s&&_o(s,!1)]];if(e==null){const v=a.filter(([,E])=>E),M=v[0]?.[1].length;if(v.some(([,E])=>E.length!==M))throw new Error("Received a different number of samples per modality.");e=Array.from({length:M},(E,A)=>v.flatMap(([S,C])=>Array(C[A].length).fill(S)).join(" "))}else typeof e=="string"&&(e=[e]);const[o,i,l]=a.map(([,v])=>v?.flat()),c=o&&await this.image_processor(o),d=i&&await this.video_processor(i),u=l&&await this._process_audio(l),{image_token:_,video_token:h,audio_token:p,boi_token:f,eoi_token:g,boa_token:m,eoa_token:w}=this,y={[_]:c?.num_soft_tokens_per_image.map(v=>f+_.repeat(v)+g),[h]:d?.num_soft_tokens_per_video.map((v,M)=>(f+h.repeat(v)+g).repeat(d.num_frames_per_video[M])),[p]:u?.num_soft_tokens_per_audio.map(v=>m+p.repeat(v)+w)};for(const[v,M]of Object.entries(y))e=gb(e,v,M??[]);return{...this.tokenizer(e,{padding:!0,...n}),...c,...d,...u}}async _process_audio(e){const t=[];for(const o of e)t.push(await this.feature_extractor(o));const s=Math.max(...t.map(o=>o.input_features.dims[1])),r=t[0].input_features.dims[2],n=new Float32Array(e.length*s*r),a=new Uint8Array(e.length*s);return t.forEach((o,i)=>{n.set(o.input_features.data,i*s*r),a.set(o.input_features_mask.data,i*s)}),{input_features:new P("float32",n,[e.length,s,r]),input_features_mask:new P("bool",a,[e.length,s]),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 a_(e,t,s=0,r=null){const n=e/t;let a=gy(n)*t;return r!==null&&a>r&&(a=Math.floor(n)*t),a<s&&(a=Math.ceil(n)*t),a}function o_([e,t],s){return[Math.max(Math.floor(e/s),1)*s,Math.max(Math.floor(t/s),1)*s]}function i_([e,t,s,r]){return[e-s/2,t-r/2,e+s/2,t+r/2]}function ln(e,t=.5,s=null,r=!1){const n=e.logits,a=e.pred_boxes,[o,i,l]=n.dims;if(s!==null&&s.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 u=s!==null?s[d]:null,_={boxes:[],classes:[],scores:[]},h=n[d],p=a[d];for(let f=0;f<i;++f){let g=h[f],m=[],w;if(r){w=g.sigmoid().data;for(let y=0;y<w.length;++y)w[y]>t&&m.push(y)}else{let y=ke(g.data)[1];if(y===l-1||(w=Ne(g.data),w[y]<t))continue;m.push(y)}for(const y of m){let v=p[f].data;v=i_(v),u!==null&&(v=v.map((M,E)=>M*u[(E+1)%2])),_.boxes.push(v),_.classes.push(y),_.scores.push(w[y])}}c.push(_)}return c}function l_(e,t=null){const s=e.logits,r=s.dims[0];if(t!==null&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const n=[];for(let a=0;a<r;++a){const o=t!==null?t[a]:null;let i=s[a];o!==null&&(i=Fu(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new P("int32",new Int32Array(l*c),[l,c]),u=i[0].data,_=d.data;for(let f=1;f<i.dims[0];++f){const g=i[f].data;for(let m=0;m<g.length;++m)g[m]>u[m]&&(u[m]=g[m],_[m]=f)}const h=new Array(i.dims[0]);for(let f=0;f<_.length;++f){const g=_[f];h[g]=g}const p=h.filter(f=>f!==void 0);n.push({segmentation:d,labels:p})}return n}function vb(e,t,s,r){const n=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=ke(l.data)[1];if(d===r)continue;const _=Ne(l.data)[d];_>s&&(n.push(c),a.push(_),o.push(d))}return[n,a,o]}function yb(e,t,s,r=.5,n=.8){const a=[];let o=0,i=0;const l=t[s].data;for(let d=0;d<e.length;++d)e[d]===s&&(a.push(d),++o),l[d]>=r&&++i;let c=o>0&&i>0;return c&&(c=o/i>n),[c,a]}function Mb(e,t,s,r,n,a=null,o=null){const[i,l]=o??e[0].dims,c=new P("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let f=0;f<e.length;++f)e[f]=Fu(e[f],o,"bilinear",!1);const u=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let f=0;f<e.length;++f){let g=t[f];const m=e[f].data;for(let w=0;w<m.length;++w)m[w]*=g,m[w]>_[w]&&(u[w]=f,_[w]=m[w])}let h=0;const p=c.data;for(let f=0;f<s.length;++f){const g=s[f],[m,w]=yb(u,e,f,r,n);if(m){++h;for(const y of w)p[y]=h;d.push({id:h,label_id:g,score:t[f]})}}return[c,d]}function ho(e,t,s=28,r=3136,n=784*1280,a=1){if(e<s||t<s){const l=Math.max(s/e,s/t);e=Math.round(e*l),t=Math.round(t*l)}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/s)*s,i=Math.round(t/s)*s;if(a*o*i>n){const l=Math.sqrt(a*e*t/n);o=Math.max(s,Math.floor(e/l/s)*s),i=Math.max(s,Math.floor(t/l/s)*s)}else if(a*o*i<r){const l=Math.sqrt(r/(a*e*t));o=Math.ceil(e*l/s)*s,i=Math.ceil(t*l/s)*s}return[i,o]}function c_(e,t=.5,s=.5,r=.8,n=null,a=null){n===null&&(Q.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);const o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,u]=o.dims;if(u-=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 h=0;h<c;++h){let p=a!==null?a[h]:null,f=o[h],g=l[h],[m,w,y]=vb(f,g,t,u);if(y.length===0){let[E,A]=p??g.dims.slice(-2),S=new P("int32",new Int32Array(E*A).fill(-1),[E,A]);_.push({segmentation:S,segments_info:[]});continue}let[v,M]=Mb(m,w,y,s,r,n,p);_.push({segmentation:v,segments_info:M})}return _}function d_(e,t=.5,s=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var X=class extends Ue{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,s=2){const r=e.height,n=e.width,a=t.height,o=t.width;let i=Math.min(r,a),l=Math.min(n,o);return i===r&&l===n?e:(r>n?l=Math.floor(n*i/r):n>r&&(i=Math.floor(r*l/n)),await e.resize(l,i,{resample:s}))}async crop_margin(e,t=200){const s=e.clone().grayscale(),r=Ha(s.data)[0],a=ke(s.data)[0]-r;if(a===0)return e;const o=t/255;let i=s.width,l=s.height,c=0,d=0;const u=s.data;for(let _=0;_<s.height;++_){const h=_*s.width;for(let p=0;p<s.width;++p)(u[h+p]-r)/a<o&&(i=Math.min(i,p),l=Math.min(l,_),c=Math.max(c,p),d=Math.max(d,_))}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,s,{mode:r="constant",center:n=!1,constant_values:a=0}={}){const[o,i,l]=t;let c,d;if(typeof s=="number"?(c=s,d=s):s==="square"?c=d=Math.max(o,i):(c=s.width,d=s.height),c!==i||d!==o){const u=new Float32Array(c*d*l);if(Array.isArray(a))for(let p=0;p<u.length;++p)u[p]=a[p%l];else a!==0&&u.fill(a);const[_,h]=n?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let p=0;p<o;++p){const f=(p+h)*c,g=p*i;for(let m=0;m<i;++m){const w=(f+m+_)*l,y=(g+m)*l;for(let v=0;v<l;++v)u[w+v]=e[y+v]}}if(r==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const p=o-1,f=i-1;for(let g=0;g<d;++g){const m=g*c,w=Gr(g,p)*i;for(let y=0;y<c;++y){if(g<o&&y<i)continue;const v=(m+y)*l,M=(w+Gr(y,f))*l;for(let E=0;E<l;++E)u[v+E]=e[M+E]}}}e=u,t=[d,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[s,r]=e.size;let n,a;if(this.do_thumbnail){const{height:o,width:i}=t;n=Math.min(o,i)}else Number.isInteger(t)?(n=t,a=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,a=t.longest_edge);if(n!==void 0||a!==void 0){const o=n===void 0?1:Math.max(n/s,n/r),i=s*o,l=r*o,c=a===void 0?1:Math.min(a/i,a/l);let d=Math.floor(Number((i*c).toFixed(2))),u=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,u]=o_([d,u],this.size_divisibility)),[d,u]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/r,c=o/s;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=a_(l*r,this.config.ensure_multiple_of),o=a_(c*s,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return o_([s,r],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,s,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:s=null,do_convert_rgb:r=null,do_convert_grayscale:n=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(r??this.do_convert_rgb?e=e.rgb():n&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,h;Number.isInteger(this.crop_size)?(_=this.crop_size,h=this.crop_size):(_=this.crop_size.width,h=this.crop_size.height),e=await e.center_crop(_,h)}const l=[e.height,e.width];let c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let h=this.image_std;if(Array.isArray(this.image_std)||(h=new Array(e.channels).fill(h)),_.length!==e.channels||h.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${h.length}) must match the number of channels in the image (${e.channels}).`);for(let p=0;p<c.length;p+=e.channels)for(let f=0;f<e.channels;++f)c[p+f]=(c[p+f]-_[f])/h[f]}if(s??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,h=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:_,height:h})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){const h=c[_];c[_]=c[_+2],c[_+2]=h}}const u=new P("float32",c,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:u}}async _call(e,...t){Array.isArray(e)||(e=[e]);const s=await Promise.all(e.map(n=>this.preprocess(n)));return{pixel_values:Ct(s.map(n=>n.pixel_values),0),original_sizes:s.map(n=>n.original_size),reshaped_input_sizes:s.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){const s=await Mt(e,ur,!0,t);return new this(s)}},cn={};sr(cn,{BeitFeatureExtractor:()=>bb,BitImageProcessor:()=>xb,CHMv2ImageProcessor:()=>Eb,CLIPFeatureExtractor:()=>Tb,CLIPImageProcessor:()=>u_,ChineseCLIPFeatureExtractor:()=>kb,ConvNextFeatureExtractor:()=>Ab,ConvNextImageProcessor:()=>__,DINOv3ViTImageProcessor:()=>Pb,DPTFeatureExtractor:()=>Ib,DPTImageProcessor:()=>f_,DeiTFeatureExtractor:()=>Cb,DeiTImageProcessor:()=>h_,DetrFeatureExtractor:()=>Sb,DetrImageProcessor:()=>p_,DonutFeatureExtractor:()=>Fb,DonutImageProcessor:()=>po,EfficientNetImageProcessor:()=>Lb,GLPNFeatureExtractor:()=>zb,Gemma3ImageProcessor:()=>Ob,Gemma4ImageProcessor:()=>uo,Glm46VImageProcessor:()=>Nb,GroundingDinoImageProcessor:()=>Db,Idefics3ImageProcessor:()=>g_,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>Rb,Lfm2VlImageProcessor:()=>jb,LlavaOnevisionImageProcessor:()=>qb,Mask2FormerImageProcessor:()=>Hb,MaskFormerFeatureExtractor:()=>Wb,MaskFormerImageProcessor:()=>fo,MobileNetV1FeatureExtractor:()=>Qb,MobileNetV1ImageProcessor:()=>v_,MobileNetV2FeatureExtractor:()=>Xb,MobileNetV2ImageProcessor:()=>y_,MobileNetV3FeatureExtractor:()=>Yb,MobileNetV3ImageProcessor:()=>M_,MobileNetV4FeatureExtractor:()=>Kb,MobileNetV4ImageProcessor:()=>b_,MobileViTFeatureExtractor:()=>Jb,MobileViTImageProcessor:()=>x_,NougatImageProcessor:()=>Zb,OwlViTFeatureExtractor:()=>ex,OwlViTImageProcessor:()=>mo,Owlv2ImageProcessor:()=>tx,Phi3VImageProcessor:()=>rx,PixtralImageProcessor:()=>nx,PvtImageProcessor:()=>ax,Qwen2VLImageProcessor:()=>m_,RTDetrImageProcessor:()=>ox,Sam2ImageProcessor:()=>vo,Sam3ImageProcessor:()=>vo,SamImageProcessor:()=>vo,SapiensFeatureExtractor:()=>ix,SapiensImageProcessor:()=>k_,SegformerFeatureExtractor:()=>lx,SegformerImageProcessor:()=>E_,SiglipImageProcessor:()=>cx,SmolVLMImageProcessor:()=>g_,Swin2SRImageProcessor:()=>dx,VLMImageProcessor:()=>Bb,ViTFeatureExtractor:()=>ux,ViTImageProcessor:()=>T_,VitMatteImageProcessor:()=>_x,VitPoseImageProcessor:()=>hx,YolosFeatureExtractor:()=>px,YolosImageProcessor:()=>A_});var bb=class extends X{},xb=class extends X{},kb=class extends X{},Eb=class extends X{},u_=class extends X{},Tb=class extends u_{},__=class extends X{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const s=Math.floor(t/this.crop_pct),[r,n]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(r,n,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},Ab=class extends __{},h_=class extends X{},Cb=class extends h_{},p_=class extends X{async _call(e){const t=await super._call(e),s=[t.pixel_values.dims[0],64,64],r=Re(s,1n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return ln(...e)}post_process_panoptic_segmentation(...e){return c_(...e)}post_process_instance_segmentation(...e){return d_(...e)}},Sb=class extends p_{},Pb=class extends X{},po=class extends X{pad_image(e,t,s,r={}){const[n,a,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const c=i.map((d,u)=>-d/l[u]);return super.pad_image(e,t,s,{center:!0,constant_values:c,...r})}},Fb=class extends po{},f_=class extends X{},Ib=class extends f_{},Lb=class extends X{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},Ob=class extends X{},m_=class extends X{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){const s=this.patch_size*this.merge_size;return ho(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:s,original_sizes:r,reshaped_input_sizes:n}=await super._call(e,...t);let a=s;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=fe(Array.from({length:o},()=>a),0));const c=a.dims[0]/o,d=a.dims[1],u=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),h=a.view(c,o,d,Math.floor(u/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*u*_,d*o*l*l),p=new P("int64",[c,u,_],[1,3]);return{pixel_values:h,image_grid_thw:p,original_sizes:r,reshaped_input_sizes:n}}},Nb=class extends m_{get_resize_output_image_size(e,t){const s=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return ho(e.height,e.width,s,this.min_pixels,this.max_pixels,r)}},zb=class extends X{},Db=class extends X{async _call(e){const t=await super._call(e),s=t.pixel_values.dims,r=qe([s[0],s[2],s[3]]);return{...t,pixel_mask:r}}},g_=class extends X{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[s,r]=e.dims.slice(-2);const n=r/s;return r>=s?(r=Math.ceil(r/t)*t,s=Math.floor(r/n),s=Math.ceil(s/t)*t):(s=Math.ceil(s/t)*t,r=Math.floor(s*n),r=Math.ceil(r/t)*t),{height:s,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:s=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?r=e:r=[e]}let n=[],a=[],o=[];const i=[],l=[];for(const g of r){let m=await Promise.all(g.map(v=>this.preprocess(v)));i.push(...m.map(v=>v.original_size)),l.push(...m.map(v=>v.reshaped_input_size)),m.forEach(v=>v.pixel_values.unsqueeze_(0));const{longest_edge:w}=this.max_image_size;let y;if(t??this.do_image_splitting){let v=new Array(m.length),M=new Array(m.length);y=await Promise.all(m.map(async(E,A)=>{const S=this.get_resize_for_vision_encoder(E.pixel_values,w),C=await ht(E.pixel_values,{size:[S.height,S.width]}),{frames:z,num_splits_h:R,num_splits_w:N}=await this.split_image(C,this.max_image_size);return v[A]=R,M[A]=N,fe(z,0)})),a.push(v),o.push(M)}else{const v=[w,w];y=await Promise.all(m.map(M=>ht(M.pixel_values,{size:v}))),a.push(new Array(m.length).fill(0)),o.push(new Array(m.length).fill(0))}n.push(fe(y,0))}const c=n.length,[d,u,_,h]=n[0].dims;let p,f;if(c===1)p=n[0].unsqueeze_(0),f=Re([c,d,_,h],!0);else{const g=Math.max(...n.map(y=>y.dims.at(0)));f=Re([c,g,_,h],!0);const m=f.data,w=g*_*h;for(let y=0;y<c;++y){const v=n[y].dims[0];if(v<g){n[y]=fe([n[y],Re([g-v,u,_,h],0)],0);const M=y*w+v*_*h,E=(y+1)*w;m.fill(!1,M,E)}}p=Ct(n,0)}return{pixel_values:p,pixel_attention_mask:f,original_sizes:i,reshaped_input_sizes:l,...s?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){const s=t,r=t,n=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>s||o>r){i=Math.ceil(a/s),l=Math.ceil(o/r);const c=Math.ceil(a/i),d=Math.ceil(o/l);for(let h=0;h<i;++h)for(let p=0;p<l;++p){let f,g,m,w;h===i-1?(g=a-c,w=a):(g=h*c,w=(h+1)*c),p===l-1?(f=o-d,m=o):(f=p*d,m=(p+1)*d);const M=await Iu(e,[g,f],[w,m],[2,3]);n.push(M)}const u=s,_=r;(a!==u||o!==_)&&(e=await ht(e,{size:[u,_]}))}return n.push(e),{frames:n,num_splits_h:i,num_splits_w:l}}},Bb=class extends X{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,s,r){return super.pad_image(e,t,s,{constant_values:this.constant_values,center:!0,...r})}},Rb=class extends X{constructor(e){const{resize_mode:t,fill_color:s,interpolation:r,size:n,...a}=e,o=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},i=r==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:n,do_normalize:!0})}};function w_(e,t){return Math.round(e/t)*t}function $b(e,t,s,r,n){let a=1/0,o=[1,1];const i=s*r;for(const l of t){const c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*n*n*l[0]*l[1]&&(o=l)}return o}function Gb(e,t){const s=[],r=new Set;for(let n=e;n<=t;++n)for(let a=1;a<=n;++a)for(let o=1;o<=n;++o){const i=a*o;if(i>=e&&i<=t){const l=a<<16|o;r.has(l)||(r.add(l),s.push([a,o]))}}return s.sort((n,a)=>n[0]*n[1]-a[0]*a[1])}function Vb(e,t){const[s,r,n,a]=e.dims,o=Math.floor(n/t),i=Math.floor(a/t),l=t*t*r,c=e.data,d=new Float32Array(s*o*i*l),u=n*a;for(let _=0;_<s;++_){const h=_*r*u,p=_*o*i*l;for(let f=0;f<o;++f)for(let g=0;g<i;++g){let m=p+(f*i+g)*l;for(let w=0;w<t;++w){const y=(f*t+w)*a+g*t;for(let v=0;v<t;++v){const M=y+v;for(let E=0;E<r;++E)d[m++]=c[h+E*u+M]}}}}return new P("float32",d,[s,o*i,l])}function Ub(e,t){const[,s,r]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,s);let a=e;if(s<t){const o=new Float32Array(t*r);o.set(e.data),a=new P("float32",o,[1,t,r])}return{padded:a,mask:new P("int64",n,[t])}}var jb=class extends X{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;const t=this.max_image_tokens*this.downsample_factor**2,s=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,s)}_is_image_too_large(e,t){const s=this.encoder_patch_size*this.downsample_factor,r=Math.max(this.encoder_patch_size,w_(e,s)),n=Math.max(this.encoder_patch_size,w_(t,s));return r*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const s=Gb(this.min_tiles,this.max_tiles),[r,n]=$b(t/e,s,t,e,this.tile_size);return{grid_width:r,grid_height:n,target_width:this.tile_size*r,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];const r=[],n=[],a=[],o=[],i=[],l=[];for(const d of s){const u=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(const{pixel_values:_}of u){const[,h,p]=_.dims,f=_.unsqueeze_(0),g=this.encoder_patch_size*this.downsample_factor,m=g**2,[w,y]=ho(Math.max(g,h),Math.max(g,p),g,this.min_image_tokens*m,this.max_image_tokens*m).map(C=>Math.max(g,C));let v,M=1,E=1;const A=this._is_image_too_large(h,p),S=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(A&&S){const{grid_width:C,grid_height:z,target_width:R,target_height:N}=this._get_grid_layout(h,p);M=z,E=C;const O=await ht(f,{size:[N,R]});v=[];for(let $=0;$<z;++$)for(let L=0;L<C;++L){const D=$*this.tile_size,se=L*this.tile_size;v.push(O.slice(null,null,[D,D+this.tile_size],[se,se+this.tile_size]))}this.use_thumbnail&&C*z!==1&&v.push(await ht(f,{size:[y,w]}))}else v=[await ht(f,{size:[y,w]})];for(const C of v){const[,,z,R]=C.dims,N=Vb(C,this.encoder_patch_size),{padded:O,mask:$}=Ub(N,this.max_num_patches);r.push(O),n.push($),a.push([Math.floor(z/this.encoder_patch_size),Math.floor(R/this.encoder_patch_size)])}o.push(M),i.push(E),l.push([y,w])}}const c={pixel_values:fe(r,0),pixel_attention_mask:Ct(n,0),spatial_shapes:new P("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(c.image_rows=o,c.image_cols=i,c.image_sizes=l),c}},qb=class extends X{},fo=class extends X{post_process_panoptic_segmentation(...e){return c_(...e)}post_process_instance_segmentation(...e){return d_(...e)}},Wb=class extends fo{},Hb=class extends fo{},v_=class extends X{},Qb=class extends v_{},y_=class extends X{},Xb=class extends y_{},M_=class extends X{},Yb=class extends M_{},b_=class extends X{},Kb=class extends b_{},x_=class extends X{},Jb=class extends x_{},Zb=class extends po{},mo=class extends X{post_process_object_detection(...e){return ln(...e)}},ex=class extends mo{},tx=class extends mo{},Ye=336,sx=[2,3],{ceil:go,floor:ks,sqrt:wo}=Math,rx=class extends X{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){const{num_img_tokens:s}=this.config;return ks((ks(t/Ye)*ks(e/Ye)+1)*s+1+(ks(t/Ye)+1)*wo(s))}get_resize_output_image_size(e,t){const s=this._num_crops,[r,n]=e.size;let a=r/n,o=1;for(;o*Math.ceil(o/a)<=s;)o+=1;o-=1;const i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,s,r={}){const[n,a]=t,o=Ye*go(n/Ye),i=Ye*go(a/Ye),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,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||wo(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const s=e.length,r=await Promise.all(e.map(u=>this.preprocess(u))),n=r.map(u=>u.original_size),a=r.map(u=>u.reshaped_input_size),o=[];for(const{pixel_values:u}of r){u.unsqueeze_(0);const[_,h]=u.dims.slice(-2),p=await ht(u,{size:[Ye,Ye],mode:"bicubic"});if(t>0){const f=[],g=wo(t),m=ks(h/g),w=ks(_/g);for(let v=0;v<g;++v)for(let M=0;M<g;++M){let E,A,S,C;v===g-1?(A=_-w,C=_):(A=v*w,C=(v+1)*w),M===g-1?(E=h-m,S=h):(E=M*m,S=(M+1)*m);const N=await Iu(u,[A,E],[C,S],sx);f.push(N)}const y=await ht(fe(f,0),{size:[Ye,Ye],mode:"bicubic"});o.push(fe([p,y],0))}else o.push(p)}const i=Ct(o,0),l=a.map(u=>u.map(_=>Ye*go(_/Ye))),c=new P("int64",l.flat(),[s,2]),d=l.map(([u,_])=>this.calc_num_image_tokens_from_image_size(_,u));return{pixel_values:i,original_sizes:n,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},nx=class extends X{get_resize_output_image_size(e,t){const{longest_edge:s}=t;if(s===void 0)throw new Error("size must contain 'longest_edge'");const[r,n]=e.size,a=Math.max(r,n)/s;let o=r,i=n;a>1&&(o=Math.floor(r/a),i=Math.floor(n/a));const{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");const d=l*c,u=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[u*d,_*d]}},ax=class extends X{},ox=class extends X{post_process_object_detection(...e){return ln(...e)}},vo=class extends X{reshape_input_points(e,t,s,r=!1){e=structuredClone(e);let n=pd(e);if(n.length===3)r||(n=[1,...n]),e=[e];else if(n.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){const[o,i]=t[a],[l,c]=s[a],d=[c/i,l/o];for(let u=0;u<e[a].length;++u)for(let _=0;_<e[a][u].length;++_)for(let h=0;h<e[a][u][_].length;++h)e[a][u][_][h]*=d[h%2]}return new P("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let s=pd(e);if(s.length===2)s=[1,...s],e=[e];else if(s.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(s.some((r,n)=>r!==t.dims[n]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new P("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:t=null,input_labels:s=null,input_boxes:r=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),s){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(s,n.input_points)}return r&&(n.input_boxes=this.reshape_input_points(r,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,s,{mask_threshold:r=0,binarize:n=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;l<t.length;++l){const c=t[l],d=s[l];let u=await ht(e[l],{mode:"bilinear",size:i});if(u=u.slice(null,null,[0,d[0]],[0,d[1]]),u=await ht(u,{mode:"bilinear",size:c}),n){const _=u.data,h=new Uint8Array(_.length);for(let p=0;p<_.length;++p)_[p]>r&&(h[p]=1);u=new P("bool",h,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:s=0,overlap_ratio:r=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:a=1}={}){}},k_=class extends X{post_process_semantic_segmentation(...e){return l_(...e)}},ix=class extends k_{},E_=class extends X{post_process_semantic_segmentation(...e){return l_(...e)}},lx=class extends E_{},cx=class extends X{},dx=class extends X{pad_image(e,t,s,r={}){const[n,a,o]=t;return super.pad_image(e,t,{width:a+(s-a%s)%s,height:n+(s-n%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...r})}},T_=class extends X{},ux=class extends T_{},_x=class extends X{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=await Promise.all(e.map(a=>this.preprocess(a))),r=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Ct(s.map((a,o)=>fe([a.pixel_values,r[o].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}},hx=class extends X{post_process_pose_estimation(e,t,{threshold:s=null}={}){const r=e.tolist(),[n,a,o,i]=e.dims,l=[];for(let c=0;c<n;++c){const d=r[c],u=t[c],_=[];for(let h=0;h<u.length;++h){const p=u[h],f=[],g=[],m=[],w=p.at(-2)/i,y=p.at(-1)/o;for(let v=0;v<d.length;++v){let[M,E]=[0,0],A=0,S=-1/0;const C=d[v];for(let R=0;R<C.length;++R){const N=C[R];for(let O=0;O<N.length;++O){const $=N[O];A+=$,S=Math.max(S,$),M+=(O+.5)*$,E+=R*$}}if(s!=null&&S<s)continue;const z=[w*M/A,y*E/A];f.push(z),m.push(v),g.push(S)}_.push({bbox:p,scores:g,labels:m,keypoints:f})}l.push(_)}return l}},A_=class extends X{post_process_object_detection(...e){return ln(...e)}},px=class extends A_{},Ge=class{static async from_pretrained(e,t={}){const s=await Mt(e,ur,!0,t),r=s.image_processor_type??s.feature_extractor_type;let n=cn[r?.replace(/Fast$/,"")];return n||(r!==void 0&&Q.warn(`Image processor type '${r}' not found, assuming base ImageProcessor. Please report this at ${an}.`),n=X),new n(s)}},fx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;constructor(e,t,s){super(e,t,s);const{tasks_answer_post_processing_type:r,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(r??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const t=[];for(const s of e)if(this.task_prompts_without_inputs.has(s))t.push(this.task_prompts_without_inputs.get(s));else{for(const[r,n]of this.task_prompts_with_input)if(s.includes(r)){t.push(n.replaceAll("{input}",s).replaceAll(r,""));break}t.length!==e.length&&t.push(s)}return t}post_process_generation(e,t,s){const r=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(r){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=r==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[c,d,...u]of o)i.push(d?d.trim():i.at(-1)??""),l.push(u.map((_,h)=>(Number(_)+.5)/this.size_per_bin*s[h%2]));n={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");const r=await this.image_processor(e,s),n=t?this.tokenizer(this.construct_prompts(t),s):{};return{...r,...n}}},mx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,s),this.image_seq_length=this.config.image_seq_length;const{boi_token:r,image_token:n,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=n,this.eoi_token=a;const o=n.repeat(this.image_seq_length);this.full_image_sequence=`
|
||
|
||
${r}${o}${a}
|
||
|
||
`}async _call(e,t=null,s={}){typeof e=="string"&&(e=[e]);let r;return t&&(r=await this.image_processor(t,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...r}}},gx=class extends oe{static image_processor_class=Ge;static feature_extractor_class=rt;static tokenizer_class=ne;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:r,boa_token:n,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=n,this.audio_token=a;const u=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
||
|
||
${n}${u}${o}
|
||
|
||
`,this.image_token_id=i,this.boi_token=l,this.image_token=c;const _=c.repeat(this.image_seq_length);this.full_image_sequence=`
|
||
|
||
${l}${_}${d}
|
||
|
||
`}async _call(e,t=null,s=null,r={}){typeof e=="string"&&(e=[e]);let n;s&&(n=await this.feature_extractor(s,r),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...n}}},yo=class extends oe{static image_processor_class=Ge;static tokenizer_class=ne;static image_token="<|image_pad|>";async _call(e,t=null,...s){Array.isArray(e)||(e=[e]);let r,n;if(t&&(r=await this.image_processor(t),n=r.image_grid_thw),n){let o=this.image_processor.config.merge_size**2,i=0;const l=this.constructor.image_token,c=n.tolist();e=e.map(d=>{for(;d.includes(l);){const u=Number(c[i++].reduce((_,h)=>_*h,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(u/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...r}}},wx=class extends yo{static image_token="<|image|>"},vx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;static uses_processor_config=!0;_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:r}=this.feature_extractor.config,n=Math.floor(s/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/s)*n}async _call(e,t=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let r={};if(t){const{input_features:a}=await this.feature_extractor(t);r.input_features=a;const o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);r.input_features_mask=new P("bool",i,[1,o]);const l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...r}}};function yx(e,t){const r=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,r);const a=t.tolist();return n.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var Mx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;async _call(e,t,s={}){const r=e?await this.image_processor(e,s):{};return{...t?this.tokenizer(t,s):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:s=.25,text_threshold:r=.25,target_sizes:n=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(n!==null&&n.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),u=o.tolist().map(h=>h.map(p=>i_(p))),_=[];for(let h=0;h<i;++h){const p=n!==null?n[h]:null;p!==null&&(u[h]=u[h].map(y=>y.map((v,M)=>v*p[(M+1)%2])));const f=d[h],g=[],m=[],w=[];for(let y=0;y<l;++y){const v=f[y];if(v<=s)continue;const M=u[h][y],E=c[h][y];g.push(v),w.push(M);const A=yx(E.gt(r),t[h]);m.push(A)}_.push({scores:g,boxes:w,labels:this.batch_decode(m)})}return _}};function bx(e,t,s,r,n,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<s;++l)o+=r+`<row_${i+1}_col_${l+1}>`+n.repeat(e);o+=`
|
||
`}return o+=`
|
||
${r}${a}`+n.repeat(e)+`${r}`,o}function xx(e,t,s,r){return`${t}${r}`+s.repeat(e)+`${t}`}function kx(e,t,s,r,n,a){return e===0&&t===0?xx(s,r,n,a):bx(s,e,t,r,n,a)}var C_=class extends oe{static image_processor_class=Ge;static tokenizer_class=ne;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,s={}){s.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,s)),Array.isArray(e)||(e=[e]);const n=r.rows??[new Array(e.length).fill(0)],a=r.cols??[new Array(e.length).fill(0)],o=this.config.image_seq_len,i=[],l=[];for(let d=0;d<e.length;++d){const u=e[d],_=n[d],h=a[d];i.push(xm(u,this.image_token));const p=_.map((m,w)=>kx(m,h[w],o,this.fake_image_token,this.image_token,this.global_img_token)),f=u.split(this.image_token);if(f.length===0)throw new Error("The image token should be present in the text.");let g=f[0];for(let m=0;m<p.length;++m)g+=p[m]+f[m+1];l.push(g)}return{...this.tokenizer(l),...r}}},Ex=class extends oe{static image_processor_class=Ge;static tokenizer_class=ne;static uses_processor_config=!0;constructor(e,t,s){super(e,t,s),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:s="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(f=>f.images).flatMap(f=>f.images).map(f=>pt.read(f)));const r=this.tokenizer,n=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=f=>r.encode(f,{add_special_tokens:!1}),o=n.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,c,d]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let u=a(o[0]),_=new Array(u.length).fill(!1);for(let f=1;f<o.length;++f){const g=new Array(this.num_image_tokens).fill(l),m=a(o[f]);u=ot(u,[c],g,[d],m);const w=new Array(this.num_image_tokens).fill(!0);_=ot(_,[!1],w,[!1],new Array(m.length).fill(!1))}const h=[1,u.length],p={input_ids:new P("int64",u,h),attention_mask:new P("int64",new Array(u.length).fill(1),h),images_seq_mask:new P("bool",_,h),images_emb_mask:new P("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const f=await this.image_processor(t);return f.pixel_values.unsqueeze_(0),{...p,...f}}return p}},Tx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;async _call(e=null,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");const r=e?this.tokenizer(e,s):{},n=t?await this.image_processor(t,s):{};return{...r,...n}}},Ax=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;async _call(e,t=null,s={}){const{image_rows:r,image_cols:n,image_sizes:a,...o}=await this.image_processor(e,{...s,return_row_col_info:!0});if(t){const i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:u=!0}=this.image_processor.config,_=w=>Math.ceil(Math.floor(w/d)/c),h=_(l)**2,p=this.config.image_start_token??"<|image_start|>",f=this.config.image_end_token??"<|image_end|>",g=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let m=0;t=t.map(w=>{const y=w.split(i);return y[0]+y.slice(1).map(v=>{const M=m++,[E,A]=a[M],S=r[M],C=n[M],z=_(E)*_(A);let R=p;if(S>1||C>1){const N=i.repeat(h);for(let O=0;O<S;++O)for(let $=0;$<C;++$)R+=`<|img_row_${O+1}_col_${$+1}|>`+N;u&&(R+=g+i.repeat(z))}else R+=i.repeat(z);return R+f+v}).join("")})}return{...o,...t?this.tokenizer(t,s):{}}}},Cx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;static uses_processor_config=!0;async _call(e,t=null,s={}){const r=await this.image_processor(e,s);if(t){const[a,o]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let u=0;u<t.length;++u)t[u]=t[u].replace(i,i.repeat(d))}const n=t?this.tokenizer(t,s):{};return{...r,...n}}},S_={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Sx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;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(!S_.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[s,r]=S_[t],n=this[s].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let u=0;u<a;++u){const _=c[u],h=[],p=[];for(let g=1;g<o;++g){const[m,w]=ke(Ne(_[g]));if(p.push(m),w==r)break;h.push(w)}const f=p.length>0?p.reduce((g,m)=>g*m,1):0;l.push(h),i.push(f)}return[n(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,s]){const[r,n]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(s,"wp"),c=[],d=[];for(let u=0;u<r.length;++u){const[_,h]=ke([n[u],o[u],l[u]]);c.push([r[u],a[u],i[u]][h]),d.push(_)}return{generated_text:c,scores:d,char_preds:r,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),s=await ne.from_pretrained("Xenova/gpt2"),r=await ne.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:s,wp_tokenizer:r},t}async _call(e,t=null){const s=await this.image_processor(e);return t&&(s.labels=this.tokenizer(t).input_ids),s}},Px=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}},Fx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge},Es="<image>";function Ix(e,t,s,r,n){return`${r.repeat(s*n)}${t}${e}
|
||
`}var Lx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;static uses_processor_config=!1;async _call(e,t=null,s={}){t||(Q.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(Es))?a=t.map(l=>{const c=l.replaceAll(Es,Es.repeat(n)),d=c.lastIndexOf(Es),u=d===-1?0:d+Es.length;return c.slice(0,u)+r+c.slice(u)+`
|
||
`}):(Q.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=>Ix(l,r,n,Es,e.length)));const o=this.tokenizer(a,s);return{...await this.image_processor(e,s),...o}}},P_="<|image|>",Ox=/<\|image_\d+\|>/g,Nx=class extends oe{static image_processor_class=Ge;static tokenizer_class=ne;async _call(e,t=null,{padding:s=!0,truncation:r=!0,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:n});const{num_img_tokens:i}=o,l=e.map((d,u)=>d.split(Ox).join(P_.repeat(i[u])));a=this.tokenizer(l,{padding:s,truncation:r});const c=this.tokenizer._tokenizer.token_to_id(P_);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},zx=class extends oe{static tokenizer_class=ne;static image_processor_class=Ge;static uses_processor_config=!0;async _call(e,t=null,s={}){const r=await this.image_processor(e,s);if(t){const[a,o]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:d,spatial_merge_size:u}=this.config,_=d*u,h=Math.floor(a/_),p=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let f=0;f<t.length;++f){const g=i.repeat(p),m=g+l,w=g+c,y=m.repeat(h-1)+w;t[f]=t[f].replace(i,y)}}const n=t?this.tokenizer(t,s):{};return{...r,...n}}},Dx=class extends oe{static feature_extractor_class=t_;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}},F_=class extends yo{},Bx=class extends F_{},I_=class extends oe{static image_processor_class=Ge;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)}},L_=class extends I_{},Rx=class extends L_{},$x=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}},Gx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;static uses_processor_config=!0;async _call(e,t=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let r={};if(t){const a=t.length,{input_features:o}=await this.feature_extractor(t,{...s,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);r.audio_token_len=[l],r.audio_values=o;const c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...r}}},dn="[AUDIO]",Vx="[BEGIN_AUDIO]",Ux=375;function jx(e,t){const s=[];for(let r=0;r<e.length;r+=t)s.push(e.subarray(r,Math.min(r+t,e.length)));return s}var qx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;static uses_processor_config=!1;async _call(e,t=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const r={};if(t){if(!e.includes(dn))throw new Error(`The input text does not contain the audio token ${dn}.`);Array.isArray(t)||(t=[t]);const a=e.split(dn),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(h=>jx(h,i)),c=l.map(h=>h.length),d=l.flat(),u=(await Promise.all(d.map(h=>this.feature_extractor(h,s)))).map(h=>h.input_features);r.audio_values=u.length>1?fe(u,0):u[0];let _=a[0];for(let h=0;h<c.length;++h){_+=Vx;for(let p=0;p<c[h];++p)_+=dn.repeat(Ux);_+=a[h+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...r}}},O_=32,Mo=6,un=8,Wx=10,Hx=32,Qx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Mo+1)*un}get num_samples_first_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return un*e+t}get num_right_pad_tokens(){return Mo+1+Wx}get audio_length_per_tok(){return un}get raw_audio_length_per_tok(){return un*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:s=!0}={}){if(ze(e,"VoxtralRealtimeProcessor"),!t&&!s)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(s)if(t){const r=O_*this.raw_audio_length_per_tok,n=new Float32Array(r+e.length);n.set(e,r);const a=await this.feature_extractor(n,{center:!0}),i=1+(O_+Mo),l=new BigInt64Array(i).fill(BigInt(Hx));return l[0]=1n,{input_ids:new P("int64",l,[1,i]),...a}}else{const r=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+r);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},Xx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}},Yx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}},Kx=class extends oe{static tokenizer_class=ne;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}},Jx=class{static async from_pretrained(e,t={}){const s=await Mt(e,ur,!0,t),{image_processor_type:r,feature_extractor_type:n,processor_class:a}=s;if(a&&oo[a])return oo[a].from_pretrained(e,t);if(!r&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(r){const l=cn[r.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${r}'.`);o.image_processor=new l(s)}if(n){const l=cn[n];if(l)o.image_processor=new l(s);else{const c=io[n];if(!c)throw new Error(`Unknown feature_extractor_type: '${n}'.`);o.feature_extractor=new c(s)}}const i={};return new oe(i,o,null)}};async function Zx(e,t){return await Mt(e,"config.json",!0,t)}function Ts(e){const t={};let s={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":s=Ts(e.text_config);break;case"moondream1":s=Ts(e.phi_config);break;case"musicgen":s=Ts(e.decoder);break;case"multi_modality":s=Ts(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"deepseek_v4":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv=e.model_type==="deepseek_v4"?"head_dim":"qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"zaya":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"hrm_text":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";const{num_hidden_layers:n,num_attention_heads:a,hidden_size:o}=e.encoder_config;s={num_encoder_layers:n,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":const i=Ts(e.decoder),l="num_decoder_layers"in i,c=Ie(e,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=i.num_decoder_layers,c.num_decoder_heads=i.num_decoder_heads,c.decoder_hidden_size=i.decoder_hidden_size,c.num_encoder_layers=i.num_encoder_layers,c.num_encoder_heads=i.num_encoder_heads,c.encoder_hidden_size=i.encoder_hidden_size):(c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size),c}const r={...s,...Ie(e,["model_type","multi_query","is_encoder_decoder"])};for(const n in t)r[n]=e[t[n]];return r}function _n(e,t){e instanceof bo||(e=new bo(e));const s=t?.prefix??"past_key_values",r=s==="present"?"present":"past",n=new Set;if(["lfm2","lfm2_moe"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")n.add(`${s}.${o}.key`),n.add(`${s}.${o}.value`);else if(a[o]==="conv")n.add(`${r}_conv.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){const a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??o?.length;for(let l=0;l<i;++l)(!o||o[l]==="mamba")&&(n.add(`${r}_conv.${l}`),n.add(`${r}_ssm.${l}`)),(!o||o[l]==="attention")&&(n.add(`${s}.${l}.key`),n.add(`${s}.${l}.value`));return n}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")n.add(`${s}.${o}.key`),n.add(`${s}.${o}.value`);else if(a[o]==="linear_attention")e.model_type==="olmo_hybrid"?(n.add(`${r}_conv.${o}.key`),n.add(`${r}_conv.${o}.value`),n.add(`${r}_conv.${o}.query`)):n.add(`${r}_conv.${o}`),n.add(`${r}_recurrent.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}else if(["gemma4","gemma4_text"].includes(e.model_type)){const a=e.model_type==="gemma4"?e.text_config:e,o=a.num_hidden_layers,i=a.num_kv_shared_layers??0,l=o-i;for(let c=0;c<l;++c)n.add(`${s}.${c}.key`),n.add(`${s}.${c}.value`);return n}else if(e.model_type==="deepseek_v4"){const{layer_types:a,num_hidden_layers:o}=e;for(let i=0;i<o;++i){n.add(`${s}.${i}.key`),n.add(`${s}.${i}.value`);const l=a[i];if(l==="compressed_sparse_attention")n.add(`${r}_compressor.${i}.kv`),n.add(`${r}_compressor.${i}.gate`),n.add(`${r}_indexer.${i}.kv`),n.add(`${r}_indexer.${i}.gate`);else if(l==="heavily_compressed_attention")n.add(`${r}_compressor.${i}.kv`),n.add(`${r}_compressor.${i}.gate`);else if(l&&l!=="sliding_attention")throw new Error(`Unsupported layer type: ${l}`)}return n}else if(e.model_type==="zaya"){const{num_hidden_layers:a,cca_time1:o}=e,i=o??1;for(let l=0;l<a;l+=i)n.add(`${s}.${l}.key`),n.add(`${s}.${l}.value`),n.add(`${s}.${l}.conv_state`),n.add(`${s}.${l}.shift_state`);return n}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let a;return e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder"?a=e.audio_config:a=e.text_config,_n(a,t)}return e0(e,{prefix:s})}function e0(e,{prefix:t="past_key_values"}={}){const s=new Set,r=e.normalized_config;if(r.is_encoder_decoder&&"num_encoder_heads"in r&&"num_decoder_heads"in r)for(let n=0;n<r.num_decoder_layers;++n)s.add(`${t}.${n}.encoder.key`),s.add(`${t}.${n}.encoder.value`),s.add(`${t}.${n}.decoder.key`),s.add(`${t}.${n}.decoder.value`);else if(r.multi_query)for(let n=0;n<r.num_layers;++n)s.add(`${t}.${n}.key_value`);else for(let n=0;n<r.num_layers;++n)s.add(`${t}.${n}.key`),s.add(`${t}.${n}.value`);return s}var bo=class Ul{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=Ts(this)}static async from_pretrained(t,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){r&&!(r instanceof Ul)&&(r=new Ul(r));const i=r??await Zx(t,{progress_callback:s,config:r,cache_dir:n,local_files_only:a,revision:o});return new this(i)}},_r=class{static async from_pretrained(...e){return bo.from_pretrained(...e)}};function N_(e,t,s){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(s)?+e[s]:0:+e:0}function z_(e,t){const s=[];for(let r=0;r<t;++r)s.push(`${e}_data${r===0?"":"_"+r}`);return s}async function t0(e,t,s,r){const n=`${t}${r}.onnx`,a=`${s.subfolder??""}/${n}`;return await sn(e,a,!0,s,Y.IS_NODE_ENV)}async function s0(e,t,s,r,n,a={}){const o=`${t}${s}.onnx`,i=Y.IS_NODE_ENV;let l=[];const c=N_(n,o,t);if(c>0){if(c>iu)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${iu}).`);const d=z_(o,c);for(const u of d){const _=`${r.subfolder??""}/${u}`;l.push(new Promise(async(h,p)=>{const f=await sn(e,_,!0,r,i);h(f instanceof Uint8Array?{path:u,data:f}:u)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const u=await sn(e,d.data,!0,r);return{...d,data:u}}return d}));return Promise.all(l)}async function r0(e,t,s,r=!1,n=void 0){let a=s.config?.["transformers.js_config"]??{};const o=Au(s.device??a.device,t,{warn:w=>Q.info(w)}),i=Ty(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const c=Pu(s.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:w=>Q.info(w)});if(Ka.hasOwnProperty(c)){if(o==="webgpu"&&!Y.IS_NODE_ENV&&c===Te.fp16&&!await Sy())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(Te).join(", ")}`);const d=Ka[c],u={...s.session_options};u.executionProviders??=i;const _=a.free_dimension_overrides;_?u.freeDimensionOverrides??=_:o.startsWith("webnn")&&!u.freeDimensionOverrides&&Q.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const h=t0(e,t,s,d),p=s.use_external_data_format??a.use_external_data_format,f=await s0(e,t,d,s,p,u);if(f.length>0&&(!Y.IS_NODE_ENV||f.some(w=>typeof w!="string"))&&(u.externalData=f),r&&o==="webgpu"){const w=_n(s.config,{prefix:"present",session_name:n});if(w.size>0&&!Xa()){const y={};for(const v of w)y[v]="gpu-buffer";u.preferredOutputLocation=y}}return{buffer_or_path:await h,session_options:u,session_config:{dtype:c,device:o}}}async function n0(e,t,s,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const a=r?.[n]??!1,{buffer_or_path:o,session_options:i,session_config:l}=await r0(e,t[n],s,a,n),c=await xu(o,i,l);return[n,c]})))}function D_(e){for(let t in e)Tu(e[t])?e[t]=new P(e[t]):typeof e[t]=="object"&&D_(e[t]);return e}async function te(e,t){const s=a0(e,t);try{const r=Object.fromEntries(Object.entries(s).map(([a,o])=>{const i=o.ort_tensor;return Y.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),n=await Eu(e,r);return D_(n)}catch(r){const n=Object.fromEntries(Object.entries(s).map(([a,o])=>{const i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw Q.error(`An error occurred during model execution: "${r}".`),Q.error("Inputs given to model:",n),r}}function a0(e,t){const s=Object.create(null),r=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof P)){r.push(o);continue}s[o]=Xa()?i.clone():i}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const n=Object.keys(t).length,a=e.inputNames.length;if(n>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));Q.warn(`WARNING: Too many inputs were provided (${n} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return s}var Me=class{},o0=class extends Me{constructor({last_hidden_state:e,hidden_states:t=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=s}},V=class extends Me{constructor({logits:e,...t}){super(),this.logits=e;const s=Object.values(t);s.length>0&&(this.attentions=s)}},Ee=class extends Me{constructor({logits:e}){super(),this.logits=e}},Ae=class extends Me{constructor({logits:e}){super(),this.logits=e}},De=class extends Me{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},qt=class extends Me{constructor({logits:e}){super(),this.logits=e}},i0=class extends Me{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}},l0=class extends Me{constructor({logits:e,past_key_values:t,encoder_outputs:s,decoder_attentions:r=null,cross_attentions:n=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=s,this.decoder_attentions=r,this.cross_attentions=n}},B_=class extends Me{constructor({alphas:e}){super(),this.alphas=e}},ft=class extends Ue{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},c0=class extends Ue{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},xo=class extends Ue{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let s=t;for(const r of this.processors)s=r(e,s);return s}[Symbol.iterator](){return this.processors.values()}},d0=class extends ft{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===1){const r=t[s].data;r.fill(-1/0),r[this.bos_token_id]=0}return t}},u0=class extends ft{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){const r=t[s].data;r.fill(-1/0);for(const n of this.eos_token_id)r[n]=0}return t}},_0=class extends ft{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;for(const n of this.suppress_tokens)r[n]=-1/0}return t}},R_=class extends ft{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){const r=t[s].data;for(const n of this.begin_suppress_tokens)r[n]=-1/0}return t}},h0=class extends ft{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;if(r[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index){r.subarray(0,this.timestamp_begin).fill(-1/0);continue}const n=e[s].slice(this.begin_index),a=n.length>=1&&n[n.length-1]>=this.timestamp_begin,o=n.length<2||n[n.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){const d=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(d+1).fill(-1/0)}const i=hy(r),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,u)=>d+u)),c=ke(i.subarray(0,this.timestamp_begin))[0];l>c&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},p0=class extends ft{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,s=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[n+o]);s.push(a.map(Number))}const r=new Map;for(const n of s){const a=n.slice(0,n.length-1),o=JSON.stringify(a),i=r.get(o)??[];i.push(n[n.length-1]),r.set(o,i)}return r}getGeneratedNgrams(e,t){const s=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const s=this.getNgrams(e);return this.getGeneratedNgrams(s,e)}}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=this.calcBannedNgramTokens(e[s]);for(const a of n)r[a]=-1/0}return t}},f0=class extends ft{constructor(e){super(),this.penalty=e}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data;for(const n of new Set(e[s])){const a=Number(n);r[a]<0?r[a]*=this.penalty:r[a]/=this.penalty}}return t}},m0=class extends ft{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){const r=t[s].data;for(const n of this.eos_token_id)r[n]=-1/0}return t}},g0=class extends ft{constructor(e,t,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){const n=t[s].data;for(const a of this.eos_token_id)n[a]=-1/0}return t}},w0=class extends ft{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s){const r=t[s].data,n=e[s];for(const a of this.bad_words_ids){if(n.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=n.at(-i)){o=!1;break}o&&(r[a.at(-1)]=-1/0)}}return t}},v0=class extends ft{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const s=e.length,r=t.slice([0,s],null),n=t.slice([s,t.dims[0]],null);for(let a=0;a<n.data.length;++a)n.data[a]+=(r.data[a]-n.data[a])*this.guidance_scale;return n}},y0=class extends c0{constructor(e){super(),this.temperature=e}_call(e,t){const s=t.data;for(let r=0;r<s.length;++r)s[r]/=this.temperature;return t}},$_=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,Ie(e,Object.getOwnPropertyNames(this)))}},hr=class extends Ue{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},G_=class vf extends Ue{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof vf?t=t.criteria:t instanceof hr&&(t=[t]),this.criteria.push(...t)}_call(t,s){const r=new Array(t.length).fill(!1);for(const n of this.criteria){const a=n(t,s);for(let o=0;o<r.length;++o)r[o]||=a[o]}return r}[Symbol.iterator](){return this.criteria.values()}},M0=class extends hr{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)}},b0=class extends hr{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(s=>{const r=s.at(-1);return this.eos_token_id.some(n=>r==n)})}},x0=class extends hr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}},hn=class extends Ue{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 s=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-s);else{let n=t*s;r=r.slice(n,n+s)}return r}randomSelect(e){return Yv(e)}static getSampler(e){if(e.do_sample)return new E0(e);if(e.num_beams>1)return new T0(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new k0(e)}},k0=class extends hn{async sample(e){const t=ke(e.data)[1];return[[BigInt(t),0]]}},E0=class extends hn{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await xs(e,t),n=Ne(s.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(n);return[r.data[a],Math.log(n[a])]})}},T0=class extends hn{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[s,r]=await xs(e,t),n=Ne(s.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[r.data[o],Math.log(n[o])])}},A0=class{constructor(e){if(e)for(const t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);const s=e[t];if(!(s instanceof P))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof s}`);this[t]=s}}get_seq_length(){const e=this;if(Object.keys(e).length===0)return 0;for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(const t in e){const s=this[t],r=e[t];s&&s!==r&&s.location==="gpu-buffer"&&s.dispose(),this[t]=r}}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},ko=A0,I={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},Pt={[I.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[I.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[I.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[I.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[I.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"}},[I.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[I.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[I.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{const r={...Pt[I.ImageTextToText].text_only_sessions};return s||(r.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(r.model="encoder_model"),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[I.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{const r={...Pt[I.AudioTextToText].text_only_sessions};return s||(r.audio_encoder="audio_encoder"),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[I.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{const r={...Pt[I.ImageAudioTextToText].text_only_sessions};return s||(r.audio_encoder="audio_encoder",r.vision_encoder="vision_encoder"),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[I.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"}},[I.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"}},[I.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[I.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[I.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"}},[I.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{const r={...Pt[I.VoxtralRealtime].text_only_sessions};return s||(r.audio_encoder="audio_encoder"),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},[I.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 C0(e){return Pt[e]?.text_only_sessions??null}function S0(e,t,s={}){const r=Pt[e]??Pt.default;return{sessions:r.sessions(t,s,s.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function V_(e,{warn:t=!0}={}){const s=e.architectures||[];for(const r of s){const n=Ft.get(r);if(n!==void 0)return n}if(e.model_type){const r=Ft.get(e.model_type);if(r!==void 0)return r;for(const n of Object.values(As))if(n.has(e.model_type)){const a=Ft.get(n.get(e.model_type));if(a!==void 0)return a}}if(t){const r=s.length>0?s.join(", "):"(none)";Q.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${r}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${an}`)}return I.EncoderOnly}function U_(e,{config:t=null,cache_dir:s=null,local_files_only:r=!1,revision:n="main"}={}){if(t!==null)return _r.from_pretrained(e,{config:t,cache_dir:s,local_files_only:r,revision:n});const a=$a(e,{cache_dir:s,local_files_only:r,revision:n});return hu(a,()=>_r.from_pretrained(e,{config:t,cache_dir:s,local_files_only:r,revision:n}))}async function j_(e,{config:t=null,dtype:s=null,device:r=null,model_file_name:n=null}={}){t=await U_(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=r??o.device;let d=s??o.dtype;const u=V_(t),_=(f,g=null)=>{g=g??f;const m=Au(c,f),w=Pu(d,f,m),y=Ka[w]??"",v=`${g}${y}.onnx`,M=`${l}/${v}`;a.push(M);const E=N_(i,v,f);for(const A of z_(v,E)){const S=`${l}/${A}`;a.push(S)}},{sessions:h,optional_configs:p}=S0(u,t,{model_file_name:n});for(const[f,g]of Object.entries(h))_(f,g);if(p)for(const f of Object.values(p))a.push(f);return a}var As=null;function P0(e){As=e}function Eo(e){if(e instanceof P)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 P("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new P("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function q_(e){return new P("bool",[e],[1])}var W_={[I.DecoderOnly]:{can_generate:!0,forward:It,prepare_inputs:Ss},[I.DecoderOnlyWithoutHead]:{can_generate:!1,forward:It,prepare_inputs:Ss},[I.Seq2Seq]:{can_generate:!0,forward:pn,prepare_inputs:fn},[I.Vision2Seq]:{can_generate:!0,forward:pn,prepare_inputs:fn},[I.Musicgen]:{can_generate:!0,forward:pn},[I.EncoderDecoder]:{can_generate:!1,forward:pn},[I.ImageTextToText]:{can_generate:!0,forward:O0,prepare_inputs:mn},[I.AudioTextToText]:{can_generate:!0,forward:L0,prepare_inputs:mn},[I.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:mn},[I.Phi3V]:{can_generate:!0,prepare_inputs:mn},[I.MultiModality]:{can_generate:!0},[I.AutoEncoder]:{can_generate:!1,forward:F0},[I.Chatterbox]:{can_generate:!0,forward:Wt},[I.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Ss},default:{can_generate:!1,forward:Wt}};function H_(e,t){let s=Ft.get(e),r=!1;const n=t?.architectures?.[0];if(n&&n!==e&&e?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){const i=Ft.get(n);i!==void 0&&(s=i,r=!0)}const a=W_[s]??W_.default,o=Pt[s]??Pt.default;return{typeConfig:{...a,...o},textOnly:r,modelType:s}}var Ft=new Map,To=new Map,Cs=new Map,b=class extends Ue{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,s){super(),this.config=e,this.sessions=t,this.configs=s;const r=Cs.get(this.constructor),{typeConfig:n}=H_(r,e);this.can_generate=n.can_generate,this._forward=n.forward,this._prepare_inputs_for_generation=n.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:u={}}={}){const _={progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:u},h=Cs.get(this);s=_.config=await _r.from_pretrained(e,_);const{typeConfig:p,textOnly:f,modelType:g}=H_(h,s);if(g===void 0){const v=h??s?.model_type;v!=="custom"&&Q.warn(`Model type for '${v}' not found, assuming encoder-only architecture. Please report this at ${an}.`)}if(t&&!(t instanceof $r)){const v={};try{const M=await j_(e,{config:s,dtype:c,device:l,model_file_name:o});(await Promise.all(M.map(A=>or(e,A,_)))).forEach((A,S)=>{if(A.exists){const C=M[S]==="config.json";v[M[S]]={loaded:C?A.size??0:0,total:A.size??0}}})}catch(M){Q.warn(`Unable to fetch model file metadata for total progress tracking: ${M}`)}Object.keys(v).length>0&&(_.progress_callback=new $r(t,v))}const m=p.sessions(s,_,f),w=[n0(e,m,_,p.cache_sessions)];p.optional_configs&&w.push(z0(e,p.optional_configs,_));const y=await Promise.all(w);return new this(s,...y)}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,s=null){const r=new xo;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new f0(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new p0(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new w0(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new m0(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new g0(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new d0(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new u0(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new _0(e.suppress_tokens)),e.begin_suppress_tokens!==null){const n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new R_(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new v0(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Q.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new y0(e.temperature)),s!==null&&r.extend(s),r}_prepare_generation_config(e,t,s=$_){const r={...this.config};for(const a of["decoder","generator","text_config"])a in r&&Object.assign(r,r[a]);const n=new s(r);return Object.assign(n,this.generation_config??{}),e&&Object.assign(n,e),t&&Object.assign(n,Ie(t,Object.getOwnPropertyNames(n))),n}_get_stopping_criteria(e,t=null){const s=new G_;return e.max_length!==null&&s.push(new M0(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new b0(e.eos_token_id)),t&&s.extend(t),s}_validate_model_class(){if(!this.can_generate){const e=[As.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,As.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,As.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,As.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Cs.get(this.constructor),s=new Set,r=this.config.model_type;for(const a of e){const o=a?.get(r);o&&s.add(o)}let n=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(n+=` Please use the following class instead: ${[...s].join(", ")}`),Error(n)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:s,is_encoder_decoder:r}){return s.past_key_values=Ao(t,s.past_key_values),s.input_ids=new P("int64",e.flat(),[e.length,1]),r?"decoder_attention_mask"in s&&(s.decoder_attention_mask=fe([s.decoder_attention_mask,qe([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=fe([s.attention_mask,qe([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:s}){const r=Ie(s,this.forward_params),n=this.main_input_name;if(n in r){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[n]=e;return{inputs_tensor:r[n],model_inputs:r,model_input_name:n}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:s,generation_config:r}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:a,pixel_values:o,attention_mask:i,...l}=t,c=await this._prepare_inputs_embeds(t);t={...l,...Ie(c,["inputs_embeds","attention_mask"])}}let{last_hidden_state:n}=await Wt(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)n=fe([n,to(n,0)],0),"attention_mask"in t&&(t.attention_mask=fe([t.attention_mask,ro(t.attention_mask)],0));else if(t.decoder_input_ids){const a=Eo(t.decoder_input_ids).dims[0];if(a!==n.dims[0]){if(n.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${n.dims[0]}) than the decoder inputs (${a}).`);n=fe(Array.from({length:a},()=>n),0)}}return t.encoder_outputs=n,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:s,decoder_start_token_id:r,bos_token_id:n,generation_config:a}){let{decoder_input_ids:o,...i}=s;if(!(o instanceof P)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=n,this.config.model_type==="musicgen")o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expected to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=Eo(o)}return i.decoder_attention_mask=so(o),{input_ids:o,model_inputs:i}}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,streamer:n=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const c=this.config.is_encoder_decoder;c&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:i,model_input_name:l,generation_config:t})));let d;c?{input_ids:d,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[l].dims.at(0),model_input_name:l,model_kwargs:i,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):d=i[l];let u=d.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=u+t.max_new_tokens);const _=this._get_logits_processor(t,u,s),h=this._get_stopping_criteria(t,r),p=i[l].dims.at(0),f=hn.getSampler(t),g=new Array(p).fill(0),m=d.tolist();n&&n.put(m);let w,y={},v={};for(;;){if(i=this.prepare_inputs_for_generation(m,i,t),w=await this.forward(i),t.return_dict_in_generate)if(t.output_attentions){const O=I0(w);for(const $ in O)$ in y||(y[$]=[]),y[$].push(O[$])}else this._return_dict_in_generate_keys&&Object.assign(v,Ie(w,this._return_dict_in_generate_keys));const C=w.logits.slice(null,-1,null).to("float32"),z=_(m,C),R=[];for(let O=0;O<z.dims.at(0);++O){const $=z[O],L=await f($);for(const[D,se]of L){const U=BigInt(D);g[O]+=se,m[O].push(U),R.push([U]);break}}if(n&&n.put(R),h(m).every(O=>O))break;i=this._update_model_kwargs_for_generation({generated_input_ids:R,outputs:w,model_inputs:i,is_encoder_decoder:c})}n&&n.end();const M=new P("int64",m.flat(),[m.length,m[0].length]),E=Ao(w,i.past_key_values),A=new Set(Object.values(E));for(const C of Object.values(w))C.location==="gpu-buffer"&&!A.has(C)&&C.dispose();return"past_key_values"in a||t.return_dict_in_generate||await E.dispose(),t.return_dict_in_generate?{sequences:M,past_key_values:E,...y,...v}:M}async _encode_input(e,t,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);const r=this.sessions[e];return(await te(r,Ie(t,r.inputNames)))[s]}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 pn(e,t){let{encoder_outputs:s,input_ids:r,decoder_input_ids:n,decoder_attention_mask:a,...o}=t;if(!s){const i=Ie(t,e.sessions.model.inputNames);s=(await Wt(e,i)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=s,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await It(e,o,!0)}async function Wt(e,t){const s=e.sessions.model,r=Ie(t,s.inputNames);if(s.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(s.inputNames.includes("token_type_ids")&&!r.token_type_ids){if(!r.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=ro(r.input_ids)}if(s.inputNames.includes("pixel_mask")&&!r.pixel_mask){if(!r.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const n=r.pixel_values.dims;r.pixel_mask=qe([n[0],n[2],n[3]])}return await te(s,r)}async function F0(e,t){const s=await e.encode(t);return await e.decode(s)}function Ao(e,t){const s=Object.create(null);for(const r in e)if(r.startsWith("present")){const n=r.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");r.includes("encoder")&&t?s[n]=t[n]:s[n]=e[r]}return t?(t.update(s),t):new ko(s)}function I0(e){const t={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const r in e)r.startsWith(s)&&(s in t||(t[s]=[]),t[s].push(e[r]));return t}function Q_(e,t){return e.map(s=>typeof s=="number"?s:t[s]??0)}function Co(e,t,s){if(s&&Object.keys(s).length>0)return Object.assign(t,s),s;const r=e.sessions.decoder_model_merged??e.sessions.model,n=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=_n(e.config),o=e.config?.normalized_config?.num_heads,i={batch_size:n};typeof o=="number"&&(i["batch_size x num_heads"]=n*o);const l=Object.create(null);for(const c of r.inputMetadata){if(!a.has(c.name))continue;const d=Q_(c.shape,i),u=d.reduce((p,f)=>p*f,1),_=cr[c.type],h=new P(c.type,new _(u),d);t[c.name]=h,l[c.name]=h}return s?(s.update(l),s):new ko(l)}function pr(e,t,s){if(t.num_logits_to_keep)return;(e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep")&&(t.num_logits_to_keep=new P("int64",[s],[]))}async function It(e,t,s=!1){const r=e.sessions[s?"decoder_model_merged":"model"],{past_key_values:n,...a}=t;if(r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=q_(n!=null&&Object.keys(n).length>0)),r.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=N0(a,n,i)}pr(e,a,0n),Co(e,a,n);const o=Ie(a,r.inputNames);return await te(r,o)}async function X_(e,{encode_function:t,merge_function:s,modality_input_names:r,modality_output_name:n,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:u=null,num_logits_to_keep:_=null,...h}){if(!l){l=await e.encode_text({input_ids:a,...h});const f=Ie(h,r);if(Object.keys(f).length>0){if(a.dims[1]!==1){const g=await t({...f,...h});({inputs_embeds:l,attention_mask:o}=s({[n]:g,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){const g=a.dims[1],m=c.get_seq_length();o=fe([qe([a.dims[0],m]),o.slice(null,[o.dims[1]-g,o.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){const{image_grid_thw:f,video_grid_thw:g}=h;[i]=e.get_rope_index(a,f,g,o)}return await It(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:u,num_logits_to_keep:_},!0)}async function L0(e,t){return await X_(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 O0(e,t){return await X_(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 Y_(e,t=0){const[s,r]=e.dims,n=e.data,a=new BigInt64Array(n.length);for(let o=0;o<s;++o){const i=o*r;let l=BigInt(t);for(let c=0;c<r;++c){const d=i+c;n[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=n[d])}}return{data:a,dims:e.dims}}function N0(e,t=null,s=0){const{input_ids:r,inputs_embeds:n,attention_mask:a}=e,{data:o,dims:i}=Y_(a,s);let l=new P("int64",o,i);if(t){const c=-(r??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Ss(e,t,s,r){const n=s.past_key_values?s.past_key_values.get_seq_length():0;if(pr(e,s,1n),!s.attention_mask){let a;for(const o of["input_ids","inputs_embeds","position_ids"])if(s[o]){a=s[o].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");s.attention_mask=qe([a[0],n+a[1]])}if(s.past_key_values){const{input_ids:a,attention_mask:o}=s;o&&o.dims[1]>a.dims[1]||n<a.dims[1]&&(s.input_ids=a.slice(null,[n,null]))}return s}function fn(e,t,s,r){return s.past_key_values&&(t=t.map(n=>[n.at(-1)])),pr(e,s,1n),{...s,decoder_input_ids:Eo(t)}}function mn(e,...t){return e.config.is_encoder_decoder?fn(e,...t):Ss(e,...t)}function K_({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:r,attention_mask:n}){const a=r.tolist().map(c=>c.reduce((d,u,_)=>(u==e&&d.push(_),d),[])),o=a.reduce((c,d)=>c+d.length,0),i=s.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){const d=a[c],u=t[c];for(let _=0;_<d.length;++_)u[d[_]].data.set(s[l++].data)}return{inputs_embeds:t,attention_mask:n}}function So({image_token_id:e,inputs_embeds:t,image_features:s,input_ids:r,attention_mask:n}){return K_({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:r,attention_mask:n})}function J_({audio_token_id:e,inputs_embeds:t,audio_features:s,input_ids:r,attention_mask:n}){return K_({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:r,attention_mask:n})}async function z0(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map(async r=>{const n=await Mt(e,t[r],!1,s);return[r,n]})))}var Po={};sr(Po,{ASTForAudioClassification:()=>Q0,ASTModel:()=>H0,ASTPreTrainedModel:()=>Oo,AfmoeForCausalLM:()=>j0,AfmoeModel:()=>U0,AfmoePreTrainedModel:()=>Io,AlbertForMaskedLM:()=>$0,AlbertForQuestionAnswering:()=>R0,AlbertForSequenceClassification:()=>B0,AlbertModel:()=>D0,AlbertPreTrainedModel:()=>fr,ApertusForCausalLM:()=>V0,ApertusModel:()=>G0,ApertusPreTrainedModel:()=>Fo,ArceeForCausalLM:()=>W0,ArceeModel:()=>q0,ArceePreTrainedModel:()=>Lo,BartForConditionalGeneration:()=>Y0,BartForSequenceClassification:()=>K0,BartModel:()=>X0,BartPretrainedModel:()=>gn,BaseModelOutput:()=>o0,BeitForImageClassification:()=>Z0,BeitModel:()=>J0,BeitPreTrainedModel:()=>No,BertForMaskedLM:()=>t1,BertForQuestionAnswering:()=>n1,BertForSequenceClassification:()=>s1,BertForTokenClassification:()=>r1,BertModel:()=>e1,BertPreTrainedModel:()=>Ps,BlenderbotForConditionalGeneration:()=>o1,BlenderbotModel:()=>a1,BlenderbotPreTrainedModel:()=>zo,BlenderbotSmallForConditionalGeneration:()=>l1,BlenderbotSmallModel:()=>i1,BlenderbotSmallPreTrainedModel:()=>Do,BloomForCausalLM:()=>d1,BloomModel:()=>c1,BloomPreTrainedModel:()=>Bo,CHMv2ForDepthEstimation:()=>w1,CHMv2PreTrainedModel:()=>rh,CLIPModel:()=>y1,CLIPPreTrainedModel:()=>ls,CLIPSegForImageSegmentation:()=>E1,CLIPSegModel:()=>k1,CLIPSegPreTrainedModel:()=>Ro,CLIPTextModel:()=>M1,CLIPTextModelWithProjection:()=>oh,CLIPVisionModel:()=>b1,CLIPVisionModelWithProjection:()=>x1,CamembertForMaskedLM:()=>_1,CamembertForQuestionAnswering:()=>f1,CamembertForSequenceClassification:()=>h1,CamembertForTokenClassification:()=>p1,CamembertModel:()=>u1,CamembertPreTrainedModel:()=>Fs,CausalLMOutput:()=>qt,CausalLMOutputWithPast:()=>i0,ChatterboxModel:()=>th,ChatterboxPreTrainedModel:()=>eh,ChineseCLIPModel:()=>g1,ChineseCLIPPreTrainedModel:()=>sh,ClapAudioModelWithProjection:()=>ah,ClapModel:()=>v1,ClapPreTrainedModel:()=>wn,ClapTextModelWithProjection:()=>nh,CodeGenForCausalLM:()=>A1,CodeGenModel:()=>T1,CodeGenPreTrainedModel:()=>$o,Cohere2ForCausalLM:()=>F1,Cohere2Model:()=>P1,Cohere2PreTrainedModel:()=>Vo,CohereAsrForConditionalGeneration:()=>L1,CohereAsrModel:()=>I1,CohereAsrPreTrainedModel:()=>Uo,CohereForCausalLM:()=>S1,CohereModel:()=>C1,CoherePreTrainedModel:()=>Go,ConvBertForMaskedLM:()=>N1,ConvBertForQuestionAnswering:()=>B1,ConvBertForSequenceClassification:()=>z1,ConvBertForTokenClassification:()=>D1,ConvBertModel:()=>O1,ConvBertPreTrainedModel:()=>Is,ConvNextForImageClassification:()=>$1,ConvNextModel:()=>R1,ConvNextPreTrainedModel:()=>jo,ConvNextV2ForImageClassification:()=>V1,ConvNextV2Model:()=>G1,ConvNextV2PreTrainedModel:()=>qo,DFineForObjectDetection:()=>W1,DFineModel:()=>q1,DFinePreTrainedModel:()=>Ho,DINOv3ConvNextModel:()=>yk,DINOv3ConvNextPreTrainedModel:()=>fh,DINOv3ViTModel:()=>Mk,DINOv3ViTPreTrainedModel:()=>mh,DPTForDepthEstimation:()=>Sk,DPTModel:()=>Ck,DPTPreTrainedModel:()=>ei,DacDecoderModel:()=>dh,DacDecoderOutput:()=>lh,DacEncoderModel:()=>ch,DacEncoderOutput:()=>ih,DacModel:()=>H1,DacPreTrainedModel:()=>vn,DebertaForMaskedLM:()=>X1,DebertaForQuestionAnswering:()=>J1,DebertaForSequenceClassification:()=>Y1,DebertaForTokenClassification:()=>K1,DebertaModel:()=>Q1,DebertaPreTrainedModel:()=>Ls,DebertaV2ForMaskedLM:()=>nk,DebertaV2ForQuestionAnswering:()=>ik,DebertaV2ForSequenceClassification:()=>ak,DebertaV2ForTokenClassification:()=>ok,DebertaV2Model:()=>rk,DebertaV2PreTrainedModel:()=>Os,DecisionTransformerModel:()=>lk,DecisionTransformerPreTrainedModel:()=>uh,DeepseekV3ForCausalLM:()=>ek,DeepseekV3Model:()=>Z1,DeepseekV3PreTrainedModel:()=>Qo,DeepseekV4ForCausalLM:()=>sk,DeepseekV4Model:()=>tk,DeepseekV4PreTrainedModel:()=>Xo,DeiTForImageClassification:()=>dk,DeiTModel:()=>ck,DeiTPreTrainedModel:()=>Yo,DepthAnythingForDepthEstimation:()=>uk,DepthAnythingPreTrainedModel:()=>_h,DepthProForDepthEstimation:()=>_k,DepthProPreTrainedModel:()=>hh,DetrForObjectDetection:()=>pk,DetrForSegmentation:()=>fk,DetrModel:()=>hk,DetrObjectDetectionOutput:()=>Ko,DetrPreTrainedModel:()=>yn,DetrSegmentationOutput:()=>ph,Dinov2ForImageClassification:()=>gk,Dinov2Model:()=>mk,Dinov2PreTrainedModel:()=>Jo,Dinov2WithRegistersForImageClassification:()=>vk,Dinov2WithRegistersModel:()=>wk,Dinov2WithRegistersPreTrainedModel:()=>Zo,DistilBertForMaskedLM:()=>Tk,DistilBertForQuestionAnswering:()=>Ek,DistilBertForSequenceClassification:()=>xk,DistilBertForTokenClassification:()=>kk,DistilBertModel:()=>bk,DistilBertPreTrainedModel:()=>Ns,DonutSwinModel:()=>Ak,DonutSwinPreTrainedModel:()=>gh,EdgeTamModel:()=>HC,EfficientNetForImageClassification:()=>Fk,EfficientNetModel:()=>Pk,EfficientNetPreTrainedModel:()=>ti,ElectraForMaskedLM:()=>Lk,ElectraForQuestionAnswering:()=>zk,ElectraForSequenceClassification:()=>Ok,ElectraForTokenClassification:()=>Nk,ElectraModel:()=>Ik,ElectraPreTrainedModel:()=>zs,EmbeddingGemma2Model:()=>vh,EmbeddingGemma2PreTrainedModel:()=>wh,Ernie4_5ForCausalLM:()=>Bk,Ernie4_5Model:()=>Dk,Ernie4_5PretrainedModel:()=>si,EsmForMaskedLM:()=>$k,EsmForSequenceClassification:()=>Gk,EsmForTokenClassification:()=>Vk,EsmModel:()=>Rk,EsmPreTrainedModel:()=>gr,EuroBertForMaskedLM:()=>jk,EuroBertForSequenceClassification:()=>qk,EuroBertForTokenClassification:()=>Wk,EuroBertModel:()=>Uk,EuroBertPreTrainedModel:()=>wr,ExaoneForCausalLM:()=>Qk,ExaoneModel:()=>Hk,ExaonePreTrainedModel:()=>ri,FalconForCausalLM:()=>Yk,FalconH1ForCausalLM:()=>Jk,FalconH1Model:()=>Kk,FalconH1PreTrainedModel:()=>ai,FalconModel:()=>Xk,FalconPreTrainedModel:()=>ni,FastViTForImageClassification:()=>eE,FastViTModel:()=>Zk,FastViTPreTrainedModel:()=>oi,Florence2ForConditionalGeneration:()=>tE,Florence2PreTrainedModel:()=>yh,GLPNForDepthEstimation:()=>wE,GLPNModel:()=>gE,GLPNPreTrainedModel:()=>pi,GPT2LMHeadModel:()=>CE,GPT2Model:()=>AE,GPT2PreTrainedModel:()=>vi,GPTBigCodeForCausalLM:()=>yE,GPTBigCodeModel:()=>vE,GPTBigCodePreTrainedModel:()=>fi,GPTJForCausalLM:()=>PE,GPTJModel:()=>SE,GPTJPreTrainedModel:()=>yi,GPTNeoForCausalLM:()=>bE,GPTNeoModel:()=>ME,GPTNeoPreTrainedModel:()=>mi,GPTNeoXForCausalLM:()=>kE,GPTNeoXModel:()=>xE,GPTNeoXPreTrainedModel:()=>gi,Gemma2ForCausalLM:()=>aE,Gemma2Model:()=>nE,Gemma2PreTrainedModel:()=>li,Gemma3ForCausalLM:()=>cE,Gemma3ForConditionalGeneration:()=>xh,Gemma3Model:()=>lE,Gemma3PreTrainedModel:()=>bh,Gemma3nForCausalLM:()=>dE,Gemma3nForConditionalGeneration:()=>Mn,Gemma3nPreTrainedModel:()=>kh,Gemma4ForCausalLM:()=>uE,Gemma4ForConditionalGeneration:()=>ci,GemmaForCausalLM:()=>rE,GemmaModel:()=>sE,GemmaPreTrainedModel:()=>ii,GlmForCausalLM:()=>hE,GlmModel:()=>_E,GlmMoeDsaForCausalLM:()=>fE,GlmMoeDsaModel:()=>pE,GlmMoeDsaPreTrainedModel:()=>ui,GlmOcrForConditionalGeneration:()=>mE,GlmPreTrainedModel:()=>di,GptOssForCausalLM:()=>TE,GptOssModel:()=>EE,GptOssPreTrainedModel:()=>wi,GraniteForCausalLM:()=>IE,GraniteModel:()=>FE,GraniteMoeHybridForCausalLM:()=>OE,GraniteMoeHybridModel:()=>LE,GraniteMoeHybridPreTrainedModel:()=>bi,GranitePreTrainedModel:()=>Mi,GraniteSpeechForConditionalGeneration:()=>NE,GroundingDinoForObjectDetection:()=>zE,GroundingDinoPreTrainedModel:()=>Sh,GroupViTModel:()=>DE,GroupViTPreTrainedModel:()=>Ph,HeliumForCausalLM:()=>RE,HeliumModel:()=>BE,HeliumPreTrainedModel:()=>ki,HieraForImageClassification:()=>GE,HieraModel:()=>$E,HieraPreTrainedModel:()=>Ei,HrmTextForCausalLM:()=>UE,HrmTextModel:()=>VE,HrmTextPreTrainedModel:()=>Ti,HubertForCTC:()=>YE,HubertForSequenceClassification:()=>KE,HubertModel:()=>XE,HubertPreTrainedModel:()=>QE,HunYuanDenseV1ForCausalLM:()=>ZE,HunYuanDenseV1Model:()=>JE,HunYuanDenseV1PreTrainedModel:()=>Ai,IJepaForImageClassification:()=>tT,IJepaModel:()=>eT,IJepaPreTrainedModel:()=>Ci,Idefics3ForConditionalGeneration:()=>Fh,ImageMattingOutput:()=>B_,JAISLMHeadModel:()=>rT,JAISModel:()=>sT,JAISPreTrainedModel:()=>Si,JinaCLIPModel:()=>nT,JinaCLIPPreTrainedModel:()=>bn,JinaCLIPTextModel:()=>Ih,JinaCLIPVisionModel:()=>aT,Lfm2ForCausalLM:()=>iT,Lfm2Model:()=>oT,Lfm2MoeForCausalLM:()=>dT,Lfm2MoeModel:()=>cT,Lfm2MoePreTrainedModel:()=>Fi,Lfm2PreTrainedModel:()=>Pi,Lfm2VlForConditionalGeneration:()=>uT,LightOnOcrForConditionalGeneration:()=>lT,LiteWhisperForConditionalGeneration:()=>pP,Llama4ForCausalLM:()=>pT,Llama4PreTrainedModel:()=>Lh,LlamaForCausalLM:()=>hT,LlamaModel:()=>_T,LlamaPreTrainedModel:()=>Ii,LlavaForConditionalGeneration:()=>Et,LlavaOnevisionForConditionalGeneration:()=>Et,LlavaPreTrainedModel:()=>Mh,LlavaQwen2ForCausalLM:()=>iE,LongT5ForConditionalGeneration:()=>mT,LongT5Model:()=>fT,LongT5PreTrainedModel:()=>Li,M2M100ForConditionalGeneration:()=>wT,M2M100Model:()=>gT,M2M100PreTrainedModel:()=>Oi,MBartForCausalLM:()=>TT,MBartForConditionalGeneration:()=>kT,MBartForSequenceClassification:()=>ET,MBartModel:()=>xT,MBartPreTrainedModel:()=>vr,MPNetForMaskedLM:()=>gA,MPNetForQuestionAnswering:()=>yA,MPNetForSequenceClassification:()=>wA,MPNetForTokenClassification:()=>vA,MPNetModel:()=>mA,MPNetPreTrainedModel:()=>Ds,MT5ForConditionalGeneration:()=>kA,MT5Model:()=>xA,MT5PreTrainedModel:()=>Hi,MarianMTModel:()=>yT,MarianModel:()=>vT,MarianPreTrainedModel:()=>Ni,MaskFormerForInstanceSegmentation:()=>bT,MaskFormerModel:()=>MT,MaskFormerPreTrainedModel:()=>zi,MaskedLMOutput:()=>Ae,Metric3DForDepthEstimation:()=>AT,Metric3DPreTrainedModel:()=>Oh,Metric3Dv2ForDepthEstimation:()=>CT,Metric3Dv2PreTrainedModel:()=>Nh,MgpstrForSceneTextRecognition:()=>ST,MgpstrModelOutput:()=>zh,MgpstrPreTrainedModel:()=>Dh,MimiDecoderModel:()=>Gh,MimiDecoderOutput:()=>Rh,MimiEncoderModel:()=>$h,MimiEncoderOutput:()=>Bh,MimiModel:()=>PT,MimiPreTrainedModel:()=>xn,Ministral3ForCausalLM:()=>OT,Ministral3Model:()=>LT,Ministral3PreTrainedModel:()=>Bi,MinistralForCausalLM:()=>IT,MinistralModel:()=>FT,MinistralPreTrainedModel:()=>Di,Mistral3ForConditionalGeneration:()=>DT,Mistral4ForCausalLM:()=>RT,Mistral4Model:()=>BT,Mistral4PreTrainedModel:()=>$i,MistralForCausalLM:()=>zT,MistralModel:()=>NT,MistralPreTrainedModel:()=>Ri,MobileBertForMaskedLM:()=>GT,MobileBertForQuestionAnswering:()=>UT,MobileBertForSequenceClassification:()=>VT,MobileBertModel:()=>$T,MobileBertPreTrainedModel:()=>yr,MobileLLMForCausalLM:()=>qT,MobileLLMModel:()=>jT,MobileLLMPreTrainedModel:()=>Gi,MobileNetV1ForImageClassification:()=>HT,MobileNetV1ForSemanticSegmentation:()=>QT,MobileNetV1Model:()=>WT,MobileNetV1PreTrainedModel:()=>kn,MobileNetV2ForImageClassification:()=>YT,MobileNetV2ForSemanticSegmentation:()=>KT,MobileNetV2Model:()=>XT,MobileNetV2PreTrainedModel:()=>En,MobileNetV3ForImageClassification:()=>ZT,MobileNetV3ForSemanticSegmentation:()=>eA,MobileNetV3Model:()=>JT,MobileNetV3PreTrainedModel:()=>Tn,MobileNetV4ForImageClassification:()=>sA,MobileNetV4ForSemanticSegmentation:()=>rA,MobileNetV4Model:()=>tA,MobileNetV4PreTrainedModel:()=>An,MobileViTForImageClassification:()=>aA,MobileViTModel:()=>nA,MobileViTPreTrainedModel:()=>Vi,MobileViTV2ForImageClassification:()=>iA,MobileViTV2Model:()=>oA,MobileViTV2PreTrainedModel:()=>Ui,ModelOutput:()=>Me,ModernBertDecoderForCausalLM:()=>hA,ModernBertDecoderModel:()=>_A,ModernBertDecoderPreTrainedModel:()=>ji,ModernBertForMaskedLM:()=>cA,ModernBertForSequenceClassification:()=>dA,ModernBertForTokenClassification:()=>uA,ModernBertModel:()=>lA,ModernBertPreTrainedModel:()=>Mr,Moondream1ForConditionalGeneration:()=>oE,MoonshineForConditionalGeneration:()=>fA,MoonshineModel:()=>pA,MoonshinePreTrainedModel:()=>qi,MptForCausalLM:()=>bA,MptModel:()=>MA,MptPreTrainedModel:()=>Wi,MultiModalityCausalLM:()=>EA,MultiModalityPreTrainedModel:()=>Vh,MusicgenForCausalLM:()=>AA,MusicgenForConditionalGeneration:()=>Uh,MusicgenModel:()=>TA,MusicgenPreTrainedModel:()=>Qi,NanoChatForCausalLM:()=>SA,NanoChatModel:()=>CA,NanoChatPreTrainedModel:()=>Xi,NemotronHForCausalLM:()=>FA,NemotronHModel:()=>PA,NemotronHPreTrainedModel:()=>Yi,NeoBertForMaskedLM:()=>LA,NeoBertForQuestionAnswering:()=>zA,NeoBertForSequenceClassification:()=>OA,NeoBertForTokenClassification:()=>NA,NeoBertModel:()=>IA,NeoBertPreTrainedModel:()=>Bs,NomicBertModel:()=>DA,NomicBertPreTrainedModel:()=>jh,OPTForCausalLM:()=>KA,OPTModel:()=>YA,OPTPreTrainedModel:()=>rl,Olmo2ForCausalLM:()=>GA,Olmo2Model:()=>$A,Olmo2PreTrainedModel:()=>Ji,Olmo3ForCausalLM:()=>UA,Olmo3Model:()=>VA,Olmo3PreTrainedModel:()=>Zi,OlmoForCausalLM:()=>RA,OlmoHybridForCausalLM:()=>qA,OlmoHybridModel:()=>jA,OlmoHybridPreTrainedModel:()=>el,OlmoModel:()=>BA,OlmoPreTrainedModel:()=>Ki,OpenAIPrivacyFilterForTokenClassification:()=>HA,OpenAIPrivacyFilterModel:()=>WA,OpenAIPrivacyFilterPreTrainedModel:()=>tl,OpenELMForCausalLM:()=>XA,OpenELMModel:()=>QA,OpenELMPreTrainedModel:()=>sl,OwlViTForObjectDetection:()=>tC,OwlViTModel:()=>eC,OwlViTPreTrainedModel:()=>al,Owlv2ForObjectDetection:()=>ZA,Owlv2Model:()=>JA,Owlv2PreTrainedModel:()=>nl,PaliGemmaForConditionalGeneration:()=>sC,ParakeetForCTC:()=>rC,ParakeetPreTrainedModel:()=>qh,PatchTSMixerForPrediction:()=>aC,PatchTSMixerModel:()=>nC,PatchTSMixerPreTrainedModel:()=>ol,PatchTSTForPrediction:()=>iC,PatchTSTModel:()=>oC,PatchTSTPreTrainedModel:()=>il,Phi3ForCausalLM:()=>uC,Phi3Model:()=>dC,Phi3PreTrainedModel:()=>cl,Phi3VForCausalLM:()=>Hh,Phi3VPreTrainedModel:()=>Wh,PhiForCausalLM:()=>cC,PhiModel:()=>lC,PhiPreTrainedModel:()=>ll,PreTrainedModel:()=>b,PvtForImageClassification:()=>hC,PvtModel:()=>_C,PvtPreTrainedModel:()=>dl,PyAnnoteForAudioFrameClassification:()=>fC,PyAnnoteModel:()=>pC,PyAnnotePreTrainedModel:()=>ul,QuestionAnsweringModelOutput:()=>De,Qwen2ForCausalLM:()=>gC,Qwen2Model:()=>mC,Qwen2MoeForCausalLM:()=>vC,Qwen2MoeModel:()=>wC,Qwen2MoePreTrainedModel:()=>hl,Qwen2PreTrainedModel:()=>_l,Qwen2VLForCausalLM:()=>Th,Qwen2VLForConditionalGeneration:()=>_i,Qwen2VLPreTrainedModel:()=>Eh,Qwen2_5_VLForCausalLM:()=>Ah,Qwen2_5_VLForConditionalGeneration:()=>hi,Qwen3ForCausalLM:()=>MC,Qwen3Model:()=>yC,Qwen3MoeForCausalLM:()=>xC,Qwen3MoeModel:()=>bC,Qwen3MoePreTrainedModel:()=>fl,Qwen3NextForCausalLM:()=>EC,Qwen3NextModel:()=>kC,Qwen3NextPreTrainedModel:()=>ml,Qwen3PreTrainedModel:()=>pl,Qwen3VLForCausalLM:()=>Qh,Qwen3VLForConditionalGeneration:()=>gl,Qwen3VLMoeForCausalLM:()=>AC,Qwen3VLMoeForConditionalGeneration:()=>TC,Qwen3_5ForCausalLM:()=>Xh,Qwen3_5ForConditionalGeneration:()=>wl,Qwen3_5MoeForCausalLM:()=>SC,Qwen3_5MoeForConditionalGeneration:()=>CC,RFDetrForObjectDetection:()=>LC,RFDetrModel:()=>IC,RFDetrObjectDetectionOutput:()=>Yh,RFDetrPreTrainedModel:()=>yl,RTDetrForObjectDetection:()=>j1,RTDetrModel:()=>U1,RTDetrObjectDetectionOutput:()=>mr,RTDetrPreTrainedModel:()=>Wo,RTDetrV2ForObjectDetection:()=>qC,RTDetrV2Model:()=>jC,RTDetrV2ObjectDetectionOutput:()=>Kh,RTDetrV2PreTrainedModel:()=>Ml,ResNetForImageClassification:()=>FC,ResNetModel:()=>PC,ResNetPreTrainedModel:()=>vl,RoFormerForMaskedLM:()=>$C,RoFormerForQuestionAnswering:()=>UC,RoFormerForSequenceClassification:()=>GC,RoFormerForTokenClassification:()=>VC,RoFormerModel:()=>RC,RoFormerPreTrainedModel:()=>$s,RobertaForMaskedLM:()=>NC,RobertaForQuestionAnswering:()=>BC,RobertaForSequenceClassification:()=>zC,RobertaForTokenClassification:()=>DC,RobertaModel:()=>OC,RobertaPreTrainedModel:()=>Rs,Sam2ImageSegmentationOutput:()=>ep,Sam2Model:()=>bl,Sam2PreTrainedModel:()=>tp,Sam3TrackerModel:()=>QC,SamImageSegmentationOutput:()=>Jh,SamModel:()=>WC,SamPreTrainedModel:()=>Zh,SapiensForDepthEstimation:()=>YC,SapiensForNormalEstimation:()=>KC,SapiensForSemanticSegmentation:()=>XC,SapiensPreTrainedModel:()=>Cn,SegformerForImageClassification:()=>ZC,SegformerForSemanticSegmentation:()=>eS,SegformerModel:()=>JC,SegformerPreTrainedModel:()=>Sn,Seq2SeqLMOutput:()=>l0,SequenceClassifierOutput:()=>V,SiglipModel:()=>tS,SiglipPreTrainedModel:()=>xl,SiglipTextModel:()=>sp,SiglipVisionModel:()=>sS,SmolLM3ForCausalLM:()=>nS,SmolLM3Model:()=>rS,SmolLM3PreTrainedModel:()=>kl,SmolVLMForConditionalGeneration:()=>aS,SnacDecoderModel:()=>np,SnacEncoderModel:()=>rp,SnacModel:()=>oS,SnacPreTrainedModel:()=>Pn,SolarOpenForCausalLM:()=>lS,SolarOpenModel:()=>iS,SolarOpenPreTrainedModel:()=>El,SpeechT5ForSpeechToText:()=>dS,SpeechT5ForTextToSpeech:()=>uS,SpeechT5HifiGan:()=>_S,SpeechT5Model:()=>cS,SpeechT5PreTrainedModel:()=>Fn,SqueezeBertForMaskedLM:()=>pS,SqueezeBertForQuestionAnswering:()=>mS,SqueezeBertForSequenceClassification:()=>fS,SqueezeBertModel:()=>hS,SqueezeBertPreTrainedModel:()=>br,StableLmForCausalLM:()=>wS,StableLmModel:()=>gS,StableLmPreTrainedModel:()=>Tl,Starcoder2ForCausalLM:()=>yS,Starcoder2Model:()=>vS,Starcoder2PreTrainedModel:()=>Al,StyleTextToSpeech2Model:()=>MS,StyleTextToSpeech2PreTrainedModel:()=>ap,SupertonicForConditionalGeneration:()=>ip,SupertonicPreTrainedModel:()=>op,Swin2SRForImageSuperResolution:()=>TS,Swin2SRModel:()=>ES,Swin2SRPreTrainedModel:()=>Cl,SwinForImageClassification:()=>xS,SwinForSemanticSegmentation:()=>kS,SwinModel:()=>bS,SwinPreTrainedModel:()=>In,T5ForConditionalGeneration:()=>CS,T5Model:()=>AS,T5PreTrainedModel:()=>Sl,TableTransformerForObjectDetection:()=>PS,TableTransformerModel:()=>SS,TableTransformerObjectDetectionOutput:()=>lp,TableTransformerPreTrainedModel:()=>Pl,TokenClassifierOutput:()=>Ee,TrOCRForCausalLM:()=>FS,TrOCRPreTrainedModel:()=>cp,UltravoxModel:()=>xi,UltravoxPreTrainedModel:()=>Ch,UniSpeechForCTC:()=>LS,UniSpeechForSequenceClassification:()=>OS,UniSpeechModel:()=>IS,UniSpeechPreTrainedModel:()=>Ln,UniSpeechSatForAudioFrameClassification:()=>BS,UniSpeechSatForCTC:()=>zS,UniSpeechSatForSequenceClassification:()=>DS,UniSpeechSatModel:()=>NS,UniSpeechSatPreTrainedModel:()=>xr,VaultGemmaForCausalLM:()=>$S,VaultGemmaModel:()=>RS,VaultGemmaPreTrainedModel:()=>Fl,ViTForImageClassification:()=>US,ViTMAEModel:()=>jS,ViTMAEPreTrainedModel:()=>dp,ViTMSNForImageClassification:()=>WS,ViTMSNModel:()=>qS,ViTMSNPreTrainedModel:()=>Ll,ViTModel:()=>VS,ViTPreTrainedModel:()=>Il,VisionEncoderDecoderModel:()=>GS,VitMatteForImageMatting:()=>HS,VitMattePreTrainedModel:()=>up,VitPoseForPoseEstimation:()=>QS,VitPosePreTrainedModel:()=>_p,VitsModel:()=>XS,VitsModelOutput:()=>hp,VitsPreTrainedModel:()=>pp,VoxtralForConditionalGeneration:()=>YS,VoxtralRealtimeForConditionalGeneration:()=>gp,VoxtralRealtimePreTrainedModel:()=>mp,Wav2Vec2BertForCTC:()=>nP,Wav2Vec2BertForSequenceClassification:()=>aP,Wav2Vec2BertModel:()=>rP,Wav2Vec2BertPreTrainedModel:()=>On,Wav2Vec2ForAudioFrameClassification:()=>HE,Wav2Vec2ForCTC:()=>qE,Wav2Vec2ForSequenceClassification:()=>WE,Wav2Vec2Model:()=>jE,Wav2Vec2PreTrainedModel:()=>Ht,WavLMForAudioFrameClassification:()=>dP,WavLMForCTC:()=>iP,WavLMForSequenceClassification:()=>lP,WavLMForXVector:()=>cP,WavLMModel:()=>oP,WavLMPreTrainedModel:()=>Gs,WeSpeakerResNetModel:()=>uP,WeSpeakerResNetPreTrainedModel:()=>vp,WhisperForConditionalGeneration:()=>yp,WhisperModel:()=>hP,WhisperPreTrainedModel:()=>Nl,XLMForQuestionAnswering:()=>vP,XLMForSequenceClassification:()=>gP,XLMForTokenClassification:()=>wP,XLMModel:()=>fP,XLMPreTrainedModel:()=>Vs,XLMRobertaForMaskedLM:()=>MP,XLMRobertaForQuestionAnswering:()=>kP,XLMRobertaForSequenceClassification:()=>bP,XLMRobertaForTokenClassification:()=>xP,XLMRobertaModel:()=>yP,XLMRobertaPreTrainedModel:()=>Us,XLMWithLMHeadModel:()=>mP,XVectorOutput:()=>wp,YolosForObjectDetection:()=>TP,YolosModel:()=>EP,YolosObjectDetectionOutput:()=>Mp,YolosPreTrainedModel:()=>zl,YoutuForCausalLM:()=>CP,YoutuModel:()=>AP,YoutuPreTrainedModel:()=>Dl,ZayaForCausalLM:()=>PP,ZayaModel:()=>SP,ZayaPreTrainedModel:()=>Bl});var fr=class extends b{},D0=class extends fr{},B0=class extends fr{async _call(e){return new V(await super._call(e))}},R0=class extends fr{async _call(e){return new De(await super._call(e))}},$0=class extends fr{async _call(e){return new Ae(await super._call(e))}},Fo=class extends b{},G0=class extends Fo{},V0=class extends Fo{},Io=class extends b{},U0=class extends Io{},j0=class extends Io{},Lo=class extends b{},q0=class extends Lo{},W0=class extends Lo{},Oo=class extends b{},H0=class extends Oo{},Q0=class extends Oo{},gn=class extends b{},X0=class extends gn{},Y0=class extends gn{},K0=class extends gn{async _call(e){return new V(await super._call(e))}},No=class extends b{},J0=class extends No{},Z0=class extends No{async _call(e){return new V(await super._call(e))}},Ps=class extends b{},e1=class extends Ps{},t1=class extends Ps{async _call(e){return new Ae(await super._call(e))}},s1=class extends Ps{async _call(e){return new V(await super._call(e))}},r1=class extends Ps{async _call(e){return new Ee(await super._call(e))}},n1=class extends Ps{async _call(e){return new De(await super._call(e))}},zo=class extends b{},a1=class extends zo{},o1=class extends zo{},Do=class extends b{},i1=class extends Do{},l1=class extends Do{},Bo=class extends b{},c1=class extends Bo{},d1=class extends Bo{},Fs=class extends b{},u1=class extends Fs{},_1=class extends Fs{async _call(e){return new Ae(await super._call(e))}},h1=class extends Fs{async _call(e){return new V(await super._call(e))}},p1=class extends Fs{async _call(e){return new Ee(await super._call(e))}},f1=class extends Fs{async _call(e){return new De(await super._call(e))}},m1=4299n,Z_=6561n,eh=class extends b{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"]},th=class extends eh{async encode_speech(e){return te(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:s=null,exaggeration:r=null,position_ids:n=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:u=null,speaker_embeddings:_=null,speaker_features:h=null,...p}){let f;if(!a){const m=this.sessions.embed_tokens.inputNames,w={input_ids:e};if(m.includes("exaggeration")){if(!(r instanceof P)){const y=e.dims[0];if(r==null)r=Re([y],.5);else if(typeof r=="number")r=Re([y],r);else if(Array.isArray(r))r=new P("float32",r,[y]);else throw new Error("Unsupported type for `exaggeration` input")}w.exaggeration=r}if(m.includes("position_ids")&&(w.position_ids=n),{inputs_embeds:a}=await te(this.sessions.embed_tokens,w),d&&u&&_&&h&&(f={audio_features:d,audio_tokens:u,speaker_embeddings:_,speaker_features:h}),f||s)f??=await this.encode_speech(s),a=fe([f.audio_features,a],1),t=qe([a.dims[0],a.dims[1]]);else{const y=a.dims[1];if(!o||y!==1)throw new Error("Incorrect state encountered during generation.");const v=o.get_seq_length();t=qe([a.dims[0],v+y])}}return{...await It(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1),...f}}prepare_inputs_for_generation(e,t,s){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const r=Array.from({length:e.length},(n,a)=>e[a].length-e[a].findLastIndex(o=>o==Z_)-1);t.position_ids=new P("int64",r,[e.length,1])}else{const n=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=Z_?0:o++)});t.position_ids=new P("int64",n.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),Ss(this,e,t)}async generate(e){const t=e.past_key_values,{sequences:s,audio_tokens:r,speaker_embeddings:n,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{const i=s.slice(null,[e.input_ids.dims[1],-1]),l=Re([i.dims[0],3],m1),c=fe([r,i,l],1),{waveform:d}=await te(this.sessions.conditional_decoder,{speech_tokens:c,speaker_features:a,speaker_embeddings:n});return d}finally{o!==t&&await o?.dispose()}}},sh=class extends b{},g1=class extends sh{},rh=class extends b{},w1=class extends rh{},wn=class extends b{},v1=class extends wn{},nh=class extends wn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},ah=class extends wn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},ls=class extends b{},y1=class extends ls{},M1=class extends ls{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},oh=class extends ls{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},b1=class extends ls{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},x1=class extends ls{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ro=class extends b{},k1=class extends Ro{},E1=class extends Ro{},$o=class extends b{},T1=class extends $o{},A1=class extends $o{},Go=class extends b{},C1=class extends Go{},S1=class extends Go{},Vo=class extends b{},P1=class extends Vo{},F1=class extends Vo{},Uo=class extends b{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},I1=class extends Uo{},L1=class extends Uo{},Is=class extends b{},O1=class extends Is{},N1=class extends Is{async _call(e){return new Ae(await super._call(e))}},z1=class extends Is{async _call(e){return new V(await super._call(e))}},D1=class extends Is{async _call(e){return new Ee(await super._call(e))}},B1=class extends Is{async _call(e){return new De(await super._call(e))}},jo=class extends b{},R1=class extends jo{},$1=class extends jo{async _call(e){return new V(await super._call(e))}},qo=class extends b{},G1=class extends qo{},V1=class extends qo{async _call(e){return new V(await super._call(e))}},Wo=class extends b{},U1=class extends Wo{},j1=class extends Wo{async _call(e){return new mr(await super._call(e))}},mr=class extends Me{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ho=class extends b{},q1=class extends Ho{},W1=class extends Ho{async _call(e){return new mr(await super._call(e))}},ih=class extends Me{constructor({audio_codes:e}){super(),this.audio_codes=e}},lh=class extends Me{constructor({audio_values:e}){super(),this.audio_values=e}},vn=class extends b{main_input_name="input_values";forward_params=["input_values"]},H1=class extends vn{async encode(e){return new ih(await te(this.sessions.encoder_model,e))}async decode(e){return new lh(await te(this.sessions.decoder_model,e))}},ch=class extends vn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},dh=class extends vn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Ls=class extends b{},Q1=class extends Ls{},X1=class extends Ls{async _call(e){return new Ae(await super._call(e))}},Y1=class extends Ls{async _call(e){return new V(await super._call(e))}},K1=class extends Ls{async _call(e){return new Ee(await super._call(e))}},J1=class extends Ls{async _call(e){return new De(await super._call(e))}},Qo=class extends b{},Z1=class extends Qo{},ek=class extends Qo{},Xo=class extends b{},tk=class extends Xo{},sk=class extends Xo{},Os=class extends b{},rk=class extends Os{},nk=class extends Os{async _call(e){return new Ae(await super._call(e))}},ak=class extends Os{async _call(e){return new V(await super._call(e))}},ok=class extends Os{async _call(e){return new Ee(await super._call(e))}},ik=class extends Os{async _call(e){return new De(await super._call(e))}},uh=class extends b{},lk=class extends uh{},Yo=class extends b{},ck=class extends Yo{},dk=class extends Yo{async _call(e){return new V(await super._call(e))}},_h=class extends b{},uk=class extends _h{},hh=class extends b{},_k=class extends hh{},yn=class extends b{},hk=class extends yn{},pk=class extends yn{async _call(e){return new Ko(await super._call(e))}},fk=class extends yn{async _call(e){return new ph(await super._call(e))}},Ko=class extends Me{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},ph=class extends Me{constructor({logits:e,pred_boxes:t,pred_masks:s}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=s}},Jo=class extends b{},mk=class extends Jo{},gk=class extends Jo{async _call(e){return new V(await super._call(e))}},Zo=class extends b{},wk=class extends Zo{},vk=class extends Zo{async _call(e){return new V(await super._call(e))}},fh=class extends b{},yk=class extends fh{},mh=class extends b{},Mk=class extends mh{},Ns=class extends b{},bk=class extends Ns{},xk=class extends Ns{async _call(e){return new V(await super._call(e))}},kk=class extends Ns{async _call(e){return new Ee(await super._call(e))}},Ek=class extends Ns{async _call(e){return new De(await super._call(e))}},Tk=class extends Ns{async _call(e){return new Ae(await super._call(e))}},gh=class extends b{},Ak=class extends gh{},ei=class extends b{},Ck=class extends ei{},Sk=class extends ei{},ti=class extends b{},Pk=class extends ti{},Fk=class extends ti{async _call(e){return new V(await super._call(e))}},zs=class extends b{},Ik=class extends zs{},Lk=class extends zs{async _call(e){return new Ae(await super._call(e))}},Ok=class extends zs{async _call(e){return new V(await super._call(e))}},Nk=class extends zs{async _call(e){return new Ee(await super._call(e))}},zk=class extends zs{async _call(e){return new De(await super._call(e))}},wh=class extends b{},vh=class extends wh{async forward({input_ids:e,attention_mask:t,pixel_values:s=null,image_position_ids:r=null,pixel_values_videos:n=null,video_position_ids:a=null,input_features:o=null,input_features_mask:i=null}){const l={image_features:s&&await this.encode_image({pixel_values:s,pixel_position_ids:r}),video_features:n&&await this.encode_image({pixel_values:n,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:u,text_config:_}=this.config,h={image:c,video:d,audio:u};for(const[p,f]of Object.entries(h)){const g=`${p}_features`;l[g]??=new P("float32",new Float32Array(0),[0,_.hidden_size]);let m=0;for(const w of e.data)Number(w)===f&&++m;if(m!==l[g].dims[0])throw new Error(`The number of ${p} tokens (${m}) and ${p} features (${l[g].dims[0]}) do not match.`)}return await te(this.sessions.model,{input_ids:e,attention_mask:t,...l})}},si=class extends b{},Dk=class extends si{},Bk=class extends si{},gr=class extends b{},Rk=class extends gr{},$k=class extends gr{async _call(e){return new Ae(await super._call(e))}},Gk=class extends gr{async _call(e){return new V(await super._call(e))}},Vk=class extends gr{async _call(e){return new Ee(await super._call(e))}},wr=class extends b{},Uk=class extends wr{},jk=class extends wr{async _call(e){return new Ae(await super._call(e))}},qk=class extends wr{async _call(e){return new V(await super._call(e))}},Wk=class extends wr{async _call(e){return new Ee(await super._call(e))}},ri=class extends b{},Hk=class extends ri{},Qk=class extends ri{},ni=class extends b{},Xk=class extends ni{},Yk=class extends ni{},ai=class extends b{},Kk=class extends ai{},Jk=class extends ai{},oi=class extends b{},Zk=class extends oi{},eE=class extends oi{async _call(e){return new V(await super._call(e))}},yh=class extends b{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"},tE=class extends yh{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:r}){return{inputs_embeds:fe([t,e],1),attention_mask:fe([qe(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:r}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,a;return e&&(n=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),n&&a?{inputs_embeds:s,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:a,input_ids:e,attention_mask:r}):s=n||a,{inputs_embeds:s,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:s,decoder_input_ids:r,decoder_attention_mask:n,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:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:s})),!a){let{last_hidden_state:u}=await Wt(this,{inputs_embeds:i,attention_mask:s});a=u}if(!l){if(!r)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:r})}return await It(this,{inputs_embeds:l,attention_mask:n,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:c},!0)}},ii=class extends b{},sE=class extends ii{},rE=class extends ii{},li=class extends b{},nE=class extends li{},aE=class extends li{},Mh=class extends b{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Et=class extends Mh{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return So({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},oE=class extends Et{},iE=class extends Et{},bh=class extends b{},lE=class extends bh{},xh=class extends Et{},cE=class extends xh{},kh=class extends b{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},Mn=class extends kh{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,input_features:r=null,input_features_mask:n=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,num_logits_to_keep:u=null,..._}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await te(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){const{image_features:p}=await this._encode_vision({pixel_values:s,..._});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){const{audio_features:p}=await te(this.sessions.audio_encoder,{input_features:r,input_features_mask:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await It(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:u},!0)}_encode_vision(e){return te(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return So({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,t);return J_({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},dE=class extends Mn{},ci=class extends Mn{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 te(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},uE=class extends ci{},di=class extends b{},_E=class extends di{},hE=class extends di{},ui=class extends b{},pE=class extends ui{},fE=class extends ui{},Eh=class extends b{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},_i=class extends Eh{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){const{data:s,dims:r}=Y_(t),n=BigInt64Array.from({length:3*s.length},(o,i)=>s[i%s.length]),a=Array.from({length:r[0]},(o,i)=>ke(s.subarray(r[1]*i,r[1]*(i+1)))[0]+1n+BigInt(r[1]));return[new P("int64",n,[3,...r]),new P("int64",a,[a.length,1])]}else{const[s,r]=e.dims,n=BigInt64Array.from({length:3*s*r},(a,o)=>BigInt(Math.floor(o%r/s)));return[new P("int64",n,[3,...e.dims]),Nu([s,1])]}}_reorder_and_write_positions(e,t,s,r){const n=e.reduce((l,c)=>l+c.length,0),a=new Array(n);let o=0;for(let l=0;l<3;++l)for(const c of e){const d=c.length/3;for(let u=l*d;u<(l+1)*d;++u)a[o++]=c[u]}let i=0;for(let l=0;l<t.length;++l)if(t[l]==1){for(let c=0;c<3;++c)s[c][r][l]=a[c*n/3+i];++i}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:s,spatial_merge_size:r,state:n}){const{image_token_id:a,video_token_id:o,vision_start_token_id:i}=this.config,l=e,d=l.reduce((m,w,y)=>(w==i&&m.push(y),m),[]).map(m=>l[m+1]),u=d.filter(m=>m==a).length,_=d.filter(m=>m==o).length,h=[];let p=0,f=u,g=_;for(let m=0;m<d.length;++m){const w=l.findIndex((x,k)=>k>p&&x==a),y=l.findIndex((x,k)=>k>p&&x==o),v=f>0&&w!==-1?w:l.length+1,M=g>0&&y!==-1?y:l.length+1;let E,A,S,C;v<M?([A,S,C]=t[n.image_index],++n.image_index,--f,E=v):([A,S,C]=s[n.video_index],++n.video_index,--g,E=M);const[z,R,N]=[Number(A),Math.floor(Number(S)/r),Math.floor(Number(C)/r)],O=E-p,$=h.length>0?ke(h.at(-1))[0]+1:0;h.push(Array.from({length:3*O},(x,k)=>$+k%O));const L=O+$,D=z*R*N,se=Array.from({length:D},(x,k)=>L+Math.floor(k/(R*N))),U=Array.from({length:D},(x,k)=>L+Math.floor(k/N)%R),W=Array.from({length:D},(x,k)=>L+k%N);h.push([se,U,W].flat()),p=E+D}if(p<l.length){const m=h.length>0?ke(h.at(-1))[0]+1:0,w=l.length-p;h.push(Array.from({length:3*w},(y,v)=>m+v%w))}return h}get_rope_index(e,t,s,r){const{vision_config:n}=this.config,a=n.spatial_merge_size??2;if(t||s){const o=e.tolist();r||(r=so(e));const i=r.tolist(),l=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],d=s?s.tolist():[],u={image_index:0,video_index:0},_=[];for(let h=0;h<o.length;++h){const p=o[h].filter((m,w)=>i[h][w]==1),f=this._get_multimodal_rope_positions({filtered_ids:p,image_grid_thw_list:c,video_grid_thw_list:d,spatial_merge_size:a,state:u}),g=this._reorder_and_write_positions(f,i[h],l,h);_.push(ke(g)[0]+1-o[h].length)}return[new P("int64",l.flat(1/0),[3,e.dims[0],e.dims[1]]),new P("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await te(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return So({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,s){if(pr(this,t,1n),!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const n=t.past_key_values.get_seq_length();if(n<t.input_ids.dims[1]){const[a,o]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=o,t.position_ids=a.slice(null,null,[n,null]),t.input_ids=t.input_ids.slice(null,[n,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));const a=BigInt(n),o=t.rope_deltas.map(i=>a+i);t.position_ids=Ct([o,o,o],0)}}return t}},Th=class extends _i{},hi=class extends _i{image_grid_thw_name="image_grid_thw"},Ah=class extends Th{image_grid_thw_name="image_grid_thw"},mE=class extends hi{get_vision_position_ids(e,t,s,r){const n=Math.floor(t[0]/s),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),i=a*o*n,l=Array.from({length:i},()=>e),c=Array.from({length:i},(u,_)=>e+Math.floor(_/(o*n))),d=Array.from({length:i},(u,_)=>e+_%o);return[...l,...c,...d]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:s,spatial_merge_size:r,state:n}){const{image_token_id:a}=this.config,o=[];let i=0,l=e[0]==a?1:0;for(let u=1;u<=e.length;++u){const _=u<e.length?e[u]==a?1:0:-1;_!==l&&(o.push([l,i,u]),i=u,l=_)}let c=0;const d=[];for(const[u,_,h]of o)if(u===0){const p=h-_;d.push(Array.from({length:3*p},(f,g)=>c+g%p)),c+=p}else{const p=t[n.image_index++].map(Number),f=p[0];d.push(this.get_vision_position_ids(c,p,f,r)),c+=Math.max(p[1],p[2])/r}return d}},pi=class extends b{},gE=class extends pi{},wE=class extends pi{},fi=class extends b{},vE=class extends fi{},yE=class extends fi{},mi=class extends b{},ME=class extends mi{},bE=class extends mi{},gi=class extends b{},xE=class extends gi{},kE=class extends gi{},wi=class extends b{},EE=class extends wi{},TE=class extends wi{},vi=class extends b{},AE=class extends vi{},CE=class extends vi{},yi=class extends b{},SE=class extends yi{},PE=class extends yi{},Mi=class extends b{},FE=class extends Mi{},IE=class extends Mi{},bi=class extends b{},LE=class extends bi{},OE=class extends bi{},Ch=class extends b{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},xi=class extends Ch{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,t);return J_({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}},NE=class extends xi{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},Sh=class extends b{},zE=class extends Sh{},Ph=class extends b{},DE=class extends Ph{},ki=class extends b{},BE=class extends ki{},RE=class extends ki{},Ei=class extends b{},$E=class extends Ei{},GE=class extends Ei{async _call(e){return new V(await super._call(e))}},Ti=class extends b{},VE=class extends Ti{},UE=class extends Ti{forward_params=["input_ids","attention_mask","token_type_ids","past_key_values"];prepare_inputs_for_generation(e,t,s){const r=Ss(this,e,t);return r.token_type_ids=(r.past_key_values?ro:so)(r.input_ids),r}},Ht=class extends b{},jE=class extends Ht{},qE=class extends Ht{async _call(e){return new qt(await super._call(e))}},WE=class extends Ht{async _call(e){return new V(await super._call(e))}},HE=class extends Ht{async _call(e){return new Ee(await super._call(e))}},QE=class extends b{},XE=class extends Ht{},YE=class extends Ht{async _call(e){return new qt(await super._call(e))}},KE=class extends Ht{async _call(e){return new V(await super._call(e))}},Ai=class extends b{},JE=class extends Ai{},ZE=class extends Ai{},Fh=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},Ci=class extends b{},eT=class extends Ci{},tT=class extends Ci{async _call(e){return new V(await super._call(e))}},Si=class extends b{},sT=class extends Si{},rT=class extends Si{},bn=class extends b{},nT=class extends bn{async forward(e){const t=!e.input_ids,s=!e.pixel_values;if(t&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=qe([e.pixel_values.dims[0],1])),s){const{image_size:l}=this.config.vision_config;e.pixel_values=Re([0,3,l,l],0)}const{text_embeddings:r,image_embeddings:n,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=r,i.l2norm_text_embeddings=a),s||(i.image_embeddings=n,i.l2norm_image_embeddings=o),i}},Ih=class extends bn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},aT=class extends bn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Pi=class extends b{},oT=class extends Pi{},iT=class extends Pi{},lT=class extends Et{},Fi=class extends b{},cT=class extends Fi{},dT=class extends Fi{},uT=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},Ii=class extends b{},_T=class extends Ii{},hT=class extends Ii{},Lh=class extends b{},pT=class extends Lh{},Li=class extends b{},fT=class extends Li{},mT=class extends Li{},Oi=class extends b{},gT=class extends Oi{},wT=class extends Oi{},Ni=class extends b{},vT=class extends Ni{},yT=class extends Ni{},zi=class extends b{},MT=class extends zi{},bT=class extends zi{},vr=class extends b{},xT=class extends vr{},kT=class extends vr{},ET=class extends vr{async _call(e){return new V(await super._call(e))}},TT=class extends vr{},Oh=class extends b{},AT=class extends Oh{},Nh=class extends b{},CT=class extends Nh{},zh=class extends Me{constructor({char_logits:e,bpe_logits:t,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Dh=class extends b{},ST=class extends Dh{async _call(e){return new zh(await super._call(e))}},Bh=class extends Me{constructor({audio_codes:e}){super(),this.audio_codes=e}},Rh=class extends Me{constructor({audio_values:e}){super(),this.audio_values=e}},xn=class extends b{main_input_name="input_values";forward_params=["input_values"]},PT=class extends xn{async encode(e){return new Bh(await te(this.sessions.encoder_model,e))}async decode(e){return new Rh(await te(this.sessions.decoder_model,e))}},$h=class extends xn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Gh=class extends xn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Di=class extends b{},FT=class extends Di{},IT=class extends Di{},Bi=class extends b{},LT=class extends Bi{},OT=class extends Bi{},Ri=class extends b{},NT=class extends Ri{},zT=class extends Ri{},DT=class extends Et{},$i=class extends b{},BT=class extends $i{},RT=class extends $i{},yr=class extends b{},$T=class extends yr{},GT=class extends yr{async _call(e){return new Ae(await super._call(e))}},VT=class extends yr{async _call(e){return new V(await super._call(e))}},UT=class extends yr{async _call(e){return new De(await super._call(e))}},Gi=class extends b{},jT=class extends Gi{},qT=class extends Gi{},kn=class extends b{},WT=class extends kn{},HT=class extends kn{async _call(e){return new V(await super._call(e))}},QT=class extends kn{},En=class extends b{},XT=class extends En{},YT=class extends En{async _call(e){return new V(await super._call(e))}},KT=class extends En{},Tn=class extends b{},JT=class extends Tn{},ZT=class extends Tn{async _call(e){return new V(await super._call(e))}},eA=class extends Tn{},An=class extends b{},tA=class extends An{},sA=class extends An{async _call(e){return new V(await super._call(e))}},rA=class extends An{},Vi=class extends b{},nA=class extends Vi{},aA=class extends Vi{async _call(e){return new V(await super._call(e))}},Ui=class extends b{},oA=class extends Ui{},iA=class extends Ui{async _call(e){return new V(await super._call(e))}},Mr=class extends b{},lA=class extends Mr{},cA=class extends Mr{async _call(e){return new Ae(await super._call(e))}},dA=class extends Mr{async _call(e){return new V(await super._call(e))}},uA=class extends Mr{async _call(e){return new Ee(await super._call(e))}},ji=class extends b{},_A=class extends ji{},hA=class extends ji{},qi=class extends b{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},pA=class extends qi{},fA=class extends qi{},Ds=class extends b{},mA=class extends Ds{},gA=class extends Ds{async _call(e){return new Ae(await super._call(e))}},wA=class extends Ds{async _call(e){return new V(await super._call(e))}},vA=class extends Ds{async _call(e){return new Ee(await super._call(e))}},yA=class extends Ds{async _call(e){return new De(await super._call(e))}},Wi=class extends b{},MA=class extends Wi{},bA=class extends Wi{},Hi=class extends b{},xA=class extends Hi{},kA=class extends Hi{},Vh=class extends b{},EA=class extends Vh{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let s;if(t==="text"||!e.past_key_values){const i=this.sessions.prepare_inputs_embeds,l=Ie(e,i.inputNames);s=await te(i,l)}else{const i=this.sessions.gen_img_embeds,l=Ie({image_ids:e.input_ids},i.inputNames);s=await te(i,l)}const r={...e,...s},n=await It(this,r),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);const o=await te(a,Ie(n,a.inputNames));return{...s,...n,...o}}prepare_inputs_for_generation(e,t,s){const r=!!t.past_key_values;return pr(this,t,1n),s.guidance_scale!==null&&s.guidance_scale>1&&(r?t.input_ids=fe([t.input_ids,t.input_ids],0):(t.input_ids=fe([t.input_ids,to(t.input_ids,BigInt(s.pad_token_id))],0),t.attention_mask=fe([t.attention_mask,to(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=Re([0,0,3,384,384],1)),r&&(t.images_seq_mask=new P("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new P("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],r=(await super.generate(e)).slice(null,[t,null]),n=this.sessions.image_decode,{decoded_image:a}=await te(n,{generated_tokens:r}),o=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const l of o){const c=pt.fromTensor(l);i.push(c)}return i}},Qi=class extends b{},TA=class extends Qi{},AA=class extends Qi{},Uh=class extends b{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,s]=e.dims,r=this.config.decoder.num_codebooks,n=s-r;let a=0;for(let l=0;l<e.size;++l){if(e.data[l]==this.config.decoder.pad_token_id)continue;const c=l%s,d=Math.floor(l/s)%r,u=c-d;u>0&&u<=n&&(e.data[a++]=e.data[l])}const o=Math.floor(t/r),i=a/(o*r);return new P(e.type,e.data.slice(0,a),[o,r,i])}prepare_inputs_for_generation(e,t,s){const r=BigInt(this.config.decoder.pad_token_id);let n=structuredClone(e);for(let a=0;a<n.length;++a)for(let o=0;o<n[a].length;++o)a%this.config.decoder.num_codebooks>=o&&(n[a][o]=r);return s.guidance_scale!==null&&s.guidance_scale>1&&(n=n.concat(n)),fn(this,n,t)}async generate(e){const t=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await te(this.sessions.encodec_decode,{audio_codes:s});return r}},Xi=class extends b{},CA=class extends Xi{},SA=class extends Xi{},Yi=class extends b{},PA=class extends Yi{},FA=class extends Yi{},Bs=class extends b{},IA=class extends Bs{},LA=class extends Bs{async _call(e){return new Ae(await super._call(e))}},OA=class extends Bs{async _call(e){return new V(await super._call(e))}},NA=class extends Bs{async _call(e){return new Ee(await super._call(e))}},zA=class extends Bs{async _call(e){return new De(await super._call(e))}},jh=class extends b{},DA=class extends jh{},Ki=class extends b{},BA=class extends Ki{},RA=class extends Ki{},Ji=class extends b{},$A=class extends Ji{},GA=class extends Ji{},Zi=class extends b{},VA=class extends Zi{},UA=class extends Zi{},el=class extends b{},jA=class extends el{},qA=class extends el{},tl=class extends b{},WA=class extends tl{},HA=class extends tl{async _call(e){return new V(await super._call(e))}},sl=class extends b{},QA=class extends sl{},XA=class extends sl{},rl=class extends b{},YA=class extends rl{},KA=class extends rl{},nl=class extends b{},JA=class extends nl{},ZA=class extends nl{},al=class extends b{},eC=class extends al{},tC=class extends al{},sC=class extends Et{},qh=class extends b{},rC=class extends qh{async _call(e){return new qt(await super._call(e))}},ol=class extends b{},nC=class extends ol{},aC=class extends ol{},il=class extends b{},oC=class extends il{},iC=class extends il{},ll=class extends b{},lC=class extends ll{},cC=class extends ll{},cl=class extends b{},dC=class extends cl{},uC=class extends cl{},Wh=class extends b{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Hh=class extends Wh{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,image_sizes:r=null,position_ids:n=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(s&&e.dims[1]!==1){if(!r)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await te(this.sessions.vision_encoder,{pixel_values:s,image_sizes:r}))}else{const h=this.config.normalized_config.hidden_size;_=new P("float32",[],[0,h])}({inputs_embeds:a}=await te(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await It(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:n,generation_config:i,logits_processor:l,num_logits_to_keep:c},!1)}},dl=class extends b{},_C=class extends dl{},hC=class extends dl{async _call(e){return new V(await super._call(e))}},ul=class extends b{},pC=class extends ul{},fC=class extends ul{async _call(e){return new Ee(await super._call(e))}},_l=class extends b{},mC=class extends _l{},gC=class extends _l{},hl=class extends b{},wC=class extends hl{},vC=class extends hl{},pl=class extends b{},yC=class extends pl{},MC=class extends pl{},fl=class extends b{},bC=class extends fl{},xC=class extends fl{},ml=class extends b{},kC=class extends ml{},EC=class extends ml{},gl=class extends hi{},Qh=class extends Ah{},TC=class extends gl{},AC=class extends Qh{},wl=class extends gl{},Xh=class extends wl{},CC=class extends wl{},SC=class extends Xh{},vl=class extends b{},PC=class extends vl{},FC=class extends vl{async _call(e){return new V(await super._call(e))}},yl=class extends b{},IC=class extends yl{},LC=class extends yl{async _call(e){return new Yh(await super._call(e))}},Yh=class extends mr{},Rs=class extends b{},OC=class extends Rs{},NC=class extends Rs{async _call(e){return new Ae(await super._call(e))}},zC=class extends Rs{async _call(e){return new V(await super._call(e))}},DC=class extends Rs{async _call(e){return new Ee(await super._call(e))}},BC=class extends Rs{async _call(e){return new De(await super._call(e))}},$s=class extends b{},RC=class extends $s{},$C=class extends $s{async _call(e){return new Ae(await super._call(e))}},GC=class extends $s{async _call(e){return new V(await super._call(e))}},VC=class extends $s{async _call(e){return new Ee(await super._call(e))}},UC=class extends $s{async _call(e){return new De(await super._call(e))}},Ml=class extends b{},jC=class extends Ml{},qC=class extends Ml{async _call(e){return new Kh(await super._call(e))}},Kh=class extends mr{},Jh=class extends Me{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Zh=class extends b{},WC=class extends Zh{async get_image_embeddings({pixel_values:e}){return await Wt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=qe(e.input_points.dims.slice(0,-1));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await te(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new Jh(await super._call(e))}},ep=class extends Me{constructor({iou_scores:e,pred_masks:t,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=s}},tp=class extends b{},bl=class extends tp{async get_image_embeddings({pixel_values:e}){return await Wt(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const a=e.input_points.dims;e.input_labels??=qe(a.slice(0,-1)),e.input_boxes??=Re([a[0],0,4],0)}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=Re([a[0],a[1],0],-1n),e.input_points=Re([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const r=this.sessions.prompt_encoder_mask_decoder,n=Ie(e,r.inputNames);return await te(r,n)}async _call(e){return new ep(await super._call(e))}},HC=class extends bl{},QC=class extends bl{},Cn=class extends b{},XC=class extends Cn{},YC=class extends Cn{},KC=class extends Cn{},Sn=class extends b{},JC=class extends Sn{},ZC=class extends Sn{},eS=class extends Sn{},xl=class extends b{},tS=class extends xl{},sp=class extends xl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},sS=class extends ls{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},kl=class extends b{},rS=class extends kl{},nS=class extends kl{},aS=class extends Fh{},Pn=class extends b{main_input_name="input_values";forward_params=["input_values"]},oS=class extends Pn{async encode(e){return await te(this.sessions.encoder_model,e)}async decode(e){return await te(this.sessions.decoder_model,e)}},rp=class extends Pn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},np=class extends Pn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},El=class extends b{},iS=class extends El{},lS=class extends El{},Fn=class extends b{},cS=class extends Fn{},dS=class extends Fn{},uS=class extends Fn{async generate_speech(e,t,{threshold:s=.5,minlenratio:r=0,maxlenratio:n=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Wt(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),u=Math.floor(c*r),_=this.config.num_mel_bins;let h=[],p=null,f=null,g=0;for(;;){++g;const y=q_(!!f);let v;f?v=f.output_sequence_out:v=new P("float32",new Float32Array(_),[1,1,_]);let M={use_cache_branch:y,output_sequence:v,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};Co(this,M,p),f=await te(this.sessions.decoder_model_merged,M),p=Ao(f,p);const{prob:E,spectrum:A}=f;if(h.push(A),g>=u&&(Array.from(E.data).filter(S=>S>=s).length>0||g>=d))break}const m=fe(h),{waveform:w}=await te(a.sessions.model,{spectrogram:m});return{spectrogram:m,waveform:w}}},_S=class extends b{main_input_name="spectrogram"},br=class extends b{},hS=class extends br{},pS=class extends br{async _call(e){return new Ae(await super._call(e))}},fS=class extends br{async _call(e){return new V(await super._call(e))}},mS=class extends br{async _call(e){return new De(await super._call(e))}},Tl=class extends b{},gS=class extends Tl{},wS=class extends Tl{},Al=class extends b{},vS=class extends Al{},yS=class extends Al{},ap=class extends b{},MS=class extends ap{},op=class extends b{},ip=class extends op{async generate_speech({input_ids:e,attention_mask:t,style:s,num_inference_steps:r=5,speed:n=1.05}){const{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:c,durations:d}=await te(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:s}),u=d.div(n).mul_(a),_=i*o,h=u.data,p=Int32Array.from(h,C=>Math.ceil(C/_)),f=Math.max(...p),g=e.dims[0],m=new BigInt64Array(g*f);for(let C=0;C<g;++C)m.fill(1n,C*f,C*f+p[C]);const w=new P("int64",m,[g,f]),y=l*o,v=y*f;let M=Ny([g,y,f]);const E=M.data;for(let C=0;C<g;++C)if(p[C]!==f)for(let z=0;z<y;++z)E.fill(0,C*v+z*f+p[C],C*v+(z+1)*f);const A=Re([g],r);for(let C=0;C<r;++C){const z=Re([g],C);({denoised_latents:M}=await te(this.sessions.latent_denoiser,{style:s,noisy_latents:M,latent_mask:w,encoder_outputs:c,attention_mask:t,timestep:z,num_inference_steps:A}))}const{waveform:S}=await te(this.sessions.voice_decoder,{latents:M});return{waveform:S,durations:u}}},In=class extends b{},bS=class extends In{},xS=class extends In{async _call(e){return new V(await super._call(e))}},kS=class extends In{},Cl=class extends b{},ES=class extends Cl{},TS=class extends Cl{},Sl=class extends b{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},AS=class extends Sl{},CS=class extends Sl{},Pl=class extends b{},SS=class extends Pl{},PS=class extends Pl{async _call(e){return new lp(await super._call(e))}},lp=class extends Ko{},cp=class extends b{},FS=class extends cp{},Ln=class extends b{},IS=class extends Ln{},LS=class extends Ln{async _call(e){return new qt(await super._call(e))}},OS=class extends Ln{async _call(e){return new V(await super._call(e))}},xr=class extends b{},NS=class extends xr{},zS=class extends xr{async _call(e){return new qt(await super._call(e))}},DS=class extends xr{async _call(e){return new V(await super._call(e))}},BS=class extends xr{async _call(e){return new Ee(await super._call(e))}},Fl=class extends b{},RS=class extends Fl{},$S=class extends Fl{},GS=class extends b{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},Il=class extends b{},VS=class extends Il{},US=class extends Il{async _call(e){return new V(await super._call(e))}},dp=class extends b{},jS=class extends dp{},Ll=class extends b{},qS=class extends Ll{},WS=class extends Ll{async _call(e){return new V(await super._call(e))}},up=class extends b{},HS=class extends up{async _call(e){return new B_(await super._call(e))}},_p=class extends b{},QS=class extends _p{},hp=class extends Me{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},pp=class extends b{},XS=class extends pp{async _call(e){return new hp(await super._call(e))}},YS=class extends xi{},fp=2,KS=1,Ol=new WeakMap;function JS(e,t){const{text_config:s,audio_config:r}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=r,i=a+o,l=new ko,c=_n(r),d={batch_size:1};let u="float32";for(const f of n.inputMetadata){if(f.name==="past_padding_cache"){u=f.type;continue}if(!c.has(f.name))continue;const g=Q_(f.shape,d),m=g.reduce((y,v)=>y*v,1),w=cr[f.type];l[f.name]=new P(f.type,new w(m),g)}const _=cr[u],h=new P(u,new _(i*fp),[1,i,fp]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:h,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:p,text_hidden_size:s.hidden_size}}async function ZS(e,t){const s=t.dims[2],r=Math.floor((KS+s-3)/2)+1,n=new P("int64",BigInt64Array.from({length:r},(d,u)=>BigInt(e.enc_past_seq_len+u)),[1,r]),a=e.enc_past_seq_len+r,o=qe([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await te(e.encoder_session,{input_features:t,attention_mask:o,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=l;for(const d in c)if(d.startsWith("present.")){const u=d.replace("present","past_key_values"),_=e.enc_kv_cache[u];_?.location==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[u]=c[d]}return e.enc_past_seq_len=a,i}async function eP(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){const s=await e.chunks_iter.next();if(s.done){e.stream_exhausted=!0;break}const r=await ZS(e,s.value);e.audio_embed_queue.push({data:r.data,tokens:r.dims[1]}),e.audio_embed_total_tokens+=r.dims[1]}}function tP(e,t,s){if(e.audio_embed_queue.length===0)return;const r=t.data;let n=0,a=s;for(;a>0&&e.audio_embed_queue.length>0;){const o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)r[n*e.text_hidden_size+d]+=o.data[c+d];n+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=s-a}var sP=class extends hr{constructor(e){super(),this._s=e}_call(e){const t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},mp=class extends b{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},gp=class extends mp{async forward({input_ids:e,past_key_values:t,...s}){const r=e.dims[1],n=Ol.get(this);n&&await eP(n,n.audio_consumed+r);const{inputs_embeds:a}=await te(this.sessions.embed_tokens,{input_ids:e});n&&tP(n,a,r);const o={inputs_embeds:a,...s};Co(this,o,t);const i=this.sessions.decoder_model_merged,l=Ie(o,i.inputNames);return await te(i,l)}async generate({input_features:e,stopping_criteria:t,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const r=JS(this,e);Ol.set(this,r);const n=new G_;n.push(new sP(r)),t&&n.extend(t);try{return await super.generate({...s,stopping_criteria:n})}finally{r.enc_kv_cache.dispose(),Ol.delete(this)}}},On=class extends b{},rP=class extends On{},nP=class extends On{async _call(e){return new qt(await super._call(e))}},aP=class extends On{async _call(e){return new V(await super._call(e))}},wp=class extends Me{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Gs=class extends b{},oP=class extends Gs{},iP=class extends Gs{async _call(e){return new qt(await super._call(e))}},lP=class extends Gs{async _call(e){return new V(await super._call(e))}},cP=class extends Gs{async _call(e){return new wp(await super._call(e))}},dP=class extends Gs{async _call(e){return new Ee(await super._call(e))}},vp=class extends b{},uP=class extends vp{},_P=class extends $_{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},Nl=class extends b{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},hP=class extends Nl{},yp=class extends Nl{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,_P)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let s=e.language;const r=e.task;if(e.is_multilingual){s||(Q.warn("No language specified - defaulting to English (en)."),s="en");const a=`<|${PM(s)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[r??"transcribe"])}else if(s||r)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(Q.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:r=null,...n}){t=this._prepare_generation_config(t,n);const a=n.decoder_input_ids instanceof P?no(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(s??=new xo,s.push(new h0(t,a))),t.begin_suppress_tokens&&(s??=new xo,s.push(new R_(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&Q.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:s,init_tokens:a,kwargs:n});const o=await super.generate({inputs:e,generation_config:t,logits_processor:s,decoder_input_ids:a,...n});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:s,init_tokens:r,kwargs:n}){const a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,i=t.return_token_timestamps,l=e,c=l.dims[2],d=2,u=this.config.max_source_positions,_=d*u;let h=0;const p=[],f=[];for(;h<c;){const m=Math.min(h+_,c),w=l.slice(null,null,[h,m]);let y;const v=w.dims[2];if(v<_){const D=l.dims[1],se=new Float32Array(D*_),U=w.data;for(let W=0;W<D;++W)se.set(U.subarray(W*v,(W+1)*v),W*_);y=new P("float32",se,[1,D,_])}else y=w;if(s)for(const D of s)"begin_index"in D&&(D.begin_index=r.length);const M=await super.generate({inputs:y,generation_config:t,logits_processor:s,decoder_input_ids:r,...n}),A=(i?M.sequences:M)[0].tolist().map(Number).slice(r.length);let S;if(i){M.token_timestamps=this._extract_token_timestamps(M,t.alignment_heads,Math.floor((m-h)/d),.02,r.length);const D=h/d*.02;S=M.token_timestamps[0].tolist().slice(r.length).map(se=>se+D)}if(A.length>0&&A.at(-1)===o&&A.pop(),A.length===0)break;const C=A.map(D=>D>=a),z=A.length>=2&&C[A.length-1]&&!C[A.length-2],R=[];for(let D=0;D<A.length-1;++D)C[D]&&C[D+1]&&R.push(D+1);let N,O=A.length;if(R.length>0)if(z)N=m-h;else{const D=R.at(-1);N=(A[D-1]-a)*d,O=D}else N=m-h;const $=Math.floor(h/d),L=a+1500;for(let D=0;D<O;++D)A[D]>=a&&(A[D]=Math.min(A[D]+$,L));p.push(...A.slice(0,O)),S&&f.push(...S.slice(0,O)),h+=N}p.push(o);const g=[...r,...p];if(i){const m=new P("int64",g.map(BigInt),[1,g.length]),w=[...new Array(r.length).fill(0),...f,0],y=new P("float32",new Float32Array(w),[1,w.length]);return{sequences:m,token_timestamps:y}}return new P("int64",g.map(BigInt),[1,g.length])}_extract_token_timestamps(e,t,s=null,r=.02,n=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&Q.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(Q.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(g,m)=>fe(o.map(w=>w[m]),2)),l=Ct(t.map(([g,m])=>{if(g>=i.length)throw new Error(`Layer index ${g} is out of bounds for cross attentions (length ${i.length}).`);return s?i[g].slice(null,m,null,[0,s]):i[g].slice(null,m)})).permute(1,0,2,3),[c,d]=Oy(l,-2,0,!0),u=l.clone();for(let g=0;g<u.dims[0];++g){const m=u[g];for(let w=0;w<m.dims[0];++w){const y=m[w],v=c[g][w][0].data,M=d[g][w][0].data;for(let E=0;E<y.dims[0];++E){let A=y[E].data;for(let S=0;S<A.length;++S)A[S]=(A[S]-M[S])/v[S];A.set(my(A,a))}}}const _=n>0?u.slice(null,null,[n,u.dims[2]],null):u,h=[Ja(_,1)],p=e.sequences.dims,f=new P("float32",new Float32Array(p[0]*p[1]),p);for(let g=0;g<p[0];++g){const m=h[g].neg().squeeze_(0),[w,y]=wy(m.tolist()),v=Array.from({length:w.length-1},(S,C)=>w[C+1]-w[C]),M=ot([1],v).map(S=>!!S),E=[];for(let S=0;S<M.length;++S)M[S]&&E.push(y[S]*r);const A=new Array(n).fill(0);A.push(...E),E.length>0&&A.push(E.at(-1)),f[g].data.set(A)}return f}},pP=class extends yp{},Vs=class extends b{},fP=class extends Vs{},mP=class extends Vs{async _call(e){return new Ae(await super._call(e))}},gP=class extends Vs{async _call(e){return new V(await super._call(e))}},wP=class extends Vs{async _call(e){return new Ee(await super._call(e))}},vP=class extends Vs{async _call(e){return new De(await super._call(e))}},Us=class extends b{},yP=class extends Us{},MP=class extends Us{async _call(e){return new Ae(await super._call(e))}},bP=class extends Us{async _call(e){return new V(await super._call(e))}},xP=class extends Us{async _call(e){return new Ee(await super._call(e))}},kP=class extends Us{async _call(e){return new De(await super._call(e))}},zl=class extends b{},EP=class extends zl{},TP=class extends zl{async _call(e){return new Mp(await super._call(e))}},Mp=class extends Me{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Dl=class extends b{},AP=class extends Dl{},CP=class extends Dl{},Bl=class extends b{},SP=class extends Bl{},PP=class extends Bl{},FP=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"]]),IP=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"]]),LP=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),OP=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["deepseek_v4","DeepseekV4Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"],["zaya","ZayaModel"],["hrm_text","HrmTextModel"]]),bp=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),xp=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),kp=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Ep=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"]]),Tp=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"]]),Ap=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Cp=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["deepseek_v4","DeepseekV4ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["zaya","ZayaForCausalLM"],["hrm_text","HrmTextForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),NP=new Map([["multi_modality","MultiModalityCausalLM"]]),Sp=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"]]),Pp=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"]]),Fp=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Ip=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),Lp=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),zP=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Op=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"]]),Np=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),zp=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),js=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Dp=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Bp=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Rp=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),$p=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Gp=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Vp=new Map([["wavlm","WavLMForXVector"]]),Up=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),jp=new Map([["vitmatte","VitMatteForImageMatting"]]),DP=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),qp=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),Wp=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),Hp=new Map([["sapiens","SapiensForNormalEstimation"]]),Qp=new Map([["vitpose","VitPoseForPoseEstimation"]]),Xp=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),Yp=[[FP,I.EncoderOnly],[IP,I.EncoderDecoder],[OP,I.DecoderOnlyWithoutHead],[LP,I.AutoEncoder],[Ep,I.EncoderOnly],[Tp,I.EncoderOnly],[Ap,I.Seq2Seq],[bp,I.Seq2Seq],[Cp,I.DecoderOnly],[NP,I.MultiModality],[Sp,I.EncoderOnly],[Pp,I.EncoderOnly],[Fp,I.Vision2Seq],[Ip,I.ImageTextToText],[Lp,I.AudioTextToText],[Op,I.EncoderOnly],[js,I.EncoderOnly],[Bp,I.EncoderOnly],[Dp,I.EncoderOnly],[jp,I.EncoderOnly],[DP,I.EncoderOnly],[qp,I.EncoderOnly],[Wp,I.EncoderOnly],[Hp,I.EncoderOnly],[Qp,I.EncoderOnly],[Np,I.EncoderOnly],[zp,I.EncoderOnly],[Rp,I.MaskGeneration],[$p,I.EncoderOnly],[Gp,I.EncoderOnly],[xp,I.Seq2Seq],[kp,I.EncoderOnly],[Vp,I.EncoderOnly],[Up,I.EncoderOnly],[Xp,I.EncoderOnly]];for(const[e,t]of Yp)for(const s of e.values()){Ft.set(s,t);const r=Po[s];Cs.set(r,s),To.set(s,r)}var BP=[["MusicgenForConditionalGeneration",Uh,I.Musicgen],["Phi3VForCausalLM",Hh,I.Phi3V],["CLIPTextModelWithProjection",oh,I.EncoderOnly],["SiglipTextModel",sp,I.EncoderOnly],["JinaCLIPTextModel",Ih,I.EncoderOnly],["ClapTextModelWithProjection",nh,I.EncoderOnly],["ClapAudioModelWithProjection",ah,I.EncoderOnly],["DacEncoderModel",ch,I.EncoderOnly],["DacDecoderModel",dh,I.EncoderOnly],["MimiEncoderModel",$h,I.EncoderOnly],["MimiDecoderModel",Gh,I.EncoderOnly],["SnacEncoderModel",rp,I.EncoderOnly],["SnacDecoderModel",np,I.EncoderOnly],["Gemma3nForConditionalGeneration",Mn,I.ImageAudioTextToText],["Gemma4ForConditionalGeneration",ci,I.ImageAudioTextToText],["SupertonicForConditionalGeneration",ip,I.Supertonic],["ChatterboxModel",th,I.Chatterbox],["EmbeddingGemma2Model",vh,I.MultimodalEncoder],["VoxtralRealtimeForConditionalGeneration",gp,I.VoxtralRealtime]];for(const[e,t,s]of BP)Ft.set(e,s),Cs.set(t,e),To.set(e,t);var Kp=new Map([["modnet",js],["birefnet",js],["isnet",js],["ben",js]]);for(const[e,t]of Kp.entries())t.set(e,"PreTrainedModel"),Ft.set(e,I.EncoderOnly),To.set(e,b);var RP=new Set(Kp.keys());Ft.set("PreTrainedModel",I.EncoderOnly),Cs.set(b,"PreTrainedModel");var ie={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Ep,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Tp,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:xp,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:kp,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Sp,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Pp,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Op,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:js,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Dp,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Bp,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Np,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:zp,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Rp,MODEL_FOR_CTC_MAPPING_NAMES:$p,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Gp,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Vp,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Up,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:zP,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:jp,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:qp,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:Wp,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:Hp,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:Qp,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:Xp,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Ip,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Lp,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Ap,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:bp,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Cp,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Fp};P0(ie);var le=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(const t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:r=null,local_files_only:n=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:u={}}={}){const _={progress_callback:t,config:s,cache_dir:r,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:u};if(_.config=await _r.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const{model_type:h}=_.config;for(const p of this.MODEL_CLASS_MAPPINGS){let f=p.get(h);if(!f){for(const g of p.values())if(g[0]===h){f=g;break}if(!f)continue}return await Po[f].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return RP.has(h)||Q.warn(`Unknown model class "${h}", attempting to construct from base class.`),await b.from_pretrained(e,_);throw Error(`Unsupported model type: ${h}`)}},kr=class extends le{static MODEL_CLASS_MAPPINGS=Yp.map(e=>e[0]);static BASE_IF_FAIL=!0},Jp=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},$P=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Rl=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},GP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},VP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},UP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Zp=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},jP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},qP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},WP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},HP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},ef=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},tf=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},sf=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},QP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},XP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var YP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_CTC_MAPPING_NAMES]},KP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var JP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var ZP=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},e2=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var t2=class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends le{static MODEL_CLASS_MAPPINGS=[ie.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function mt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>pt.read(t)))}async function qs(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(s=>typeof s=="string"||s instanceof URL?RM(s,t):s instanceof Float64Array?new Float32Array(s):s))}function $l(e,t){t&&(e=e.map(o=>o|0));const[s,r,n,a]=e;return{xmin:s,ymin:r,xmax:n,ymax:a}}var be=class extends Ue{constructor({task:e,model:t,tokenizer:s=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=s,this.processor=r}async dispose(){await this.model.dispose()}},s2=class extends be{async _call(e,{top_k:t=1}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(s),{problem_type:n,id2label:a}=this.model.config,o=n==="multi_label_classification"?l=>l.sigmoid():l=>new P("float32",Ne(l.data),l.dims),i=[];for(const l of r.logits){const c=o(l),d=await xs(c,t),u=d[0].tolist(),h=d[1].tolist().map((p,f)=>({label:a?a[p]:`LABEL_${p}`,score:u[f]}));t===1?i.push(...h):i.push(h)}return Array.isArray(e)||t===1?i:i[0]}},r2=class extends be{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:s="none"}={}){if(s!=="none"&&s!=="simple")throw new Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);const r=Array.isArray(e),n=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),o=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let c=0;c<o.dims[0];++c){const d=n.input_ids[c].tolist(),u=o[c],_=[];for(let h=0;h<u.dims[0];++h){const p=u[h],f=ke(p.data)[1],g=i?i[f]:`LABEL_${f}`;if(t.includes(g))continue;const m=this.tokenizer.decode([d[h]],{skip_special_tokens:!0});if(m==="")continue;const w=Ne(p.data);_.push({entity:g,score:w[f],index:h,word:m})}l.push(s==="simple"?a2(_,d,this.tokenizer):_)}return r?l:l[0]}};function n2(e){const t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function a2(e,t,s){const r=[];let n=null;for(let a=0;a<e.length;++a){const[o,i]=n2(e[a].entity);n===i&&o!=="B"&&o!=="S"?(r[r.length-1].end=a+1,o==="E"&&(n=null)):(r.push({tag:i,start:a,end:a+1}),n=o==="S"?null:i)}return r.map(({tag:a,start:o,end:i})=>{let l=0;const c=[];for(let d=o;d<i;++d)l+=e[d].score,c.push(t[e[d].index]);return{entity_group:a,score:l/(i-o),word:s.decode(c,{skip_special_tokens:!0})}})}var o2=class extends be{async _call(e,t,{top_k:s=1}={}){const r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),n=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(r),i=r.input_ids.tolist(),l=r.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,u=[];for(let _=0;_<a.dims[0];++_){const h=i[_],p=h.findIndex(M=>M==d),f=a[_].tolist(),g=o[_].tolist();for(let M=1;M<f.length;++M)(l[_]==0||M<=p||c.findIndex(E=>E==h[M])!==-1)&&(f[M]=-1/0,g[M]=-1/0);const m=Ne(f).map((M,E)=>[M,E]),w=Ne(g).map((M,E)=>[M,E]);m[0][0]=0,w[0][0]=0;const y=bm(m,w).filter(M=>M[0][1]<=M[1][1]).map(M=>[M[0][1],M[1][1],M[0][0]*M[1][0]]).sort((M,E)=>E[2]-M[2]),v=[];for(let M=0;M<Math.min(y.length,s);++M){const[E,A,S]=y[M],C=h.slice(E,A+1),z=this.tokenizer.decode(C,{skip_special_tokens:!0});v.push({answer:z,score:S})}s===1?u.push(...v):u.push(v)}return n?u:u[0]}},i2=class extends be{async _call(e,{top_k:t=5}={}){const{mask_token_id:s,mask_token:r}=this.tokenizer,n=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(n),o=[],i=n.input_ids.tolist();for(let l=0;l<i.length;++l){const c=i[l],d=c.findIndex(f=>f==s);if(d===-1)throw Error(`Mask token (${r}) not found in text.`);const u=a[l][d],_=await xs(new P("float32",Ne(u.data),u.dims),t),h=_[0].tolist(),p=_[1].tolist();o.push(p.map((f,g)=>{const m=c.slice();return m[d]=f,{score:h[g],token:Number(f),token_str:this.tokenizer.decode([f]),sequence:this.tokenizer.decode(m,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Gl=class extends be{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(i=>this.model.config.prefix+i));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(i=>s[this.task].prefix+i));const r=this.tokenizer,n={padding:!0,truncation:!0};let a;this.task==="translation"&&"_build_translation_inputs"in r?a=r._build_translation_inputs(e,n,t):a=r(e,n);const o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(i=>({[this._key]:i}))}},l2=class extends Gl{_key="summary_text"},c2=class extends Gl{_key="translation_text"};function rf(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var d2=class extends be{_default_generation_config={max_new_tokens:256};async _call(e,t={}){const{add_special_tokens:s,return_full_text:r,tools:n,documents:a,chat_template:o,tokenizer_encode_kwargs:i,...l}=t;let c=!1,d=!1,u=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,_=i,h;if(typeof e=="string")h=e=[e];else if(Array.isArray(e)&&e.every(v=>typeof v=="string"))c=!0,h=e;else{if(rf(e))e=[e];else if(Array.isArray(e)&&e.every(rf))c=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");d=!0;const v={tokenize:!1,add_generation_prompt:!0,...Ie({tools:n,documents:a,chat_template:o},["tools","documents","chat_template"]),..._};h=e.map(M=>this.tokenizer.apply_chat_template(M,v)),u=!1,_=void 0}const p=d?!1:r??!0;this.tokenizer.padding_side="left";const f=this.tokenizer(h,{add_special_tokens:u,padding:!0,truncation:!0,..._}),g=await this.model.generate({...f,...this._default_generation_config,...l}),m=this.tokenizer.batch_decode(g,{skip_special_tokens:!0});let w;!p&&f.input_ids.dims.at(-1)>0&&(w=this.tokenizer.batch_decode(f.input_ids,{skip_special_tokens:!0}).map(v=>v.length));const y=Array.from({length:e.length},v=>[]);for(let v=0;v<m.length;++v){const M=Math.floor(v/g.dims[0]*e.length);w&&(m[v]=m[v].slice(w[M])),y[M].push({generated_text:d?[...e[M],{role:"assistant",content:m[v]}]:m[v]})}return!c&&y.length===1?y[0]:y}},u2=class extends be{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,s])=>[t.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Q.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(Q.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:s="This example is {}.",multi_label:r=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>s.replace("{}",l)),o=r||t.length===1,i=[];for(const l of e){const c=[];for(const _ of a){const h=this.tokenizer(l,{text_pair:_,padding:!0,truncation:!0}),p=await this.model(h);o?c.push([p.logits.data[this.contradiction_id],p.logits.data[this.entailment_id]]):c.push(p.logits.data[this.entailment_id])}const u=(o?c.map(_=>Ne(_)[1]):Ne(c)).map((_,h)=>[_,h]).sort((_,h)=>h[0]-_[0]);i.push({sequence:l,labels:u.map(_=>t[_[1]]),scores:u.map(_=>_[0])})}return n?i:i[0]}},_2=class extends be{async _call(e,{top_k:t=5}={}){const s=this.processor.feature_extractor.config.sampling_rate,r=await qs(e,s),n=this.model.config.id2label,a=[];for(const o of r){const i=await this.processor(o),c=(await this.model(i)).logits[0],d=await xs(new P("float32",Ne(c.data),c.dims),t),u=d[0].tolist(),h=d[1].tolist().map((p,f)=>({label:n?n[p]:`LABEL_${p}`,score:u[f]}));a.push(h)}return Array.isArray(e)?a:a[0]}},h2=class extends be{async _call(e,t,{hypothesis_template:s="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const n=t.map(c=>s.replace("{}",c)),a=this.tokenizer(n,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await qs(e,o),l=[];for(const c of i){const d=await this.processor(c),u=await this.model({...a,...d}),_=Ne(u.logits_per_audio.data);l.push([..._].map((h,p)=>({score:h,label:t[p]})))}return r?l[0]:l}},p2=class extends be{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);case"cohere_asr":return this._call_cohere_asr(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&Q.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&Q.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(e),r=s?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,a=await qs(r,n),o=[];for(const i of a){const l=await this.processor(i),d=(await this.model(l)).logits[0],u=[];for(const h of d)u.push(ke(h.data)[1]);const _=this.tokenizer.decode(u,{skip_special_tokens:!0}).trim();o.push({text:_})}return s?o[0]:o}async _call_whisper(e,t){const s=t.return_timestamps??!1,r=t.chunk_length_s??0,n=t.force_full_sequences??!1;let a=t.stride_length_s??null;const o={...t};s==="word"&&(o.return_token_timestamps=!0,o.return_timestamps=!0);const i=!Array.isArray(e),l=i?[e]:e,c=this.processor.feature_extractor.config,d=c.chunk_length/this.model.config.max_source_positions,u=c.hop_length,_=c.sampling_rate,h=await qs(l,_),p=[];for(const f of h){let g=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const y=_*r,v=_*a,M=y-2*v;let E=0;for(;;){const A=E+y,S=f.subarray(E,A),C=await this.processor(S),z=E===0,R=A>=f.length;if(g.push({stride:[S.length,z?0:v,R?0:v],input_features:C.input_features,is_last:R}),R)break;E+=M}}else g=[{stride:[f.length,0,0],input_features:(await this.processor(f)).input_features,is_last:!0}];for(const y of g){o.num_frames=Math.floor(y.stride[0]/u);const v=await this.model.generate({inputs:y.input_features,...o});if(s==="word"){const M=v.sequences.tolist()[0],E=v.token_timestamps.tolist()[0],A=this.tokenizer.timestamp_begin,S=Math.max(M.findIndex(C=>Number(C)>=A),0);y.tokens=M.slice(S),y.token_timestamps=E.slice(S).map(C=>lr(C,2))}else y.tokens=v[0].tolist();y.stride=y.stride.map(M=>M/_)}const[m,w]=this.tokenizer._decode_asr(g,{time_precision:d,return_timestamps:s,force_full_sequences:n});p.push({text:m,...w})}return i?p[0]:p}async _call_moonshine(e,t){const s=!Array.isArray(e),r=s?[e]:e,n=this.processor.feature_extractor.config.sampling_rate,a=await qs(r,n),o=[];for(const i of a){const l=await this.processor(i),c=Math.floor(i.length/n)*6,d=await this.model.generate({max_new_tokens:c,...t,...l}),u=this.tokenizer.batch_decode(d,{skip_special_tokens:!0})[0];o.push({text:u})}return s?o[0]:o}async _call_cohere_asr(e,t){const s=!Array.isArray(e),r=s?[e]:e,n=this.processor.feature_extractor,a=n.config.sampling_rate,o=await qs(r,a),i=t.language??"en",l=this.processor.get_decoder_prompt_ids(i),c=[];for(const d of o){const u=n.split_audio(d),_=[];for(const p of u){const f=await this.processor(p),g=await this.model.generate({...f,decoder_input_ids:l,...t}),m=this.tokenizer.decode(g[0].tolist(),{skip_special_tokens:!0}).trim();_.push(m)}const h=this.processor.constructor.join_chunks(_,i);c.push({text:h})}return s?c[0]:c}},f2=class extends be{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 ee.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new P("float32",e,[e.length]);else if(!(e instanceof P))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw new Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,s,r=null){const n=t.data,[a,o]=t.dims,i=r?r.data:null,l=[];for(let c=0;c<a;++c){const d=i?Math.min(Math.ceil(i[c]),o):o,u=c*o;l.push(new XM(n.slice(u,u+d),s))}return Array.isArray(e)?l:l[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type==="supertonic"?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:s,speed:r}){if(!t)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:n,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),i=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,i),t=t.view(i,-1,a);const{waveform:l,durations:c}=await this.model.generate_speech({...o,style:t,num_inference_steps:s,speed:r});return this._postprocess_waveform(e,l,n,c)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(t),r=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,r)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||(Q.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await kr.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),r=s.dims[0];t=await this._prepare_speaker_embeddings(t,r),t=t.view(r,-1);const{waveform:n}=await this.model.generate_speech(s,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,n,a)}},m2=class extends be{async _call(e,t={}){const s=Array.isArray(e),r=await mt(e),{pixel_values:n}=await this.processor(r),a=[];for(const o of n){o.dims=[1,...o.dims];const i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(l)}return s?a:a[0]}},g2=class extends be{async _call(e,{top_k:t=5}={}){const s=await mt(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(const i of n.logits){const l=await xs(new P("float32",Ne(i.data),i.dims),t),c=l[0].tolist(),u=l[1].tolist().map((_,h)=>({label:a?a[_]:`LABEL_${_}`,score:c[h]}));o.push(u)}return Array.isArray(e)?o:o[0]}},nf={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},af=class extends be{async _call(e,{threshold:t=.5,mask_threshold:s=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:n=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const l=await mt(e),c=l.map(m=>[m.height,m.width]),d=await this.processor(l),{inputNames:u,outputNames:_}=this.model.sessions.model;if(!u.includes("pixel_values")){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);const m=u[0];if(m in d)throw Error(`Input name ${m} already exists in the inputs.`);d[m]=d.pixel_values}const h=await this.model(d);let p=null;if(o!==null)p=nf[o];else if(this.processor.image_processor){for(const[m,w]of Object.entries(nf))if(w in this.processor.image_processor){p=this.processor.image_processor[w].bind(this.processor.image_processor),o=m;break}}const f=this.model.config.id2label,g=[];if(o)if(o==="panoptic"||o==="instance"){const m=p(h,t,s,r,n,a??c)[0],w=m.segmentation;for(const y of m.segments_info){const v=new Uint8ClampedArray(w.data.length);for(let E=0;E<w.data.length;++E)w.data[E]===y.id&&(v[E]=255);const M=new pt(v,w.dims[1],w.dims[0],1);g.push({score:y.score,label:f[y.label_id],mask:M})}}else if(o==="semantic"){const{segmentation:m,labels:w}=p(h,a??c)[0];for(const y of w){const v=new Uint8ClampedArray(m.data.length);for(let E=0;E<m.data.length;++E)m.data[E]===y&&(v[E]=255);const M=new pt(v,m.dims[1],m.dims[0],1);g.push({score:null,label:f[y],mask:M})}}else throw Error(`Subtask ${o} not supported.`);else{const w=h[_[0]];for(let y=0;y<c.length;++y){const v=c[y],M=w[y];M.data.some(A=>A<-1e-5||A>1+1e-5)&&M.sigmoid_();const E=await pt.fromTensor(M.mul_(255).to("uint8")).resize(v[1],v[0]);g.push({label:null,score:null,mask:E})}}return g}},w2=class extends af{async _call(e,t={}){const s=await mt(e),r=await super._call(e,t),n=s.map((a,o)=>{const i=a.clone();return i.putAlpha(r[o].mask),i});return Array.isArray(e)?n:n[0]}},v2=class extends be{async _call(e,t,{hypothesis_template:s="This is a photo of {}"}={}){const r=Array.isArray(e),n=await mt(e),a=t.map(u=>s.replace("{}",u)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(n),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?u=>u.sigmoid().data:u=>Ne(u.data),d=[];for(const u of l.logits_per_image){const h=[...c(u)].map((p,f)=>({score:p,label:t[f]}));h.sort((p,f)=>f.score-p.score),d.push(h)}return r?d:d[0]}},y2=class extends be{async _call(e,{threshold:t=.9,percentage:s=!1}={}){const r=Array.isArray(e);if(r&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await mt(e),a=s?null:n.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(n),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,u=c.map(_=>_.boxes.map((h,p)=>({score:_.scores[p],label:d[_.classes[p]],box:$l(h,!s)})));return r?u:u[0]}},M2=class extends be{async _call(e,t,{threshold:s=.1,top_k:r=null,percentage:n=!1}={}){const a=Array.isArray(e),o=await mt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){const u=o[d],_=n?null:[[u.height,u.width]],h=l.pixel_values[d].unsqueeze_(0),p=await this.model({...i,pixel_values:h});let f;if("post_process_grounded_object_detection"in this.processor){const g=this.processor.post_process_grounded_object_detection(p,i.input_ids,{box_threshold:s,text_threshold:s,target_sizes:_})[0];f=g.boxes.map((m,w)=>({score:g.scores[w],label:g.labels[w],box:$l(m,!n)}))}else{const g=this.processor.image_processor.post_process_object_detection(p,s,_,!0)[0];f=g.boxes.map((m,w)=>({score:g.scores[w],label:t[g.classes[w]],box:$l(m,!n)}))}f.sort((g,m)=>m.score-g.score),r!==null&&(f=f.slice(0,r)),c.push(f)}return a?c:c[0]}},b2=class extends be{_default_generation_config={max_new_tokens:256};async _call(e,t,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}const r=(await mt(e))[0],{pixel_values:n}=await this.processor(r),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,i=await this.model.generate({inputs:n,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...s}),c=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/);let d=null;return c&&c.length>=2&&(d=c[1].trim()),[{answer:d}]}},x2=class extends be{async _call(e){const t=await mt(e),s=await this.processor(t),r=await this.model(s),n=[];for(const a of r.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(pt.fromTensor(o))}return Array.isArray(e)?n:n[0]}},k2=class extends be{async _call(e){const t=await mt(e),s=await this.processor(t),{predicted_depth:r}=await this.model(s),n=[];for(let a=0;a<t.length;++a){const o=r[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,u=(await ht(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=u.min().item(),h=u.max().item(),p=u.sub(_).div_(h-_).mul_(255).to("uint8").unsqueeze(0),f=pt.fromTensor(p);n.push({predicted_depth:u,depth:f})}return Array.isArray(e)?n:n[0]}},E2=class extends be{async _call(e,{pooling:t="none",normalize:s=!1,quantize:r=!1,precision:n="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=Ly(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return s&&(i=i.normalize(2,-1)),r&&(i=zy(i,n)),i}},T2=class extends be{async _call(e,{pool:t=null}={}){const s=await mt(e),{pixel_values:r}=await this.processor(s),n=await this.model({pixel_values:r});let a;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=n.pooler_output}else a=n.last_hidden_state??n.logits??n.image_embeds;return a}},Nn=Object.freeze({"text-classification":{pipeline:s2,model:Jp,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:r2,model:$P,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:o2,model:qP,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:i2,model:jP,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:l2,model:Rl,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:c2,model:Rl,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Gl,model:Rl,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:d2,model:Zp,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:u2,model:Jp,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:_2,model:KP,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:h2,model:kr,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:p2,model:[GP,YP],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:f2,model:[UP,VP],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:m2,model:WP,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:g2,model:HP,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:af,model:[ef,tf,sf],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:w2,model:[ef,tf,sf],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:v2,model:kr,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:y2,model:QP,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:M2,model:XP,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:b2,model:JP,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:x2,model:ZP,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:k2,model:e2,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:E2,model:kr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:T2,model:[t2,kr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),of=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function A2(e){if(!e)throw new Error("modelId is required");return(await or(e,ur,{})).exists?[ur]:[]}async function C2(e,{config:t=null,dtype:s=null,device:r=null,model_file_name:n=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await j_(e,{config:t,dtype:s,device:r,model_file_name:n});if(a){const l=await zu(e);i.push(...l)}if(o){const l=await A2(e);i.push(...l)}return i}async function S2(e,t,s={}){e=of[e]??e;const r=Nn[e];if(!r)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(Nn).join(", ")}]`);const{type:n}=r,i=await C2(t,{...s,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){const l=await U_(t,s),c=V_(l),d=C0(c);if(d){const u=Object.values(d).map(_=>`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||u.some(h=>_.startsWith(h)))}}return i}async function P2(e,t=null,{progress_callback:s=null,config:r=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:u=null,session_options:_={}}={}){e=of[e]??e;const h=Nn[e.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(Nn)}]`);t||(t=h.default.model,Q.info(`No model specified. Using default model: "${t}".`),!l&&h.default.dtype&&(l=h.default.dtype));const p=await S2(e,t,{device:i,dtype:l});let f={};if(s)try{(await Promise.all(p.map(async R=>or(t,R)))).forEach((R,N)=>{R.exists&&(f[p[N]]={loaded:0,total:R.size??0})})}catch(z){Q.warn(`Unable to fetch model file metadata for total progress tracking: ${z}`)}const g={progress_callback:s?new $r(s,f):void 0,config:r,cache_dir:n,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:u,session_options:_},m=p.includes("tokenizer.json"),w=p.includes("preprocessor_config.json"),y=h.model;let v;if(Array.isArray(y)){const z=r??await _r.from_pretrained(t,g),{model_type:R}=z,N=y.find(O=>O.supports(R));if(!N)throw Error(`Unsupported model type "${R}" for task "${e}". None of the candidate model classes support this type.`);v=N.from_pretrained(t,{...g,config:z})}else v=y.from_pretrained(t,g);const[M,E,A]=await Promise.all([m?ne.from_pretrained(t,g):null,w?Jx.from_pretrained(t,g):null,v]),S={task:e,model:A};M&&(S.tokenizer=M),E&&(S.processor=E),Bt(s,{status:"ready",task:e,model:t});const C=h.pipeline;return new C(S)}var F2=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,I2=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},lf=Y.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),L2=class extends I2{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:r=null,skip_special_tokens:n=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=s??lf,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:n,...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");const t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){const 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}const a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=ot(this.token_cache,s);const r=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let n;t||r.endsWith(`
|
||
`)?(n=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&F2(r.charCodeAt(r.length-1))?(n=r.slice(this.print_len),this.print_len+=n.length):(n=r.slice(this.print_len,r.lastIndexOf(" ")+1),this.print_len+=n.length),this.on_finalized_text(n,!1)}end(){let e;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):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===lf&&Y.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
|
||
`)}};ee.allowLocalModels=!1;const cs=e=>self.postMessage(e);let Ws=null,Hs=null;const Vl=new x0;function cf(e){const t=new Map;return s=>{if(s.status!=="progress"||!s.file)return;t.set(s.file,{loaded:s.loaded??0,total:s.total??0});let r=0,n=0;t.forEach(a=>{r+=a.loaded,n+=a.total}),cs({type:"progress",task:e,loaded:r,total:n})}}const df=new MessageChannel,uf=[];df.port1.onmessage=()=>uf.shift()?.();const O2=()=>new Promise(e=>{uf.push(e),df.port2.postMessage(null)});function N2(e){const t=e.forward.bind(e);e.forward=async(...s)=>(await O2(),t(...s))}const z2=e=>e instanceof Error?e.message:String(e);async function D2(e,t,s){const r=performance.now();Ws&&(await Ws.model.dispose(),Ws=null);const n=cf("chat"),a=await ne.from_pretrained(e,{progress_callback:n}),o=await Zp.from_pretrained(e,{dtype:t,device:s,progress_callback:n});N2(o),Ws={id:e,tokenizer:a,model:o},cs({type:"ready",task:"chat",ms:Math.round(performance.now()-r)})}async function B2(e,t,s){if(!Ws)throw new Error("no model loaded");const{tokenizer:r,model:n}=Ws;Vl.reset();const a={add_generation_prompt:!0,return_dict:!0,enable_thinking:s},o=r.apply_chat_template(e,a);let i=0,l=0;const c=performance.now(),d=new L2(r,{skip_prompt:!0,skip_special_tokens:!0,callback_function:_=>cs({type:"token",text:_}),token_callback_function:()=>{i+=1,i===1&&(l=performance.now())}});await n.generate({...o,max_new_tokens:t,do_sample:!1,repetition_penalty:1.1,streamer:d,stopping_criteria:Vl});const u=performance.now();cs({type:"done",tokens:i,ms:Math.round(u-c),firstTokenMs:Math.round((l||u)-c)})}async function R2(e,t){const s=performance.now();Hs&&(await Hs.run.dispose(),Hs=null);const r=await P2("feature-extraction",e,{dtype:t,device:"wasm",progress_callback:cf("embed")});Hs={id:e,run:r},cs({type:"ready",task:"embed",ms:Math.round(performance.now()-s)})}async function $2(e,t){if(!Hs)throw new Error("no embedding model loaded");const s=await Hs.run(t,{pooling:"mean",normalize:!0});cs({type:"embedded",id:e,vectors:s.tolist()})}self.addEventListener("message",async e=>{const t=e.data,s=t.type==="load-embed"||t.type==="embed"?"embed":"chat";try{t.type==="load-chat"?await D2(t.model,t.dtype,t.device):t.type==="generate"?await B2(t.messages,t.maxNewTokens,t.thinking):t.type==="interrupt"?Vl.interrupt():t.type==="load-embed"?await R2(t.model,t.dtype):t.type==="embed"&&await $2(t.id,t.texts)}catch(r){cs({type:"error",task:s,message:z2(r)})}})})();
|