@octomil/browser 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,52 +1,59 @@
1
- "use strict";var __Octomil_ns=(()=>{var Wh=Object.create;var Os=Object.defineProperty;var Gh=Object.getOwnPropertyDescriptor;var Kh=Object.getOwnPropertyNames;var $h=Object.getPrototypeOf,Hh=Object.prototype.hasOwnProperty;var Qh=(d,t,e)=>t in d?Os(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var jt=(d,t)=>()=>(d&&(t=d(d=0)),t);var Xh=(d,t)=>()=>(t||d((t={exports:{}}).exports,t),t.exports),ti=(d,t)=>{for(var e in t)Os(d,e,{get:t[e],enumerable:!0})},gm=(d,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kh(t))!Hh.call(d,o)&&o!==e&&Os(d,o,{get:()=>t[o],enumerable:!(r=Gh(t,o))||r.enumerable});return d};var Mm=(d,t,e)=>(e=d!=null?Wh($h(d)):{},gm(t||!d||!d.__esModule?Os(e,"default",{value:d,enumerable:!0}):e,d)),Jh=d=>gm(Os({},"__esModule",{value:!0}),d);var v=(d,t,e)=>Qh(d,typeof t!="symbol"?t+"":t,e);var ii=Xh((SD,xm)=>{xm.exports=globalThis.ort});var Uo,ns,Sm,hf,Dm,hi=jt(()=>{Uo=new Map,ns=[],Sm=(d,t,e)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let r=Uo.get(d);if(r===void 0)Uo.set(d,{backend:t,priority:e});else{if(r.priority>e)return;if(r.priority===e&&r.backend!==t)throw new Error(`cannot register backend "${d}" using priority ${e}`)}if(e>=0){let o=ns.indexOf(d);o!==-1&&ns.splice(o,1);for(let a=0;a<ns.length;a++)if(Uo.get(ns[a]).priority<=e){ns.splice(a,0,d);return}ns.push(d)}return}throw new TypeError("not a valid backend")},hf=async d=>{let t=Uo.get(d);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let e=!!t.initPromise;try{return e||(t.initPromise=t.backend.init(d)),await t.initPromise,t.initialized=!0,t.backend}catch(r){return e||(t.error=`${r}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Dm=async d=>{let t=d.executionProviders||[],e=t.map(l=>typeof l=="string"?l:l.name),r=e.length===0?ns:e,o,a=[],h=new Set;for(let l of r){let p=await hf(l);typeof p=="string"?a.push({name:l,err:p}):(o||(o=p),o===p&&h.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:p}of a)e.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${p}`);let u=t.filter(l=>h.has(typeof l=="string"?l:l.name));return[o,new Proxy(d,{get:(l,p)=>p==="executionProviders"?u:Reflect.get(l,p)})]}});var Lm=jt(()=>{hi()});var Om,Rm=jt(()=>{Om="1.24.2"});var Bm,Gt,fi=jt(()=>{Rm();Bm="warning",Gt={wasm:{},webgl:{},webgpu:{},versions:{common:Om},set logLevel(d){if(d!==void 0){if(typeof d!="string"||["verbose","info","warning","error","fatal"].indexOf(d)===-1)throw new Error(`Unsupported logging level: ${d}`);Bm=d}},get logLevel(){return Bm}};Object.defineProperty(Gt,"logLevel",{enumerable:!0})});var ff,Nm=jt(()=>{fi();ff=Gt});var jm,Vm,Um=jt(()=>{jm=(d,t)=>{let e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);e.width=d.dims[3],e.height=d.dims[2];let r=e.getContext("2d");if(r!=null){let o,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=d.dims[2],a=d.dims[3]):(o=d.dims[3],a=d.dims[2]);let h=t?.format!==void 0?t.format:"RGB",u=t?.norm,l,p;u===void 0||u.mean===void 0?l=[255,255,255,255]:typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:(l=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(l[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let w=a*o,f=0,i=w,y=w*2,E=-1;h==="RGBA"?(f=0,i=w,y=w*2,E=w*3):h==="RGB"?(f=0,i=w,y=w*2):h==="RBG"&&(f=0,y=w,i=w*2);for(let S=0;S<a;S++)for(let z=0;z<o;z++){let k=(d.data[f++]-p[0])*l[0],A=(d.data[i++]-p[1])*l[1],N=(d.data[y++]-p[2])*l[2],x=E===-1?255:(d.data[E++]-p[3])*l[3];r.fillStyle="rgba("+k+","+A+","+N+","+x+")",r.fillRect(z,S,1,1)}if("toDataURL"in e)return e.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Vm=(d,t)=>{let e=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(e!=null){let o,a,h;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=d.dims[2],a=d.dims[1],h=d.dims[3]):(o=d.dims[3],a=d.dims[2],h=d.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,p,w;l===void 0||l.mean===void 0?p=[255,255,255,255]:typeof l.mean=="number"?p=[l.mean,l.mean,l.mean,l.mean]:(p=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(p[3]=l.mean[3])),l===void 0||l.bias===void 0?w=[0,0,0,0]:typeof l.bias=="number"?w=[l.bias,l.bias,l.bias,l.bias]:(w=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(w[3]=l.bias[3]));let f=a*o;if(t!==void 0&&(t.format!==void 0&&h===4&&t.format!=="RGBA"||h===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let i=4,y=0,E=1,S=2,z=3,k=0,A=f,N=f*2,x=-1;u==="RGBA"?(k=0,A=f,N=f*2,x=f*3):u==="RGB"?(k=0,A=f,N=f*2):u==="RBG"&&(k=0,N=f,A=f*2),r=e.createImageData(o,a);for(let P=0;P<a*o;y+=i,E+=i,S+=i,z+=i,P++)r.data[y]=(d.data[k++]-w[0])*p[0],r.data[E]=(d.data[A++]-w[1])*p[1],r.data[S]=(d.data[N++]-w[2])*p[2],r.data[z]=x===-1?255:(d.data[x++]-w[3])*p[3]}else throw new Error("Can not access image data");return r}});var gi,zm,Wm,Gm,Km,$m,Hm=jt(()=>{zo();gi=(d,t)=>{if(d===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:e,width:r}=t,o=t.norm??{mean:255,bias:0},a,h;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?h=[o.bias,o.bias,o.bias,o.bias]:h=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=e*r,w=l==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),f=4,i=0,y=1,E=2,S=3,z=0,k=p,A=p*2,N=-1;u==="RGB"&&(f=3,i=0,y=1,E=2,S=-1),l==="RGBA"?N=p*3:l==="RBG"?(z=0,A=p,k=p*2):l==="BGR"&&(A=0,k=p,z=p*2);for(let P=0;P<p;P++,i+=f,E+=f,y+=f,S+=f)w[z++]=(d[i]+h[0])/a[0],w[k++]=(d[y]+h[1])/a[1],w[A++]=(d[E]+h[2])/a[2],N!==-1&&S!==-1&&(w[N++]=(d[S]+h[3])/a[3]);return l==="RGBA"?new Zt("float32",w,[1,4,e,r]):new Zt("float32",w,[1,3,e,r])},zm=async(d,t)=>{let e=typeof HTMLImageElement<"u"&&d instanceof HTMLImageElement,r=typeof ImageData<"u"&&d instanceof ImageData,o=typeof ImageBitmap<"u"&&d instanceof ImageBitmap,a=typeof d=="string",h,u=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")},p=w=>typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||w instanceof OffscreenCanvas?w.getContext("2d"):null;if(e){let w=l();w.width=d.width,w.height=d.height;let f=p(w);if(f!=null){let i=d.height,y=d.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(i=t.resizedHeight,y=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=i,u.width=y}else u.tensorFormat="RGBA",u.height=i,u.width=y;f.drawImage(d,0,0),h=f.getImageData(0,0,y,i).data}else throw new Error("Can not access image data")}else if(r){let w,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(w=t.resizedHeight,f=t.resizedWidth):(w=d.height,f=d.width),t!==void 0&&(u=t),u.format="RGBA",u.height=w,u.width=f,t!==void 0){let i=l();i.width=f,i.height=w;let y=p(i);if(y!=null)y.putImageData(d,0,0),h=y.getImageData(0,0,f,w).data;else throw new Error("Can not access image data")}else h=d.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let w=l();w.width=d.width,w.height=d.height;let f=p(w);if(f!=null){let i=d.height,y=d.width;return f.drawImage(d,0,0,y,i),h=f.getImageData(0,0,y,i).data,u.height=i,u.width=y,gi(h,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((w,f)=>{let i=l(),y=p(i);if(!d||!y)return f();let E=new Image;E.crossOrigin="Anonymous",E.src=d,E.onload=()=>{i.width=E.width,i.height=E.height,y.drawImage(E,0,0,i.width,i.height);let S=y.getImageData(0,0,i.width,i.height);u.height=i.height,u.width=i.width,w(gi(S.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(h!==void 0)return gi(h,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Wm=(d,t)=>{let{width:e,height:r,download:o,dispose:a}=t,h=[1,r,e,4];return new Zt({location:"texture",type:"float32",texture:d,dims:h,download:o,dispose:a})},Gm=(d,t)=>{let{dataType:e,dims:r,download:o,dispose:a}=t;return new Zt({location:"gpu-buffer",type:e??"float32",gpuBuffer:d,dims:r,download:o,dispose:a})},Km=(d,t)=>{let{dataType:e,dims:r,download:o,dispose:a}=t;return new Zt({location:"ml-tensor",type:e??"float32",mlTensor:d,dims:r,download:o,dispose:a})},$m=(d,t,e)=>new Zt({location:"cpu-pinned",type:d,data:t,dims:e??[t.length]})});var as,Hs,Qm,Xm,Jm=jt(()=>{as=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Hs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Qm=!1,Xm=()=>{if(!Qm){Qm=!0;let d=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,e=globalThis.Float16Array,r=typeof e<"u"&&e.from;d&&(as.set("int64",BigInt64Array),Hs.set(BigInt64Array,"int64")),t&&(as.set("uint64",BigUint64Array),Hs.set(BigUint64Array,"uint64")),r?(as.set("float16",e),Hs.set(e,"float16")):as.set("float16",Uint16Array)}}});var qm,Ym,Zm=jt(()=>{zo();qm=d=>{let t=1;for(let e=0;e<d.length;e++){let r=d[e];if(typeof r!="number"||!Number.isSafeInteger(r))throw new TypeError(`dims[${e}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${e}] must be a non-negative integer, got: ${r}`);t*=r}return t},Ym=(d,t)=>{switch(d.location){case"cpu":return new Zt(d.type,d.data,t);case"cpu-pinned":return new Zt({location:"cpu-pinned",data:d.data,type:d.type,dims:t});case"texture":return new Zt({location:"texture",texture:d.texture,type:d.type,dims:t});case"gpu-buffer":return new Zt({location:"gpu-buffer",gpuBuffer:d.gpuBuffer,type:d.type,dims:t});case"ml-tensor":return new Zt({location:"ml-tensor",mlTensor:d.mlTensor,type:d.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${d.location} is not supported`)}}});var Zt,zo=jt(()=>{Um();Hm();Jm();Zm();Zt=class{constructor(t,e,r){Xm();let o,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,a=t.dims,t.location){case"cpu-pinned":{let u=as.get(o);if(!u)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" 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 u,l;if(typeof t=="string")if(o=t,l=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");u=e}else{let p=as.get(t);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&p===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${p.name} as data.`);t==="uint64"||t==="int64"?u=p.from(e,BigInt):u=p.from(e)}else if(e instanceof p)u=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")u=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&p!==Uint16Array)u=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${o} tensor's data must be type of ${p}`)}else if(l=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof t[0];if(p==="string")o="string",u=t;else if(p==="boolean")o="bool",u=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(t instanceof Uint8ClampedArray)o="uint8",u=Uint8Array.from(t);else{let p=Hs.get(t.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=p,u=t}if(l===void 0)l=[u.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=u,this.dataLocation="cpu"}let h=qm(a);if(this.cpuData&&h!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(h/2)===this.cpuData.length))throw new Error(`Tensor's size(${h}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=a,this.size=h}static async fromImage(t,e){return zm(t,e)}static fromTexture(t,e){return Wm(t,e)}static fromGpuBuffer(t,e){return Gm(t,e)}static fromMLTensor(t,e){return Km(t,e)}static fromPinnedBuffer(t,e,r){return $m(t,e,r)}toDataURL(t){return jm(this,t)}toImageData(t){return Vm(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;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ym(this,t)}}});var is,Mi=jt(()=>{zo();is=Zt});var eh,th,Wo,Go,Ko,$o,wi=jt(()=>{fi();eh=(d,t)=>{(typeof Gt.trace>"u"?!Gt.wasm.trace:!Gt.trace)||console.timeStamp(`${d}::ORT::${t}`)},th=(d,t)=>{let e=new Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let o=0;o<e.length;o++){if(r&&!e[o].includes("TRACE_FUNC")){let a=`FUNC_${d}::${e[o].trim().split(" ")[1]}`;t&&(a+=`::${t}`),eh("CPU",a);return}e[o].includes("TRACE_FUNC")&&(r=!0)}},Wo=d=>{(typeof Gt.trace>"u"?!Gt.wasm.trace:!Gt.trace)||th("BEGIN",d)},Go=d=>{(typeof Gt.trace>"u"?!Gt.wasm.trace:!Gt.trace)||th("END",d)},Ko=d=>{(typeof Gt.trace>"u"?!Gt.wasm.trace:!Gt.trace)||console.time(`ORT::${d}`)},$o=d=>{(typeof Gt.trace>"u"?!Gt.wasm.trace:!Gt.trace)||console.timeEnd(`ORT::${d}`)}});var Ho,rh=jt(()=>{hi();Mi();wi();Ho=class d{constructor(t){this.handler=t}async run(t,e,r){Wo(),Ko("InferenceSession.run");let o={},a={};if(typeof t!="object"||t===null||t instanceof is||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let h=!0;if(typeof e=="object"){if(e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(e instanceof is)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(e)){if(e.length===0)throw new TypeError("'fetches' cannot be an empty array.");h=!1;for(let p of e){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,w=Object.getOwnPropertyNames(e);for(let f of this.outputNames)if(w.indexOf(f)!==-1){let i=e[f];(i===null||i instanceof is)&&(p=!0,h=!1,o[f]=i)}if(p){if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else a=e}}else if(typeof e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(h)for(let p of this.outputNames)o[p]=null;let u=await this.handler.run(t,o,a),l={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let w=u[p];w instanceof is?l[p]=w:l[p]=new is(w.type,w.data,w.dims)}return $o("InferenceSession.run"),Go(),l}async release(){return this.handler.dispose()}static async create(t,e,r,o){Wo(),Ko("InferenceSession.create");let a,h={};if(typeof t=="string"){if(a=t,typeof e=="object"&&e!==null)h=e;else if(typeof e<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof e=="object"&&e!==null)h=e;else if(typeof e<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let w=t,f=0,i=t.byteLength;if(typeof e=="object"&&e!==null)h=e;else if(typeof e=="number"){if(f=e,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(i=t.byteLength-f,typeof r=="number"){if(i=r,!Number.isSafeInteger(i))throw new RangeError("'byteLength' must be an integer.");if(i<=0||f+i>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-f}].`);if(typeof o=="object"&&o!==null)h=o;else if(typeof o<"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 e<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(w,f,i)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,l]=await Dm(h),p=await u.createInferenceSessionHandler(a,l);return $o("InferenceSession.create"),Go(),new d(p)}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}}});var gf,sh=jt(()=>{rh();gf=Ho});var oh=jt(()=>{});var nh=jt(()=>{});var ah=jt(()=>{});var ih=jt(()=>{});var Ti={};ti(Ti,{InferenceSession:()=>gf,TRACE:()=>eh,TRACE_EVENT_BEGIN:()=>Ko,TRACE_EVENT_END:()=>$o,TRACE_FUNC_BEGIN:()=>Wo,TRACE_FUNC_END:()=>Go,Tensor:()=>is,env:()=>ff,registerBackend:()=>Sm});var lh=jt(()=>{Lm();Nm();sh();Mi();oh();nh();wi();ah();ih()});var dh={};ti(dh,{ASTFeatureExtractor:()=>Tf,ASTForAudioClassification:()=>vf,ASTModel:()=>Pf,ASTPreTrainedModel:()=>bf,AlbertForMaskedLM:()=>xf,AlbertForQuestionAnswering:()=>yf,AlbertForSequenceClassification:()=>Ef,AlbertModel:()=>Cf,AlbertPreTrainedModel:()=>kf,AlbertTokenizer:()=>Ff,ArceeForCausalLM:()=>Af,ArceeModel:()=>If,ArceePreTrainedModel:()=>Sf,AudioClassificationPipeline:()=>Df,AutoConfig:()=>Lf,AutoFeatureExtractor:()=>Of,AutoImageProcessor:()=>Rf,AutoModel:()=>Bf,AutoModelForAudioClassification:()=>Nf,AutoModelForAudioFrameClassification:()=>jf,AutoModelForAudioTextToText:()=>Vf,AutoModelForCTC:()=>Uf,AutoModelForCausalLM:()=>zf,AutoModelForDepthEstimation:()=>Wf,AutoModelForDocumentQuestionAnswering:()=>Gf,AutoModelForImageClassification:()=>Kf,AutoModelForImageFeatureExtraction:()=>$f,AutoModelForImageMatting:()=>Hf,AutoModelForImageSegmentation:()=>Qf,AutoModelForImageTextToText:()=>Xf,AutoModelForImageToImage:()=>Jf,AutoModelForMaskGeneration:()=>qf,AutoModelForMaskedLM:()=>Yf,AutoModelForNormalEstimation:()=>Zf,AutoModelForObjectDetection:()=>eg,AutoModelForPoseEstimation:()=>tg,AutoModelForQuestionAnswering:()=>rg,AutoModelForSemanticSegmentation:()=>sg,AutoModelForSeq2SeqLM:()=>og,AutoModelForSequenceClassification:()=>ng,AutoModelForSpeechSeq2Seq:()=>ag,AutoModelForTextToSpectrogram:()=>ig,AutoModelForTextToWaveform:()=>lg,AutoModelForTokenClassification:()=>cg,AutoModelForUniversalSegmentation:()=>dg,AutoModelForVision2Seq:()=>_g,AutoModelForXVector:()=>ug,AutoModelForZeroShotObjectDetection:()=>pg,AutoProcessor:()=>mg,AutoTokenizer:()=>hg,AutomaticSpeechRecognitionPipeline:()=>fg,BackgroundRemovalPipeline:()=>gg,BartForConditionalGeneration:()=>Mg,BartForSequenceClassification:()=>wg,BartModel:()=>Tg,BartPretrainedModel:()=>vg,BartTokenizer:()=>Pg,BaseModelOutput:()=>bg,BaseStreamer:()=>xg,BeitFeatureExtractor:()=>yg,BeitForImageClassification:()=>Eg,BeitModel:()=>Cg,BeitPreTrainedModel:()=>kg,BertForMaskedLM:()=>Fg,BertForQuestionAnswering:()=>Ag,BertForSequenceClassification:()=>Ig,BertForTokenClassification:()=>Sg,BertModel:()=>Dg,BertPreTrainedModel:()=>Lg,BertTokenizer:()=>Og,BitImageProcessor:()=>Rg,BlenderbotForConditionalGeneration:()=>Bg,BlenderbotModel:()=>Ng,BlenderbotPreTrainedModel:()=>jg,BlenderbotSmallForConditionalGeneration:()=>Vg,BlenderbotSmallModel:()=>Ug,BlenderbotSmallPreTrainedModel:()=>zg,BlenderbotSmallTokenizer:()=>Wg,BlenderbotTokenizer:()=>Gg,BloomForCausalLM:()=>Kg,BloomModel:()=>$g,BloomPreTrainedModel:()=>Hg,BloomTokenizer:()=>Qg,CLIPFeatureExtractor:()=>Xg,CLIPImageProcessor:()=>Jg,CLIPModel:()=>qg,CLIPPreTrainedModel:()=>Yg,CLIPSegForImageSegmentation:()=>Zg,CLIPSegModel:()=>eM,CLIPSegPreTrainedModel:()=>tM,CLIPTextModel:()=>rM,CLIPTextModelWithProjection:()=>sM,CLIPTokenizer:()=>oM,CLIPVisionModel:()=>nM,CLIPVisionModelWithProjection:()=>aM,CamembertForMaskedLM:()=>iM,CamembertForQuestionAnswering:()=>lM,CamembertForSequenceClassification:()=>cM,CamembertForTokenClassification:()=>dM,CamembertModel:()=>_M,CamembertPreTrainedModel:()=>uM,CamembertTokenizer:()=>pM,CausalLMOutput:()=>mM,CausalLMOutputWithPast:()=>hM,ChineseCLIPFeatureExtractor:()=>fM,ChineseCLIPModel:()=>gM,ChineseCLIPPreTrainedModel:()=>MM,ClapAudioModelWithProjection:()=>wM,ClapFeatureExtractor:()=>TM,ClapModel:()=>vM,ClapPreTrainedModel:()=>PM,ClapTextModelWithProjection:()=>bM,ClassifierFreeGuidanceLogitsProcessor:()=>xM,CodeGenForCausalLM:()=>yM,CodeGenModel:()=>EM,CodeGenPreTrainedModel:()=>CM,CodeGenTokenizer:()=>kM,CodeLlamaTokenizer:()=>FM,CohereForCausalLM:()=>AM,CohereModel:()=>IM,CoherePreTrainedModel:()=>SM,CohereTokenizer:()=>DM,ConvBertForMaskedLM:()=>LM,ConvBertForQuestionAnswering:()=>OM,ConvBertForSequenceClassification:()=>RM,ConvBertForTokenClassification:()=>BM,ConvBertModel:()=>NM,ConvBertPreTrainedModel:()=>jM,ConvBertTokenizer:()=>VM,ConvNextFeatureExtractor:()=>UM,ConvNextForImageClassification:()=>zM,ConvNextImageProcessor:()=>WM,ConvNextModel:()=>GM,ConvNextPreTrainedModel:()=>KM,ConvNextV2ForImageClassification:()=>$M,ConvNextV2Model:()=>HM,ConvNextV2PreTrainedModel:()=>QM,DFineForObjectDetection:()=>XM,DFineModel:()=>JM,DFinePreTrainedModel:()=>qM,DINOv3ConvNextModel:()=>YM,DINOv3ConvNextPreTrainedModel:()=>ZM,DINOv3ViTImageProcessor:()=>ew,DINOv3ViTModel:()=>tw,DINOv3ViTPreTrainedModel:()=>rw,DPTFeatureExtractor:()=>sw,DPTForDepthEstimation:()=>ow,DPTImageProcessor:()=>nw,DPTModel:()=>aw,DPTPreTrainedModel:()=>iw,DacDecoderModel:()=>lw,DacDecoderOutput:()=>cw,DacEncoderModel:()=>dw,DacEncoderOutput:()=>_w,DacFeatureExtractor:()=>uw,DacModel:()=>pw,DacPreTrainedModel:()=>mw,DataTypeMap:()=>hw,DebertaForMaskedLM:()=>fw,DebertaForQuestionAnswering:()=>gw,DebertaForSequenceClassification:()=>Mw,DebertaForTokenClassification:()=>ww,DebertaModel:()=>Tw,DebertaPreTrainedModel:()=>vw,DebertaTokenizer:()=>Pw,DebertaV2ForMaskedLM:()=>bw,DebertaV2ForQuestionAnswering:()=>xw,DebertaV2ForSequenceClassification:()=>yw,DebertaV2ForTokenClassification:()=>Ew,DebertaV2Model:()=>Cw,DebertaV2PreTrainedModel:()=>kw,DebertaV2Tokenizer:()=>Fw,DecisionTransformerModel:()=>Aw,DecisionTransformerPreTrainedModel:()=>Iw,DeiTFeatureExtractor:()=>Sw,DeiTForImageClassification:()=>Dw,DeiTImageProcessor:()=>Lw,DeiTModel:()=>Ow,DeiTPreTrainedModel:()=>Rw,DepthAnythingForDepthEstimation:()=>Bw,DepthAnythingPreTrainedModel:()=>Nw,DepthEstimationPipeline:()=>jw,DepthProForDepthEstimation:()=>Vw,DepthProPreTrainedModel:()=>Uw,DetrFeatureExtractor:()=>zw,DetrForObjectDetection:()=>Ww,DetrForSegmentation:()=>Gw,DetrImageProcessor:()=>Kw,DetrModel:()=>$w,DetrObjectDetectionOutput:()=>Hw,DetrPreTrainedModel:()=>Qw,DetrSegmentationOutput:()=>Xw,Dinov2ForImageClassification:()=>Jw,Dinov2Model:()=>qw,Dinov2PreTrainedModel:()=>Yw,Dinov2WithRegistersForImageClassification:()=>Zw,Dinov2WithRegistersModel:()=>eT,Dinov2WithRegistersPreTrainedModel:()=>tT,DistilBertForMaskedLM:()=>rT,DistilBertForQuestionAnswering:()=>sT,DistilBertForSequenceClassification:()=>oT,DistilBertForTokenClassification:()=>nT,DistilBertModel:()=>aT,DistilBertPreTrainedModel:()=>iT,DistilBertTokenizer:()=>lT,DocumentQuestionAnsweringPipeline:()=>cT,DonutFeatureExtractor:()=>dT,DonutImageProcessor:()=>_T,DonutSwinModel:()=>uT,DonutSwinPreTrainedModel:()=>pT,EdgeTamModel:()=>mT,EfficientNetForImageClassification:()=>hT,EfficientNetImageProcessor:()=>fT,EfficientNetModel:()=>gT,EfficientNetPreTrainedModel:()=>MT,ElectraForMaskedLM:()=>wT,ElectraForQuestionAnswering:()=>TT,ElectraForSequenceClassification:()=>vT,ElectraForTokenClassification:()=>PT,ElectraModel:()=>bT,ElectraPreTrainedModel:()=>xT,ElectraTokenizer:()=>yT,EncodecFeatureExtractor:()=>ET,EosTokenCriteria:()=>CT,Ernie4_5ForCausalLM:()=>kT,Ernie4_5Model:()=>FT,Ernie4_5PreTrainedModel:()=>AT,EsmForMaskedLM:()=>IT,EsmForSequenceClassification:()=>ST,EsmForTokenClassification:()=>DT,EsmModel:()=>LT,EsmPreTrainedModel:()=>OT,EsmTokenizer:()=>RT,ExaoneForCausalLM:()=>BT,ExaoneModel:()=>NT,ExaonePreTrainedModel:()=>jT,FFT:()=>VT,FalconForCausalLM:()=>UT,FalconModel:()=>zT,FalconPreTrainedModel:()=>WT,FalconTokenizer:()=>GT,FastViTForImageClassification:()=>KT,FastViTModel:()=>$T,FastViTPreTrainedModel:()=>HT,FeatureExtractionPipeline:()=>QT,FeatureExtractor:()=>XT,FillMaskPipeline:()=>JT,Florence2ForConditionalGeneration:()=>qT,Florence2PreTrainedModel:()=>YT,Florence2Processor:()=>ZT,ForcedBOSTokenLogitsProcessor:()=>ev,ForcedEOSTokenLogitsProcessor:()=>tv,GLPNFeatureExtractor:()=>rv,GLPNForDepthEstimation:()=>sv,GLPNModel:()=>ov,GLPNPreTrainedModel:()=>nv,GPT2LMHeadModel:()=>av,GPT2Model:()=>iv,GPT2PreTrainedModel:()=>lv,GPT2Tokenizer:()=>cv,GPTBigCodeForCausalLM:()=>dv,GPTBigCodeModel:()=>_v,GPTBigCodePreTrainedModel:()=>uv,GPTJForCausalLM:()=>pv,GPTJModel:()=>mv,GPTJPreTrainedModel:()=>hv,GPTNeoForCausalLM:()=>fv,GPTNeoModel:()=>gv,GPTNeoPreTrainedModel:()=>Mv,GPTNeoXForCausalLM:()=>wv,GPTNeoXModel:()=>Tv,GPTNeoXPreTrainedModel:()=>vv,GPTNeoXTokenizer:()=>Pv,Gemma2ForCausalLM:()=>bv,Gemma2Model:()=>xv,Gemma2PreTrainedModel:()=>yv,Gemma3ForCausalLM:()=>Ev,Gemma3Model:()=>Cv,Gemma3PreTrainedModel:()=>kv,Gemma3nAudioFeatureExtractor:()=>Fv,Gemma3nForConditionalGeneration:()=>Av,Gemma3nPreTrainedModel:()=>Iv,Gemma3nProcessor:()=>Sv,GemmaForCausalLM:()=>Dv,GemmaModel:()=>Lv,GemmaPreTrainedModel:()=>Ov,GemmaTokenizer:()=>Rv,GlmForCausalLM:()=>Bv,GlmModel:()=>Nv,GlmPreTrainedModel:()=>jv,GraniteForCausalLM:()=>Vv,GraniteModel:()=>Uv,GraniteMoeHybridForCausalLM:()=>zv,GraniteMoeHybridModel:()=>Wv,GraniteMoeHybridPreTrainedModel:()=>Gv,GranitePreTrainedModel:()=>Kv,Grok1Tokenizer:()=>$v,GroundingDinoForObjectDetection:()=>Hv,GroundingDinoImageProcessor:()=>Qv,GroundingDinoPreTrainedModel:()=>Xv,GroundingDinoProcessor:()=>Jv,GroupViTModel:()=>qv,GroupViTPreTrainedModel:()=>Yv,HeliumForCausalLM:()=>Zv,HeliumModel:()=>eP,HeliumPreTrainedModel:()=>tP,HerbertTokenizer:()=>rP,HieraForImageClassification:()=>sP,HieraModel:()=>oP,HieraPreTrainedModel:()=>nP,HubertForCTC:()=>aP,HubertForSequenceClassification:()=>iP,HubertModel:()=>lP,HubertPreTrainedModel:()=>cP,IJepaForImageClassification:()=>dP,IJepaModel:()=>_P,IJepaPreTrainedModel:()=>uP,Idefics3ForConditionalGeneration:()=>pP,Idefics3ImageProcessor:()=>mP,Idefics3PreTrainedModel:()=>hP,Idefics3Processor:()=>fP,ImageClassificationPipeline:()=>gP,ImageFeatureExtractionPipeline:()=>MP,ImageFeatureExtractor:()=>wP,ImageMattingOutput:()=>TP,ImageProcessor:()=>vP,ImageSegmentationPipeline:()=>PP,ImageToImagePipeline:()=>bP,ImageToTextPipeline:()=>xP,InterruptableStoppingCriteria:()=>yP,JAISLMHeadModel:()=>EP,JAISModel:()=>CP,JAISPreTrainedModel:()=>kP,JinaCLIPImageProcessor:()=>FP,JinaCLIPModel:()=>AP,JinaCLIPPreTrainedModel:()=>IP,JinaCLIPProcessor:()=>SP,JinaCLIPTextModel:()=>DP,JinaCLIPVisionModel:()=>LP,Lfm2ForCausalLM:()=>OP,Lfm2Model:()=>RP,Lfm2PreTrainedModel:()=>BP,LiteWhisperForConditionalGeneration:()=>NP,Llama4ForCausalLM:()=>jP,Llama4PreTrainedModel:()=>VP,LlamaForCausalLM:()=>UP,LlamaModel:()=>zP,LlamaPreTrainedModel:()=>WP,LlamaTokenizer:()=>GP,LlavaForConditionalGeneration:()=>KP,LlavaOnevisionForConditionalGeneration:()=>$P,LlavaOnevisionImageProcessor:()=>HP,LlavaPreTrainedModel:()=>QP,LlavaProcessor:()=>XP,LlavaQwen2ForCausalLM:()=>JP,LogitsProcessor:()=>qP,LogitsProcessorList:()=>YP,LogitsWarper:()=>ZP,LongT5ForConditionalGeneration:()=>eb,LongT5Model:()=>tb,LongT5PreTrainedModel:()=>rb,M2M100ForConditionalGeneration:()=>sb,M2M100Model:()=>ob,M2M100PreTrainedModel:()=>nb,M2M100Tokenizer:()=>ab,MBart50Tokenizer:()=>ib,MBartForCausalLM:()=>lb,MBartForConditionalGeneration:()=>cb,MBartForSequenceClassification:()=>db,MBartModel:()=>_b,MBartPreTrainedModel:()=>ub,MBartTokenizer:()=>pb,MPNetForMaskedLM:()=>mb,MPNetForQuestionAnswering:()=>hb,MPNetForSequenceClassification:()=>fb,MPNetForTokenClassification:()=>gb,MPNetModel:()=>Mb,MPNetPreTrainedModel:()=>wb,MPNetTokenizer:()=>Tb,MT5ForConditionalGeneration:()=>vb,MT5Model:()=>Pb,MT5PreTrainedModel:()=>bb,MarianMTModel:()=>xb,MarianModel:()=>yb,MarianPreTrainedModel:()=>Eb,MarianTokenizer:()=>Cb,Mask2FormerImageProcessor:()=>kb,MaskFormerFeatureExtractor:()=>Fb,MaskFormerForInstanceSegmentation:()=>Ab,MaskFormerImageProcessor:()=>Ib,MaskFormerModel:()=>Sb,MaskFormerPreTrainedModel:()=>Db,MaskedLMOutput:()=>Lb,MaxLengthCriteria:()=>Ob,Metric3DForDepthEstimation:()=>Rb,Metric3DPreTrainedModel:()=>Bb,Metric3Dv2ForDepthEstimation:()=>Nb,Metric3Dv2PreTrainedModel:()=>jb,MgpstrForSceneTextRecognition:()=>Vb,MgpstrModelOutput:()=>Ub,MgpstrPreTrainedModel:()=>zb,MgpstrProcessor:()=>Wb,MgpstrTokenizer:()=>Gb,MimiDecoderModel:()=>Kb,MimiDecoderOutput:()=>$b,MimiEncoderModel:()=>Hb,MimiEncoderOutput:()=>Qb,MimiModel:()=>Xb,MimiPreTrainedModel:()=>Jb,MinLengthLogitsProcessor:()=>qb,MinNewTokensLengthLogitsProcessor:()=>Yb,Ministral3ForCausalLM:()=>Zb,Ministral3Model:()=>ex,Ministral3PreTrainedModel:()=>tx,MinistralForCausalLM:()=>rx,MinistralModel:()=>sx,MinistralPreTrainedModel:()=>ox,Mistral3ForConditionalGeneration:()=>nx,MistralForCausalLM:()=>ax,MistralModel:()=>ix,MistralPreTrainedModel:()=>lx,MobileBertForMaskedLM:()=>cx,MobileBertForQuestionAnswering:()=>dx,MobileBertForSequenceClassification:()=>_x,MobileBertModel:()=>ux,MobileBertPreTrainedModel:()=>px,MobileBertTokenizer:()=>mx,MobileLLMForCausalLM:()=>hx,MobileLLMModel:()=>fx,MobileLLMPreTrainedModel:()=>gx,MobileNetV1FeatureExtractor:()=>Mx,MobileNetV1ForImageClassification:()=>wx,MobileNetV1ForSemanticSegmentation:()=>Tx,MobileNetV1ImageProcessor:()=>vx,MobileNetV1Model:()=>Px,MobileNetV1PreTrainedModel:()=>bx,MobileNetV2FeatureExtractor:()=>xx,MobileNetV2ForImageClassification:()=>yx,MobileNetV2ForSemanticSegmentation:()=>Ex,MobileNetV2ImageProcessor:()=>Cx,MobileNetV2Model:()=>kx,MobileNetV2PreTrainedModel:()=>Fx,MobileNetV3FeatureExtractor:()=>Ax,MobileNetV3ForImageClassification:()=>Ix,MobileNetV3ForSemanticSegmentation:()=>Sx,MobileNetV3ImageProcessor:()=>Dx,MobileNetV3Model:()=>Lx,MobileNetV3PreTrainedModel:()=>Ox,MobileNetV4FeatureExtractor:()=>Rx,MobileNetV4ForImageClassification:()=>Bx,MobileNetV4ForSemanticSegmentation:()=>Nx,MobileNetV4ImageProcessor:()=>jx,MobileNetV4Model:()=>Vx,MobileNetV4PreTrainedModel:()=>Ux,MobileViTFeatureExtractor:()=>zx,MobileViTForImageClassification:()=>Wx,MobileViTImageProcessor:()=>Gx,MobileViTModel:()=>Kx,MobileViTPreTrainedModel:()=>$x,MobileViTV2ForImageClassification:()=>Hx,MobileViTV2Model:()=>Qx,MobileViTV2PreTrainedModel:()=>Xx,ModelOutput:()=>Jx,ModernBertDecoderForCausalLM:()=>qx,ModernBertDecoderModel:()=>Yx,ModernBertDecoderPreTrainedModel:()=>Zx,ModernBertForMaskedLM:()=>ey,ModernBertForSequenceClassification:()=>ty,ModernBertForTokenClassification:()=>ry,ModernBertModel:()=>sy,ModernBertPreTrainedModel:()=>oy,Moondream1ForConditionalGeneration:()=>ny,MoonshineFeatureExtractor:()=>ay,MoonshineForConditionalGeneration:()=>iy,MoonshineModel:()=>ly,MoonshinePreTrainedModel:()=>cy,MoonshineProcessor:()=>dy,MptForCausalLM:()=>_y,MptModel:()=>uy,MptPreTrainedModel:()=>py,MultiModalityCausalLM:()=>my,MultiModalityPreTrainedModel:()=>hy,MusicgenForCausalLM:()=>fy,MusicgenForConditionalGeneration:()=>gy,MusicgenModel:()=>My,MusicgenPreTrainedModel:()=>wy,NanoChatForCausalLM:()=>Ty,NanoChatModel:()=>vy,NanoChatPreTrainedModel:()=>Py,NeoBertForMaskedLM:()=>by,NeoBertForQuestionAnswering:()=>xy,NeoBertForSequenceClassification:()=>yy,NeoBertForTokenClassification:()=>Ey,NeoBertModel:()=>Cy,NeoBertPreTrainedModel:()=>ky,NllbTokenizer:()=>Fy,NoBadWordsLogitsProcessor:()=>Ay,NoRepeatNGramLogitsProcessor:()=>Iy,NomicBertModel:()=>Sy,NomicBertPreTrainedModel:()=>Dy,NougatImageProcessor:()=>Ly,NougatTokenizer:()=>Oy,OPTForCausalLM:()=>Ry,OPTModel:()=>By,OPTPreTrainedModel:()=>Ny,ObjectDetectionPipeline:()=>jy,Olmo2ForCausalLM:()=>Vy,Olmo2Model:()=>Uy,Olmo2PreTrainedModel:()=>zy,OlmoForCausalLM:()=>Wy,OlmoModel:()=>Gy,OlmoPreTrainedModel:()=>Ky,OpenELMForCausalLM:()=>$y,OpenELMModel:()=>Hy,OpenELMPreTrainedModel:()=>Qy,OwlViTFeatureExtractor:()=>Xy,OwlViTForObjectDetection:()=>Jy,OwlViTImageProcessor:()=>qy,OwlViTModel:()=>Yy,OwlViTPreTrainedModel:()=>Zy,OwlViTProcessor:()=>eE,Owlv2ForObjectDetection:()=>tE,Owlv2ImageProcessor:()=>rE,Owlv2Model:()=>sE,Owlv2PreTrainedModel:()=>oE,PaliGemmaForConditionalGeneration:()=>nE,PaliGemmaPreTrainedModel:()=>aE,PaliGemmaProcessor:()=>iE,ParakeetFeatureExtractor:()=>lE,ParakeetForCTC:()=>cE,ParakeetPreTrainedModel:()=>dE,PatchTSMixerForPrediction:()=>_E,PatchTSMixerModel:()=>uE,PatchTSMixerPreTrainedModel:()=>pE,PatchTSTForPrediction:()=>mE,PatchTSTModel:()=>hE,PatchTSTPreTrainedModel:()=>fE,Phi3ForCausalLM:()=>gE,Phi3Model:()=>ME,Phi3PreTrainedModel:()=>wE,Phi3VForCausalLM:()=>TE,Phi3VImageProcessor:()=>vE,Phi3VPreTrainedModel:()=>PE,Phi3VProcessor:()=>bE,PhiForCausalLM:()=>xE,PhiModel:()=>yE,PhiPreTrainedModel:()=>EE,Pipeline:()=>CE,PixtralImageProcessor:()=>kE,PixtralProcessor:()=>FE,PreTrainedModel:()=>AE,PreTrainedTokenizer:()=>IE,PretrainedConfig:()=>SE,PretrainedMixin:()=>DE,Processor:()=>LE,PvtForImageClassification:()=>OE,PvtImageProcessor:()=>RE,PvtModel:()=>BE,PvtPreTrainedModel:()=>NE,PyAnnoteFeatureExtractor:()=>jE,PyAnnoteForAudioFrameClassification:()=>VE,PyAnnoteModel:()=>UE,PyAnnotePreTrainedModel:()=>zE,PyAnnoteProcessor:()=>WE,QuestionAnsweringModelOutput:()=>GE,QuestionAnsweringPipeline:()=>KE,Qwen2ForCausalLM:()=>$E,Qwen2Model:()=>HE,Qwen2PreTrainedModel:()=>QE,Qwen2Tokenizer:()=>XE,Qwen2VLForConditionalGeneration:()=>JE,Qwen2VLImageProcessor:()=>qE,Qwen2VLPreTrainedModel:()=>YE,Qwen2VLProcessor:()=>ZE,Qwen3ForCausalLM:()=>eC,Qwen3Model:()=>tC,Qwen3PreTrainedModel:()=>rC,RFDetrForObjectDetection:()=>sC,RFDetrModel:()=>oC,RFDetrObjectDetectionOutput:()=>nC,RFDetrPreTrainedModel:()=>aC,RTDetrForObjectDetection:()=>iC,RTDetrImageProcessor:()=>lC,RTDetrModel:()=>cC,RTDetrObjectDetectionOutput:()=>dC,RTDetrPreTrainedModel:()=>_C,RTDetrV2ForObjectDetection:()=>uC,RTDetrV2Model:()=>pC,RTDetrV2ObjectDetectionOutput:()=>mC,RTDetrV2PreTrainedModel:()=>hC,RawAudio:()=>fC,RawImage:()=>gC,RawVideo:()=>MC,RawVideoFrame:()=>wC,RepetitionPenaltyLogitsProcessor:()=>TC,ResNetForImageClassification:()=>vC,ResNetModel:()=>PC,ResNetPreTrainedModel:()=>bC,RoFormerForMaskedLM:()=>xC,RoFormerForQuestionAnswering:()=>yC,RoFormerForSequenceClassification:()=>EC,RoFormerForTokenClassification:()=>CC,RoFormerModel:()=>kC,RoFormerPreTrainedModel:()=>FC,RoFormerTokenizer:()=>AC,RobertaForMaskedLM:()=>IC,RobertaForQuestionAnswering:()=>SC,RobertaForSequenceClassification:()=>DC,RobertaForTokenClassification:()=>LC,RobertaModel:()=>OC,RobertaPreTrainedModel:()=>RC,RobertaTokenizer:()=>BC,Sam2ImageProcessor:()=>NC,Sam2ImageSegmentationOutput:()=>jC,Sam2Model:()=>VC,Sam2PreTrainedModel:()=>UC,Sam2Processor:()=>zC,Sam2VideoProcessor:()=>WC,Sam3ImageProcessor:()=>GC,Sam3TrackerModel:()=>KC,SamImageProcessor:()=>$C,SamImageSegmentationOutput:()=>HC,SamModel:()=>QC,SamPreTrainedModel:()=>XC,SamProcessor:()=>JC,SapiensForDepthEstimation:()=>qC,SapiensForNormalEstimation:()=>YC,SapiensForSemanticSegmentation:()=>ZC,SapiensPreTrainedModel:()=>ek,SeamlessM4TFeatureExtractor:()=>tk,SegformerFeatureExtractor:()=>rk,SegformerForImageClassification:()=>sk,SegformerForSemanticSegmentation:()=>ok,SegformerImageProcessor:()=>nk,SegformerModel:()=>ak,SegformerPreTrainedModel:()=>ik,Seq2SeqLMOutput:()=>lk,SequenceClassifierOutput:()=>ck,SiglipImageProcessor:()=>dk,SiglipModel:()=>_k,SiglipPreTrainedModel:()=>uk,SiglipTextModel:()=>pk,SiglipTokenizer:()=>mk,SiglipVisionModel:()=>hk,SmolLM3ForCausalLM:()=>fk,SmolLM3Model:()=>gk,SmolLM3PreTrainedModel:()=>Mk,SmolVLMForConditionalGeneration:()=>wk,SmolVLMImageProcessor:()=>Tk,SmolVLMProcessor:()=>vk,SnacDecoderModel:()=>Pk,SnacEncoderModel:()=>bk,SnacFeatureExtractor:()=>xk,SnacModel:()=>yk,SnacPreTrainedModel:()=>Ek,SpeechT5FeatureExtractor:()=>Ck,SpeechT5ForSpeechToText:()=>kk,SpeechT5ForTextToSpeech:()=>Fk,SpeechT5HifiGan:()=>Ak,SpeechT5Model:()=>Ik,SpeechT5PreTrainedModel:()=>Sk,SpeechT5Processor:()=>Dk,SpeechT5Tokenizer:()=>Lk,SqueezeBertForMaskedLM:()=>Ok,SqueezeBertForQuestionAnswering:()=>Rk,SqueezeBertForSequenceClassification:()=>Bk,SqueezeBertModel:()=>Nk,SqueezeBertPreTrainedModel:()=>jk,SqueezeBertTokenizer:()=>Vk,StableLmForCausalLM:()=>Uk,StableLmModel:()=>zk,StableLmPreTrainedModel:()=>Wk,Starcoder2ForCausalLM:()=>Gk,Starcoder2Model:()=>Kk,Starcoder2PreTrainedModel:()=>$k,StoppingCriteria:()=>Hk,StoppingCriteriaList:()=>Qk,StyleTextToSpeech2Model:()=>Xk,StyleTextToSpeech2PreTrainedModel:()=>Jk,SummarizationPipeline:()=>qk,SupertonicForConditionalGeneration:()=>Yk,SupertonicPreTrainedModel:()=>Zk,SuppressTokensAtBeginLogitsProcessor:()=>eF,Swin2SRForImageSuperResolution:()=>tF,Swin2SRImageProcessor:()=>rF,Swin2SRModel:()=>sF,Swin2SRPreTrainedModel:()=>oF,SwinForImageClassification:()=>nF,SwinForSemanticSegmentation:()=>aF,SwinModel:()=>iF,SwinPreTrainedModel:()=>lF,T5ForConditionalGeneration:()=>cF,T5Model:()=>dF,T5PreTrainedModel:()=>_F,T5Tokenizer:()=>uF,TableTransformerForObjectDetection:()=>pF,TableTransformerModel:()=>mF,TableTransformerObjectDetectionOutput:()=>hF,TableTransformerPreTrainedModel:()=>fF,TemperatureLogitsWarper:()=>gF,Tensor:()=>MF,Text2TextGenerationPipeline:()=>wF,TextClassificationPipeline:()=>TF,TextGenerationPipeline:()=>vF,TextStreamer:()=>PF,TextToAudioPipeline:()=>bF,TokenClassificationPipeline:()=>xF,TokenClassifierOutput:()=>yF,TokenizerModel:()=>EF,TopKLogitsWarper:()=>CF,TopPLogitsWarper:()=>kF,TrOCRForCausalLM:()=>FF,TrOCRPreTrainedModel:()=>AF,TranslationPipeline:()=>IF,UltravoxModel:()=>SF,UltravoxPreTrainedModel:()=>DF,UltravoxProcessor:()=>LF,UniSpeechForCTC:()=>OF,UniSpeechForSequenceClassification:()=>RF,UniSpeechModel:()=>BF,UniSpeechPreTrainedModel:()=>NF,UniSpeechSatForAudioFrameClassification:()=>jF,UniSpeechSatForCTC:()=>VF,UniSpeechSatForSequenceClassification:()=>UF,UniSpeechSatModel:()=>zF,UniSpeechSatPreTrainedModel:()=>WF,VLChatProcessor:()=>GF,VLMImageProcessor:()=>KF,VaultGemmaForCausalLM:()=>$F,VaultGemmaModel:()=>HF,VaultGemmaPreTrainedModel:()=>QF,ViTFeatureExtractor:()=>XF,ViTForImageClassification:()=>JF,ViTImageProcessor:()=>qF,ViTMAEModel:()=>YF,ViTMAEPreTrainedModel:()=>ZF,ViTMSNForImageClassification:()=>eA,ViTMSNModel:()=>tA,ViTMSNPreTrainedModel:()=>rA,ViTModel:()=>sA,ViTPreTrainedModel:()=>oA,VisionEncoderDecoderModel:()=>nA,VitMatteForImageMatting:()=>aA,VitMatteImageProcessor:()=>iA,VitMattePreTrainedModel:()=>lA,VitPoseForPoseEstimation:()=>cA,VitPoseImageProcessor:()=>dA,VitPosePreTrainedModel:()=>_A,VitsModel:()=>uA,VitsModelOutput:()=>pA,VitsPreTrainedModel:()=>mA,VitsTokenizer:()=>hA,VoxtralForConditionalGeneration:()=>fA,VoxtralProcessor:()=>gA,Wav2Vec2BertForCTC:()=>MA,Wav2Vec2BertForSequenceClassification:()=>wA,Wav2Vec2BertModel:()=>TA,Wav2Vec2BertPreTrainedModel:()=>vA,Wav2Vec2CTCTokenizer:()=>PA,Wav2Vec2FeatureExtractor:()=>bA,Wav2Vec2ForAudioFrameClassification:()=>xA,Wav2Vec2ForCTC:()=>yA,Wav2Vec2ForSequenceClassification:()=>EA,Wav2Vec2Model:()=>CA,Wav2Vec2PreTrainedModel:()=>kA,Wav2Vec2Processor:()=>FA,Wav2Vec2ProcessorWithLM:()=>AA,WavLMForAudioFrameClassification:()=>IA,WavLMForCTC:()=>SA,WavLMForSequenceClassification:()=>DA,WavLMForXVector:()=>LA,WavLMModel:()=>OA,WavLMPreTrainedModel:()=>RA,WeSpeakerFeatureExtractor:()=>BA,WeSpeakerResNetModel:()=>NA,WeSpeakerResNetPreTrainedModel:()=>jA,WhisperFeatureExtractor:()=>VA,WhisperForConditionalGeneration:()=>UA,WhisperModel:()=>zA,WhisperPreTrainedModel:()=>WA,WhisperProcessor:()=>GA,WhisperTextStreamer:()=>KA,WhisperTimeStampLogitsProcessor:()=>$A,WhisperTokenizer:()=>HA,XLMForQuestionAnswering:()=>QA,XLMForSequenceClassification:()=>XA,XLMForTokenClassification:()=>JA,XLMModel:()=>qA,XLMPreTrainedModel:()=>YA,XLMRobertaForMaskedLM:()=>ZA,XLMRobertaForQuestionAnswering:()=>eI,XLMRobertaForSequenceClassification:()=>tI,XLMRobertaForTokenClassification:()=>rI,XLMRobertaModel:()=>sI,XLMRobertaPreTrainedModel:()=>oI,XLMRobertaTokenizer:()=>nI,XLMTokenizer:()=>aI,XLMWithLMHeadModel:()=>iI,XVectorOutput:()=>lI,YolosFeatureExtractor:()=>cI,YolosForObjectDetection:()=>dI,YolosImageProcessor:()=>_I,YolosModel:()=>uI,YolosObjectDetectionOutput:()=>pI,YolosPreTrainedModel:()=>mI,ZeroShotAudioClassificationPipeline:()=>hI,ZeroShotClassificationPipeline:()=>fI,ZeroShotImageClassificationPipeline:()=>gI,ZeroShotObjectDetectionPipeline:()=>MI,bankers_round:()=>wI,cat:()=>TI,cos_sim:()=>vI,dot:()=>PI,dynamic_time_warping:()=>bI,env:()=>xI,full:()=>yI,full_like:()=>EI,getCacheShapes:()=>CI,hamming:()=>kI,hanning:()=>FI,interpolate:()=>AI,interpolate_4d:()=>II,interpolate_data:()=>SI,is_chinese_char:()=>DI,layer_norm:()=>LI,load_image:()=>OI,load_video:()=>RI,log_softmax:()=>BI,magnitude:()=>NI,matmul:()=>jI,max:()=>VI,mean:()=>UI,mean_pooling:()=>zI,medianFilter:()=>WI,mel_filter_bank:()=>GI,min:()=>KI,ones:()=>$I,ones_like:()=>HI,permute:()=>QI,permute_data:()=>XI,pipeline:()=>JI,quantize_embeddings:()=>qI,rand:()=>YI,randn:()=>ZI,read_audio:()=>eS,rfft:()=>tS,round:()=>rS,slice:()=>sS,softmax:()=>oS,spectrogram:()=>nS,stack:()=>aS,std_mean:()=>iS,topk:()=>lS,window_function:()=>cS,zeros:()=>dS,zeros_like:()=>_S});function wt(d){var t=ch[d];if(t!==void 0)return t.exports;var e=ch[d]={exports:{}};return wf[d](e,e.exports,wt),e.exports}var Mf,uS,wf,ch,s,Tf,vf,Pf,bf,xf,yf,Ef,Cf,kf,Ff,Af,If,Sf,Df,Lf,Of,Rf,Bf,Nf,jf,Vf,Uf,zf,Wf,Gf,Kf,$f,Hf,Qf,Xf,Jf,qf,Yf,Zf,eg,tg,rg,sg,og,ng,ag,ig,lg,cg,dg,_g,ug,pg,mg,hg,fg,gg,Mg,wg,Tg,vg,Pg,bg,xg,yg,Eg,Cg,kg,Fg,Ag,Ig,Sg,Dg,Lg,Og,Rg,Bg,Ng,jg,Vg,Ug,zg,Wg,Gg,Kg,$g,Hg,Qg,Xg,Jg,qg,Yg,Zg,eM,tM,rM,sM,oM,nM,aM,iM,lM,cM,dM,_M,uM,pM,mM,hM,fM,gM,MM,wM,TM,vM,PM,bM,xM,yM,EM,CM,kM,FM,AM,IM,SM,DM,LM,OM,RM,BM,NM,jM,VM,UM,zM,WM,GM,KM,$M,HM,QM,XM,JM,qM,YM,ZM,ew,tw,rw,sw,ow,nw,aw,iw,lw,cw,dw,_w,uw,pw,mw,hw,fw,gw,Mw,ww,Tw,vw,Pw,bw,xw,yw,Ew,Cw,kw,Fw,Aw,Iw,Sw,Dw,Lw,Ow,Rw,Bw,Nw,jw,Vw,Uw,zw,Ww,Gw,Kw,$w,Hw,Qw,Xw,Jw,qw,Yw,Zw,eT,tT,rT,sT,oT,nT,aT,iT,lT,cT,dT,_T,uT,pT,mT,hT,fT,gT,MT,wT,TT,vT,PT,bT,xT,yT,ET,CT,kT,FT,AT,IT,ST,DT,LT,OT,RT,BT,NT,jT,VT,UT,zT,WT,GT,KT,$T,HT,QT,XT,JT,qT,YT,ZT,ev,tv,rv,sv,ov,nv,av,iv,lv,cv,dv,_v,uv,pv,mv,hv,fv,gv,Mv,wv,Tv,vv,Pv,bv,xv,yv,Ev,Cv,kv,Fv,Av,Iv,Sv,Dv,Lv,Ov,Rv,Bv,Nv,jv,Vv,Uv,zv,Wv,Gv,Kv,$v,Hv,Qv,Xv,Jv,qv,Yv,Zv,eP,tP,rP,sP,oP,nP,aP,iP,lP,cP,dP,_P,uP,pP,mP,hP,fP,gP,MP,wP,TP,vP,PP,bP,xP,yP,EP,CP,kP,FP,AP,IP,SP,DP,LP,OP,RP,BP,NP,jP,VP,UP,zP,WP,GP,KP,$P,HP,QP,XP,JP,qP,YP,ZP,eb,tb,rb,sb,ob,nb,ab,ib,lb,cb,db,_b,ub,pb,mb,hb,fb,gb,Mb,wb,Tb,vb,Pb,bb,xb,yb,Eb,Cb,kb,Fb,Ab,Ib,Sb,Db,Lb,Ob,Rb,Bb,Nb,jb,Vb,Ub,zb,Wb,Gb,Kb,$b,Hb,Qb,Xb,Jb,qb,Yb,Zb,ex,tx,rx,sx,ox,nx,ax,ix,lx,cx,dx,_x,ux,px,mx,hx,fx,gx,Mx,wx,Tx,vx,Px,bx,xx,yx,Ex,Cx,kx,Fx,Ax,Ix,Sx,Dx,Lx,Ox,Rx,Bx,Nx,jx,Vx,Ux,zx,Wx,Gx,Kx,$x,Hx,Qx,Xx,Jx,qx,Yx,Zx,ey,ty,ry,sy,oy,ny,ay,iy,ly,cy,dy,_y,uy,py,my,hy,fy,gy,My,wy,Ty,vy,Py,by,xy,yy,Ey,Cy,ky,Fy,Ay,Iy,Sy,Dy,Ly,Oy,Ry,By,Ny,jy,Vy,Uy,zy,Wy,Gy,Ky,$y,Hy,Qy,Xy,Jy,qy,Yy,Zy,eE,tE,rE,sE,oE,nE,aE,iE,lE,cE,dE,_E,uE,pE,mE,hE,fE,gE,ME,wE,TE,vE,PE,bE,xE,yE,EE,CE,kE,FE,AE,IE,SE,DE,LE,OE,RE,BE,NE,jE,VE,UE,zE,WE,GE,KE,$E,HE,QE,XE,JE,qE,YE,ZE,eC,tC,rC,sC,oC,nC,aC,iC,lC,cC,dC,_C,uC,pC,mC,hC,fC,gC,MC,wC,TC,vC,PC,bC,xC,yC,EC,CC,kC,FC,AC,IC,SC,DC,LC,OC,RC,BC,NC,jC,VC,UC,zC,WC,GC,KC,$C,HC,QC,XC,JC,qC,YC,ZC,ek,tk,rk,sk,ok,nk,ak,ik,lk,ck,dk,_k,uk,pk,mk,hk,fk,gk,Mk,wk,Tk,vk,Pk,bk,xk,yk,Ek,Ck,kk,Fk,Ak,Ik,Sk,Dk,Lk,Ok,Rk,Bk,Nk,jk,Vk,Uk,zk,Wk,Gk,Kk,$k,Hk,Qk,Xk,Jk,qk,Yk,Zk,eF,tF,rF,sF,oF,nF,aF,iF,lF,cF,dF,_F,uF,pF,mF,hF,fF,gF,MF,wF,TF,vF,PF,bF,xF,yF,EF,CF,kF,FF,AF,IF,SF,DF,LF,OF,RF,BF,NF,jF,VF,UF,zF,WF,GF,KF,$F,HF,QF,XF,JF,qF,YF,ZF,eA,tA,rA,sA,oA,nA,aA,iA,lA,cA,dA,_A,uA,pA,mA,hA,fA,gA,MA,wA,TA,vA,PA,bA,xA,yA,EA,CA,kA,FA,AA,IA,SA,DA,LA,OA,RA,BA,NA,jA,VA,UA,zA,WA,GA,KA,$A,HA,QA,XA,JA,qA,YA,ZA,eI,tI,rI,sI,oI,nI,aI,iI,lI,cI,dI,_I,uI,pI,mI,hI,fI,gI,MI,wI,TI,vI,PI,bI,xI,yI,EI,CI,kI,FI,AI,II,SI,DI,LI,OI,RI,BI,NI,jI,VI,UI,zI,WI,GI,KI,$I,HI,QI,XI,JI,qI,YI,ZI,eS,tS,rS,sS,oS,nS,aS,iS,lS,cS,dS,_S,_h=jt(()=>{lh();Mf=Mm(ii(),1),uS={},wf={"onnxruntime-common":d=>{d.exports=Ti},"onnxruntime-web":d=>{d.exports=Mf},"?2ce3":()=>{},"?7992":()=>{},"?5af5":()=>{},"?2b25":()=>{},"?db59":()=>{},"?383f":()=>{},"?fa4b":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(d,t,e)=>{e.r(t),e.d(t,{Environment:()=>et,Interpreter:()=>bt,Template:()=>Gr,parse:()=>xe,tokenize:()=>f});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),o=class{constructor(m,j){this.value=m,this.type=j}};function a(m){return/\w/.test(m)}function h(m){return/[0-9]/.test(m)}function u(m){return/\s/.test(m)}var l=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["~",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],p=new Map([["n",`
2
- `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function w(m,j={}){return m.endsWith(`
3
- `)&&(m=m.slice(0,-1)),j.lstrip_blocks&&(m=m.replace(/^[ \t]*({[#%-])/gm,"$1")),j.trim_blocks&&(m=m.replace(/([#%-]})\n/g,"$1")),m.replace(/{%\s*(end)?generation\s*%}/gs,"")}function f(m,j={}){let C=[],R=w(m,j),V=0,te=0,me=je=>{let st="";for(;je(R[V]);){if(R[V]==="\\"){if(++V,V>=R.length)throw new SyntaxError("Unexpected end of input");let Ge=R[V++],ct=p.get(Ge);if(ct===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ge}`);st+=ct;continue}if(st+=R[V++],V>=R.length)throw new SyntaxError("Unexpected end of input")}return st},Ke=()=>{let je=C.at(-1);je&&je.type===r.Text&&(je.value=je.value.trimEnd(),je.value===""&&C.pop())},qe=()=>{for(;V<R.length&&u(R[V]);)++V};e:for(;V<R.length;){let je=C.at(-1)?.type;if(je===void 0||je===r.CloseStatement||je===r.CloseExpression||je===r.Comment){let Ge="";for(;V<R.length&&!(R[V]==="{"&&(R[V+1]==="%"||R[V+1]==="{"||R[V+1]==="#"));)Ge+=R[V++];if(Ge.length>0){C.push(new o(Ge,r.Text));continue}}if(R[V]==="{"&&R[V+1]==="#"){V+=2;let Ge=R[V]==="-";Ge&&++V;let ct="";for(;R[V]!=="#"||R[V+1]!=="}";){if(V+2>=R.length)throw new SyntaxError("Missing end of comment tag");ct+=R[V++]}let ft=ct.endsWith("-");ft&&(ct=ct.slice(0,-1)),Ge&&Ke(),C.push(new o(ct,r.Comment)),V+=2,ft&&qe();continue}if(R.slice(V,V+3)==="{%-"){Ke(),C.push(new o("{%",r.OpenStatement)),V+=3;continue}if(R.slice(V,V+3)==="{{-"){Ke(),C.push(new o("{{",r.OpenExpression)),te=0,V+=3;continue}if(me(u),R.slice(V,V+3)==="-%}"){C.push(new o("%}",r.CloseStatement)),V+=3,qe();continue}if(R.slice(V,V+3)==="-}}"){C.push(new o("}}",r.CloseExpression)),V+=3,qe();continue}let st=R[V];if(st==="-"||st==="+"){let Ge=C.at(-1)?.type;if(Ge===r.Text||Ge===void 0)throw new SyntaxError(`Unexpected character: ${st}`);switch(Ge){case r.Identifier:case r.NumericLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++V;let ct=me(h);C.push(new o(`${st}${ct}`,ct.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(let[Ge,ct]of l){if(Ge==="}}"&&te>0)continue;if(R.slice(V,V+Ge.length)===Ge){C.push(new o(Ge,ct)),ct===r.OpenExpression?te=0:ct===r.OpenCurlyBracket?++te:ct===r.CloseCurlyBracket&&--te,V+=Ge.length;continue e}}if(st==="'"||st==='"'){++V;let Ge=me(ct=>ct!==st);C.push(new o(Ge,r.StringLiteral)),++V;continue}if(h(st)){let Ge=me(h);if(R[V]==="."&&h(R[V+1])){++V;let ct=me(h);Ge=`${Ge}.${ct}`}C.push(new o(Ge,r.NumericLiteral));continue}if(a(st)){let Ge=me(a);C.push(new o(Ge,r.Identifier));continue}throw new SyntaxError(`Unexpected character: ${st}`)}return C}var i=class{constructor(){v(this,"type","Statement")}},y=class extends i{constructor(j){super();v(this,"type","Program");this.body=j}},E=class extends i{constructor(j,C,R){super();v(this,"type","If");this.test=j,this.body=C,this.alternate=R}},S=class extends i{constructor(j,C,R,V){super();v(this,"type","For");this.loopvar=j,this.iterable=C,this.body=R,this.defaultBlock=V}},z=class extends i{constructor(){super(...arguments);v(this,"type","Break")}},k=class extends i{constructor(){super(...arguments);v(this,"type","Continue")}},A=class extends i{constructor(j,C,R){super();v(this,"type","Set");this.assignee=j,this.value=C,this.body=R}},N=class extends i{constructor(j,C,R){super();v(this,"type","Macro");this.name=j,this.args=C,this.body=R}},x=class extends i{constructor(j){super();v(this,"type","Comment");this.value=j}},P=class extends i{constructor(){super(...arguments);v(this,"type","Expression")}},D=class extends P{constructor(j,C,R){super();v(this,"type","MemberExpression");this.object=j,this.property=C,this.computed=R}},_=class extends P{constructor(j,C){super();v(this,"type","CallExpression");this.callee=j,this.args=C}},M=class extends P{constructor(j){super();v(this,"type","Identifier");this.value=j}},I=class extends P{constructor(j){super();v(this,"type","Literal");this.value=j}},O=class extends I{constructor(){super(...arguments);v(this,"type","IntegerLiteral")}},G=class extends I{constructor(){super(...arguments);v(this,"type","FloatLiteral")}},U=class extends I{constructor(){super(...arguments);v(this,"type","StringLiteral")}},B=class extends I{constructor(){super(...arguments);v(this,"type","ArrayLiteral")}},Q=class extends I{constructor(){super(...arguments);v(this,"type","TupleLiteral")}},$=class extends I{constructor(){super(...arguments);v(this,"type","ObjectLiteral")}},Y=class extends P{constructor(j,C,R){super();v(this,"type","BinaryExpression");this.operator=j,this.left=C,this.right=R}},se=class extends P{constructor(j,C){super();v(this,"type","FilterExpression");this.operand=j,this.filter=C}},oe=class extends i{constructor(j,C){super();v(this,"type","FilterStatement");this.filter=j,this.body=C}},ue=class extends P{constructor(j,C){super();v(this,"type","SelectExpression");this.lhs=j,this.test=C}},be=class extends P{constructor(j,C,R){super();v(this,"type","TestExpression");this.operand=j,this.negate=C,this.test=R}},pe=class extends P{constructor(j,C){super();v(this,"type","UnaryExpression");this.operator=j,this.argument=C}},J=class extends P{constructor(j=void 0,C=void 0,R=void 0){super();v(this,"type","SliceExpression");this.start=j,this.stop=C,this.step=R}},F=class extends P{constructor(j,C){super();v(this,"type","KeywordArgumentExpression");this.key=j,this.value=C}},K=class extends P{constructor(j){super();v(this,"type","SpreadExpression");this.argument=j}},Z=class extends i{constructor(j,C,R){super();v(this,"type","CallStatement");this.call=j,this.callerArgs=C,this.body=R}},ie=class extends P{constructor(j,C,R){super();v(this,"type","Ternary");this.condition=j,this.trueExpr=C,this.falseExpr=R}};function xe(m){let j=new y([]),C=0;function R(ke,De){let Qe=m[C++];if(!Qe||Qe.type!==ke)throw new Error(`Parser Error: ${De}. ${Qe.type} !== ${ke}.`);return Qe}function V(ke){if(!qe(ke))throw new SyntaxError(`Expected ${ke}`);++C}function te(){switch(m[C].type){case r.Comment:return new x(m[C++].value);case r.Text:return je();case r.OpenStatement:return st();case r.OpenExpression:return Ge();default:throw new SyntaxError(`Unexpected token type: ${m[C].type}`)}}function me(...ke){return C+ke.length<=m.length&&ke.every((De,Qe)=>De===m[C+Qe].type)}function Ke(...ke){return m[C]?.type===r.OpenStatement&&m[C+1]?.type===r.Identifier&&ke.includes(m[C+1]?.value)}function qe(...ke){return C+ke.length<=m.length&&ke.every((De,Qe)=>m[C+Qe].type==="Identifier"&&De===m[C+Qe].value)}function je(){return new U(R(r.Text,"Expected text token").value)}function st(){if(R(r.OpenStatement,"Expected opening statement token"),m[C].type!==r.Identifier)throw new SyntaxError(`Unknown statement, got ${m[C].type}`);let ke=m[C].value,De;switch(ke){case"set":++C,De=ct();break;case"if":++C,De=ft(),R(r.OpenStatement,"Expected {% token"),V("endif"),R(r.CloseStatement,"Expected %} token");break;case"macro":++C,De=Qt(),R(r.OpenStatement,"Expected {% token"),V("endmacro"),R(r.CloseStatement,"Expected %} token");break;case"for":++C,De=ar(),R(r.OpenStatement,"Expected {% token"),V("endfor"),R(r.CloseStatement,"Expected %} token");break;case"call":{++C;let Qe=null;me(r.OpenParen)&&(Qe=Mr());let xt=ir();if(xt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let Qr=Mr();R(r.CloseStatement,"Expected closing statement token");let Lr=[];for(;!Ke("endcall");)Lr.push(te());R(r.OpenStatement,"Expected '{%'"),V("endcall"),R(r.CloseStatement,"Expected closing statement token");let Xr=new _(xt,Qr);De=new Z(Xr,Qe,Lr);break}case"break":++C,R(r.CloseStatement,"Expected closing statement token"),De=new z;break;case"continue":++C,R(r.CloseStatement,"Expected closing statement token"),De=new k;break;case"filter":{++C;let Qe=ir();Qe instanceof M&&me(r.OpenParen)&&(Qe=mr(Qe)),R(r.CloseStatement,"Expected closing statement token");let xt=[];for(;!Ke("endfilter");)xt.push(te());R(r.OpenStatement,"Expected '{%'"),V("endfilter"),R(r.CloseStatement,"Expected '%}'"),De=new oe(Qe,xt);break}default:throw new SyntaxError(`Unknown statement type: ${ke}`)}return De}function Ge(){R(r.OpenExpression,"Expected opening expression token");let ke=Xt();return R(r.CloseExpression,"Expected closing expression token"),ke}function ct(){let ke=Ut(),De=null,Qe=[];if(me(r.Equals))++C,De=Ut();else{for(R(r.CloseStatement,"Expected %} token");!Ke("endset");)Qe.push(te());R(r.OpenStatement,"Expected {% token"),V("endset")}return R(r.CloseStatement,"Expected closing statement token"),new A(ke,De,Qe)}function ft(){let ke=Xt();R(r.CloseStatement,"Expected closing statement token");let De=[],Qe=[];for(;!Ke("elif","else","endif");)De.push(te());if(Ke("elif")){++C,++C;let xt=ft();Qe.push(xt)}else if(Ke("else"))for(++C,++C,R(r.CloseStatement,"Expected closing statement token");!Ke("endif");)Qe.push(te());return new E(ke,De,Qe)}function Qt(){let ke=ir();if(ke.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let De=Mr();R(r.CloseStatement,"Expected closing statement token");let Qe=[];for(;!Ke("endmacro");)Qe.push(te());return new N(ke,De,Qe)}function Ut(ke=!1){let De=ke?ir:Xt,Qe=[De()],xt=me(r.Comma);for(;xt&&(++C,Qe.push(De()),!!me(r.Comma)););return xt?new Q(Qe):Qe[0]}function ar(){let ke=Ut(!0);if(!(ke instanceof M||ke instanceof Q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ke.type} instead`);if(!qe("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++C;let De=Xt();R(r.CloseStatement,"Expected closing statement token");let Qe=[];for(;!Ke("endfor","else");)Qe.push(te());let xt=[];if(Ke("else"))for(++C,++C,R(r.CloseStatement,"Expected closing statement token");!Ke("endfor");)xt.push(te());return new S(ke,De,Qe,xt)}function Xt(){return Cr()}function Cr(){let ke=kr();if(qe("if")){++C;let De=kr();if(qe("else")){++C;let Qe=Cr();return new ie(De,ke,Qe)}else return new ue(ke,De)}return ke}function kr(){let ke=Fr();for(;qe("or");){let De=m[C];++C;let Qe=Fr();ke=new Y(De,ke,Qe)}return ke}function Fr(){let ke=cr();for(;qe("and");){let De=m[C];++C;let Qe=cr();ke=new Y(De,ke,Qe)}return ke}function cr(){let ke;for(;qe("not");){let De=m[C];++C;let Qe=cr();ke=new pe(De,Qe)}return ke??Kr()}function Kr(){let ke=Ar();for(;;){let De;if(qe("not","in"))De=new o("not in",r.Identifier),C+=2;else if(qe("in"))De=m[C++];else if(me(r.ComparisonBinaryOperator))De=m[C++];else break;let Qe=Ar();ke=new Y(De,ke,Qe)}return ke}function Ar(){let ke=Sr();for(;me(r.AdditiveBinaryOperator);){let De=m[C];++C;let Qe=Sr();ke=new Y(De,ke,Qe)}return ke}function $r(){let ke=Ir(ir());return me(r.OpenParen)?mr(ke):ke}function mr(ke){let De=new _(ke,Mr());return De=Ir(De),me(r.OpenParen)&&(De=mr(De)),De}function Mr(){R(r.OpenParen,"Expected opening parenthesis for arguments list");let ke=wr();return R(r.CloseParen,"Expected closing parenthesis for arguments list"),ke}function wr(){let ke=[];for(;!me(r.CloseParen);){let De;if(m[C].type===r.MultiplicativeBinaryOperator&&m[C].value==="*"){++C;let Qe=Xt();De=new K(Qe)}else if(De=Xt(),me(r.Equals)){if(++C,!(De instanceof M))throw new SyntaxError("Expected identifier for keyword argument");let Qe=Xt();De=new F(De,Qe)}ke.push(De),me(r.Comma)&&++C}return ke}function Hr(){let ke=[],De=!1;for(;!me(r.CloseSquareBracket);)me(r.Colon)?(ke.push(void 0),++C,De=!0):(ke.push(Xt()),me(r.Colon)&&(++C,De=!0));if(ke.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(De){if(ke.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new J(...ke)}return ke[0]}function Ir(ke){for(;me(r.Dot)||me(r.OpenSquareBracket);){let De=m[C];++C;let Qe,xt=De.type===r.OpenSquareBracket;if(xt)Qe=Hr(),R(r.CloseSquareBracket,"Expected closing square bracket");else if(Qe=ir(),Qe.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ke=new D(ke,Qe,xt)}return ke}function Sr(){let ke=Dr();for(;me(r.MultiplicativeBinaryOperator);){let De=m[C++],Qe=Dr();ke=new Y(De,ke,Qe)}return ke}function Dr(){let ke=Tr();for(;qe("is");){++C;let De=qe("not");De&&++C;let Qe=ir();if(!(Qe instanceof M))throw new SyntaxError("Expected identifier for the test");ke=new be(ke,De,Qe)}return ke}function Tr(){let ke=$r();for(;me(r.Pipe);){++C;let De=ir();if(!(De instanceof M))throw new SyntaxError("Expected identifier for the filter");me(r.OpenParen)&&(De=mr(De)),ke=new se(ke,De)}return ke}function ir(){let ke=m[C++];switch(ke.type){case r.NumericLiteral:{let De=ke.value;return De.includes(".")?new G(Number(De)):new O(Number(De))}case r.StringLiteral:{let De=ke.value;for(;me(r.StringLiteral);)De+=m[C++].value;return new U(De)}case r.Identifier:return new M(ke.value);case r.OpenParen:{let De=Ut();return R(r.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),De}case r.OpenSquareBracket:{let De=[];for(;!me(r.CloseSquareBracket);)De.push(Xt()),me(r.Comma)&&++C;return++C,new B(De)}case r.OpenCurlyBracket:{let De=new Map;for(;!me(r.CloseCurlyBracket);){let Qe=Xt();R(r.Colon,"Expected colon between key and value in object literal");let xt=Xt();De.set(Qe,xt),me(r.Comma)&&++C}return++C,new $(De)}default:throw new SyntaxError(`Unexpected token: ${ke.type}`)}}for(;C<m.length;)j.body.push(te());return j}function ye(m,j,C=1){j===void 0&&(j=m,m=0);let R=[];for(let V=m;V<j;V+=C)R.push(V);return R}function Oe(m,j,C,R=1){let V=Math.sign(R);V>=0?(j=(j??(j=0))<0?Math.max(m.length+j,0):Math.min(j,m.length),C=(C??(C=m.length))<0?Math.max(m.length+C,0):Math.min(C,m.length)):(j=(j??(j=m.length-1))<0?Math.max(m.length+j,-1):Math.min(j,m.length-1),C=(C??(C=-1))<-1?Math.max(m.length+C,-1):Math.min(C,m.length-1));let te=[];for(let me=j;V*me<V*C;me+=R)te.push(m[me]);return te}function He(m){return m.replace(/\b\w/g,j=>j.toUpperCase())}function we(m){return T(new Date,m)}function T(m,j){let C=new Intl.DateTimeFormat(void 0,{month:"long"}),R=new Intl.DateTimeFormat(void 0,{month:"short"}),V=te=>te<10?"0"+te:te.toString();return j.replace(/%[YmdbBHM%]/g,te=>{switch(te){case"%Y":return m.getFullYear().toString();case"%m":return V(m.getMonth()+1);case"%d":return V(m.getDate());case"%b":return R.format(m);case"%B":return C.format(m);case"%H":return V(m.getHours());case"%M":return V(m.getMinutes());case"%%":return"%";default:return te}})}function X(m){return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function de(m,j,C,R){if(R===0)return m;let V=R==null||R<0?1/0:R,te=j.length===0?new RegExp("(?=)","gu"):new RegExp(X(j),"gu");return m.replaceAll(te,me=>V>0?(--V,C):me)}var he=class extends Error{},Te=class extends Error{},ge=class{constructor(m=void 0){v(this,"type","RuntimeValue");v(this,"value");v(this,"builtins",new Map);this.value=m}__bool__(){return new Me(!!this.value)}toString(){return String(this.value)}},le=class extends ge{constructor(){super(...arguments);v(this,"type","IntegerValue")}},ve=class extends ge{constructor(){super(...arguments);v(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ce=class extends ge{constructor(){super(...arguments);v(this,"type","StringValue");v(this,"builtins",new Map([["upper",new Ve(()=>new ce(this.value.toUpperCase()))],["lower",new Ve(()=>new ce(this.value.toLowerCase()))],["strip",new Ve(()=>new ce(this.value.trim()))],["title",new Ve(()=>new ce(He(this.value)))],["capitalize",new Ve(()=>new ce(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new le(this.value.length)],["rstrip",new Ve(()=>new ce(this.value.trimEnd()))],["lstrip",new Ve(()=>new ce(this.value.trimStart()))],["startswith",new Ve(j=>{if(j.length===0)throw new Error("startswith() requires at least one argument");let C=j[0];if(C instanceof ce)return new Me(this.value.startsWith(C.value));if(C instanceof Fe){for(let R of C.value){if(!(R instanceof ce))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(R.value))return new Me(!0)}return new Me(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ve(j=>{if(j.length===0)throw new Error("endswith() requires at least one argument");let C=j[0];if(C instanceof ce)return new Me(this.value.endsWith(C.value));if(C instanceof Fe){for(let R of C.value){if(!(R instanceof ce))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(R.value))return new Me(!0)}return new Me(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ve(j=>{let C=j[0]??new ze;if(!(C instanceof ce||C instanceof ze))throw new Error("sep argument must be a string or null");let R=j[1]??new le(-1);if(!(R instanceof le))throw new Error("maxsplit argument must be a number");let V=[];if(C instanceof ze){let te=this.value.trimStart();for(let{0:me,index:Ke}of te.matchAll(/\S+/g)){if(R.value!==-1&&V.length>=R.value&&Ke!==void 0){V.push(me+te.slice(Ke+me.length));break}V.push(me)}}else{if(C.value==="")throw new Error("empty separator");V=this.value.split(C.value),R.value!==-1&&V.length>R.value&&V.push(V.splice(R.value).join(C.value))}return new Fe(V.map(te=>new ce(te)))})],["replace",new Ve(j=>{if(j.length<2)throw new Error("replace() requires at least two arguments");let C=j[0],R=j[1];if(!(C instanceof ce&&R instanceof ce))throw new Error("replace() arguments must be strings");let V;if(j.length>2?j[2].type==="KeywordArgumentsValue"?V=j[2].value.get("count")??new ze:V=j[2]:V=new ze,!(V instanceof le||V instanceof ze))throw new Error("replace() count argument must be a number or null");return new ce(de(this.value,C.value,R.value,V.value))})]]))}},Me=class extends ge{constructor(){super(...arguments);v(this,"type","BooleanValue")}};function Re(m,j,C,R=!0){let V=C??0;switch(m.type){case"NullValue":return"null";case"UndefinedValue":return R?"null":"undefined";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(m.value);case"ArrayValue":case"ObjectValue":{let te=j?" ".repeat(j):"",me=`
4
- `+te.repeat(V),Ke=me+te;if(m.type==="ArrayValue"){let qe=m.value.map(je=>Re(je,j,V+1,R));return j?`[${Ke}${qe.join(`,${Ke}`)}${me}]`:`[${qe.join(", ")}]`}else{let qe=Array.from(m.value.entries()).map(([je,st])=>{let Ge=`"${je}": ${Re(st,j,V+1,R)}`;return j?`${Ke}${Ge}`:Ge});return j?`{${qe.join(",")}${me}}`:`{${qe.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${m.type}`)}}var Ce=class extends ge{constructor(){super(...arguments);v(this,"type","ObjectValue");v(this,"builtins",new Map([["get",new Ve(([j,C])=>{if(!(j instanceof ce))throw new Error(`Object key must be a string: got ${j.type}`);return this.value.get(j.value)??C??new ze})],["items",new Ve(()=>this.items())],["keys",new Ve(()=>this.keys())],["values",new Ve(()=>this.values())],["dictsort",new Ve(j=>{let C=new Map,R=j.filter(qe=>qe instanceof Ie?(C=qe.value,!1):!0),V=R.at(0)??C.get("case_sensitive")??new Me(!1);if(!(V instanceof Me))throw new Error("case_sensitive must be a boolean");let te=R.at(1)??C.get("by")??new ce("key");if(!(te instanceof ce))throw new Error("by must be a string");if(!["key","value"].includes(te.value))throw new Error("by must be either 'key' or 'value'");let me=R.at(2)??C.get("reverse")??new Me(!1);if(!(me instanceof Me))throw new Error("reverse must be a boolean");let Ke=Array.from(this.value.entries()).map(([qe,je])=>new Fe([new ce(qe),je])).sort((qe,je)=>{let st=te.value==="key"?0:1,Ge=qe.value[st],ct=je.value[st],ft=mt(Ge,ct,V.value);return me.value?-ft:ft});return new Fe(Ke)})]]))}__bool__(){return new Me(this.value.size>0)}items(){return new Fe(Array.from(this.value.entries()).map(([j,C])=>new Fe([new ce(j),C])))}keys(){return new Fe(Array.from(this.value.keys()).map(j=>new ce(j)))}values(){return new Fe(Array.from(this.value.values()))}toString(){return Re(this,null,0,!1)}},Ie=class extends Ce{constructor(){super(...arguments);v(this,"type","KeywordArgumentsValue")}},Fe=class extends ge{constructor(){super(...arguments);v(this,"type","ArrayValue");v(this,"builtins",new Map([["length",new le(this.value.length)]]))}__bool__(){return new Me(this.value.length>0)}toString(){return Re(this,null,0,!1)}},Je=class extends Fe{constructor(){super(...arguments);v(this,"type","TupleValue")}},Ve=class extends ge{constructor(){super(...arguments);v(this,"type","FunctionValue")}},ze=class extends ge{constructor(){super(...arguments);v(this,"type","NullValue")}},Ae=class extends ge{constructor(){super(...arguments);v(this,"type","UndefinedValue")}},et=class{constructor(m){v(this,"variables",new Map([["namespace",new Ve(m=>{if(m.length===0)return new Ce(new Map);if(m.length!==1||!(m[0]instanceof Ce))throw new Error("`namespace` expects either zero arguments or a single object argument");return m[0]})]]));v(this,"tests",new Map([["boolean",m=>m.type==="BooleanValue"],["callable",m=>m instanceof Ve],["odd",m=>{if(!(m instanceof le))throw new Error(`cannot odd on ${m.type}`);return m.value%2!==0}],["even",m=>{if(!(m instanceof le))throw new Error(`cannot even on ${m.type}`);return m.value%2===0}],["false",m=>m.type==="BooleanValue"&&!m.value],["true",m=>m.type==="BooleanValue"&&m.value],["none",m=>m.type==="NullValue"],["string",m=>m.type==="StringValue"],["number",m=>m instanceof le||m instanceof ve],["integer",m=>m instanceof le],["iterable",m=>m.type==="ArrayValue"||m.type==="StringValue"],["mapping",m=>m.type==="ObjectValue"],["lower",m=>{let j=m.value;return m.type==="StringValue"&&j===j.toLowerCase()}],["upper",m=>{let j=m.value;return m.type==="StringValue"&&j===j.toUpperCase()}],["none",m=>m.type==="NullValue"],["defined",m=>m.type!=="UndefinedValue"],["undefined",m=>m.type==="UndefinedValue"],["equalto",(m,j)=>m.value===j.value],["eq",(m,j)=>m.value===j.value]]));this.parent=m}set(m,j){return this.declareVariable(m,Vt(j))}declareVariable(m,j){if(this.variables.has(m))throw new SyntaxError(`Variable already declared: ${m}`);return this.variables.set(m,j),j}setVariable(m,j){return this.variables.set(m,j),j}resolve(m){if(this.variables.has(m))return this;if(this.parent)return this.parent.resolve(m);throw new Error(`Unknown variable: ${m}`)}lookupVariable(m){try{return this.resolve(m).variables.get(m)??new Ae}catch{return new Ae}}};function Ue(m){m.set("false",!1),m.set("true",!0),m.set("none",null),m.set("raise_exception",j=>{throw new Error(j)}),m.set("range",ye),m.set("strftime_now",we),m.set("True",!0),m.set("False",!1),m.set("None",null)}function lt(m,j){let C=j.split("."),R=m;for(let V of C)if(R instanceof Ce)R=R.value.get(V)??new Ae;else if(R instanceof Fe){let te=parseInt(V,10);if(!isNaN(te)&&te>=0&&te<R.value.length)R=R.value[te];else return new Ae}else return new Ae;return R}function mt(m,j,C=!1){if(m instanceof ze&&j instanceof ze)return 0;if(m instanceof ze||j instanceof ze)throw new Error(`Cannot compare ${m.type} with ${j.type}`);if(m instanceof Ae&&j instanceof Ae)return 0;if(m instanceof Ae||j instanceof Ae)throw new Error(`Cannot compare ${m.type} with ${j.type}`);let R=te=>te instanceof le||te instanceof ve||te instanceof Me,V=te=>te instanceof Me?te.value?1:0:te.value;if(R(m)&&R(j)){let te=V(m),me=V(j);return te<me?-1:te>me?1:0}if(m.type!==j.type)throw new Error(`Cannot compare different types: ${m.type} and ${j.type}`);switch(m.type){case"StringValue":{let te=m.value,me=j.value;return C||(te=te.toLowerCase(),me=me.toLowerCase()),te<me?-1:te>me?1:0}default:throw new Error(`Cannot compare type: ${m.type}`)}}var bt=class{constructor(m){v(this,"global");this.global=m??new et}run(m){return this.evaluate(m,this.global)}evaluateBinaryExpression(m,j){let C=this.evaluate(m.left,j);switch(m.operator.value){case"and":return C.__bool__().value?this.evaluate(m.right,j):C;case"or":return C.__bool__().value?C:this.evaluate(m.right,j)}let R=this.evaluate(m.right,j);switch(m.operator.value){case"==":return new Me(C.value==R.value);case"!=":return new Me(C.value!=R.value)}if(C instanceof Ae||R instanceof Ae){if(R instanceof Ae&&["in","not in"].includes(m.operator.value))return new Me(m.operator.value==="not in");throw new Error(`Cannot perform operation ${m.operator.value} on undefined values`)}else{if(C instanceof ze||R instanceof ze)throw new Error("Cannot perform operation on null values");if(m.operator.value==="~")return new ce(C.value.toString()+R.value.toString());if((C instanceof le||C instanceof ve)&&(R instanceof le||R instanceof ve)){let V=C.value,te=R.value;switch(m.operator.value){case"+":case"-":case"*":{let me=m.operator.value==="+"?V+te:m.operator.value==="-"?V-te:V*te;return C instanceof ve||R instanceof ve?new ve(me):new le(me)}case"/":return new ve(V/te);case"%":{let me=V%te;return C instanceof ve||R instanceof ve?new ve(me):new le(me)}case"<":return new Me(V<te);case">":return new Me(V>te);case">=":return new Me(V>=te);case"<=":return new Me(V<=te)}}else if(C instanceof Fe&&R instanceof Fe)switch(m.operator.value){case"+":return new Fe(C.value.concat(R.value))}else if(R instanceof Fe){let V=R.value.find(te=>te.value===C.value)!==void 0;switch(m.operator.value){case"in":return new Me(V);case"not in":return new Me(!V)}}}if(C instanceof ce||R instanceof ce)switch(m.operator.value){case"+":return new ce(C.value.toString()+R.value.toString())}if(C instanceof ce&&R instanceof ce)switch(m.operator.value){case"in":return new Me(R.value.includes(C.value));case"not in":return new Me(!R.value.includes(C.value))}if(C instanceof ce&&R instanceof Ce)switch(m.operator.value){case"in":return new Me(R.value.has(C.value));case"not in":return new Me(!R.value.has(C.value))}throw new SyntaxError(`Unknown operator "${m.operator.value}" between ${C.type} and ${R.type}`)}evaluateArguments(m,j){let C=[],R=new Map;for(let V of m)if(V.type==="SpreadExpression"){let te=V,me=this.evaluate(te.argument,j);if(!(me instanceof Fe))throw new Error(`Cannot unpack non-iterable type: ${me.type}`);for(let Ke of me.value)C.push(Ke)}else if(V.type==="KeywordArgumentExpression"){let te=V;R.set(te.key.value,this.evaluate(te.value,j))}else{if(R.size>0)throw new Error("Positional arguments must come before keyword arguments");C.push(this.evaluate(V,j))}return[C,R]}applyFilter(m,j,C){if(j.type==="Identifier"){let R=j;if(R.value==="tojson")return new ce(Re(m));if(m instanceof Fe)switch(R.value){case"list":return m;case"first":return m.value[0];case"last":return m.value[m.value.length-1];case"length":return new le(m.value.length);case"reverse":return new Fe(m.value.slice().reverse());case"sort":return new Fe(m.value.slice().sort((V,te)=>mt(V,te,!1)));case"join":return new ce(m.value.map(V=>V.value).join(""));case"string":return new ce(Re(m,null,0,!1));case"unique":{let V=new Set,te=[];for(let me of m.value)V.has(me.value)||(V.add(me.value),te.push(me));return new Fe(te)}default:throw new Error(`Unknown ArrayValue filter: ${R.value}`)}else if(m instanceof ce)switch(R.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let V=m.builtins.get(R.value);if(V instanceof Ve)return V.value([],C);if(V instanceof le)return V;throw new Error(`Unknown StringValue filter: ${R.value}`)}case"trim":return new ce(m.value.trim());case"indent":return new ce(m.value.split(`
5
- `).map((V,te)=>te===0||V.length===0?V:" "+V).join(`
6
- `));case"join":case"string":return m;case"int":{let V=parseInt(m.value,10);return new le(isNaN(V)?0:V)}case"float":{let V=parseFloat(m.value);return new ve(isNaN(V)?0:V)}default:throw new Error(`Unknown StringValue filter: ${R.value}`)}else if(m instanceof le||m instanceof ve)switch(R.value){case"abs":return m instanceof le?new le(Math.abs(m.value)):new ve(Math.abs(m.value));case"int":return new le(Math.floor(m.value));case"float":return new ve(m.value);default:throw new Error(`Unknown NumericValue filter: ${R.value}`)}else if(m instanceof Ce)switch(R.value){case"items":return new Fe(Array.from(m.value.entries()).map(([V,te])=>new Fe([new ce(V),te])));case"length":return new le(m.value.size);default:{let V=m.builtins.get(R.value);if(V)return V instanceof Ve?V.value([],C):V;throw new Error(`Unknown ObjectValue filter: ${R.value}`)}}else if(m instanceof Me)switch(R.value){case"bool":return new Me(m.value);case"int":return new le(m.value?1:0);case"float":return new ve(m.value?1:0);case"string":return new ce(m.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${R.value}`)}throw new Error(`Cannot apply filter "${R.value}" to type: ${m.type}`)}else if(j.type==="CallExpression"){let R=j;if(R.callee.type!=="Identifier")throw new Error(`Unknown filter: ${R.callee.type}`);let V=R.callee.value;if(V==="tojson"){let[,te]=this.evaluateArguments(R.args,C),me=te.get("indent")??new ze;if(!(me instanceof le||me instanceof ze))throw new Error("If set, indent must be a number");return new ce(Re(m,me.value))}else if(V==="join"){let te;if(m instanceof ce)te=Array.from(m.value);else if(m instanceof Fe)te=m.value.map(je=>je.value);else throw new Error(`Cannot apply filter "${V}" to type: ${m.type}`);let[me,Ke]=this.evaluateArguments(R.args,C),qe=me.at(0)??Ke.get("separator")??new ce("");if(!(qe instanceof ce))throw new Error("separator must be a string");return new ce(te.join(qe.value))}else if(V==="int"||V==="float"){let[te,me]=this.evaluateArguments(R.args,C),Ke=te.at(0)??me.get("default")??(V==="int"?new le(0):new ve(0));if(m instanceof ce){let qe=V==="int"?parseInt(m.value,10):parseFloat(m.value);return isNaN(qe)?Ke:V==="int"?new le(qe):new ve(qe)}else{if(m instanceof le||m instanceof ve)return m;if(m instanceof Me)return V==="int"?new le(m.value?1:0):new ve(m.value?1:0);throw new Error(`Cannot apply filter "${V}" to type: ${m.type}`)}}else if(V==="default"){let[te,me]=this.evaluateArguments(R.args,C),Ke=te[0]??new ce(""),qe=te[1]??me.get("boolean")??new Me(!1);if(!(qe instanceof Me))throw new Error("`default` filter flag must be a boolean");return m instanceof Ae||qe.value&&!m.__bool__().value?Ke:m}if(m instanceof Fe){switch(V){case"sort":{let[te,me]=this.evaluateArguments(R.args,C),Ke=te.at(0)??me.get("reverse")??new Me(!1);if(!(Ke instanceof Me))throw new Error("reverse must be a boolean");let qe=te.at(1)??me.get("case_sensitive")??new Me(!1);if(!(qe instanceof Me))throw new Error("case_sensitive must be a boolean");let je=te.at(2)??me.get("attribute")??new ze;if(!(je instanceof ce||je instanceof le||je instanceof ze))throw new Error("attribute must be a string, integer, or null");let st=Ge=>{if(je instanceof ze)return Ge;let ct=je instanceof le?String(je.value):je.value;return lt(Ge,ct)};return new Fe(m.value.slice().sort((Ge,ct)=>{let ft=st(Ge),Qt=st(ct),Ut=mt(ft,Qt,qe.value);return Ke.value?-Ut:Ut}))}case"selectattr":case"rejectattr":{let te=V==="selectattr";if(m.value.some(Ge=>!(Ge instanceof Ce)))throw new Error(`\`${V}\` can only be applied to array of objects`);if(R.args.some(Ge=>Ge.type!=="StringLiteral"))throw new Error(`arguments of \`${V}\` must be strings`);let[me,Ke,qe]=R.args.map(Ge=>this.evaluate(Ge,C)),je;if(Ke){let Ge=C.tests.get(Ke.value);if(!Ge)throw new Error(`Unknown test: ${Ke.value}`);je=Ge}else je=(...Ge)=>Ge[0].__bool__().value;let st=m.value.filter(Ge=>{let ct=Ge.value.get(me.value),ft=ct?je(ct,qe):!1;return te?ft:!ft});return new Fe(st)}case"map":{let[,te]=this.evaluateArguments(R.args,C);if(te.has("attribute")){let me=te.get("attribute");if(!(me instanceof ce))throw new Error("attribute must be a string");let Ke=te.get("default"),qe=m.value.map(je=>{if(!(je instanceof Ce))throw new Error("items in map must be an object");let st=lt(je,me.value);return st instanceof Ae?Ke??new Ae:st});return new Fe(qe)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${V}`)}else if(m instanceof ce){switch(V){case"indent":{let[te,me]=this.evaluateArguments(R.args,C),Ke=te.at(0)??me.get("width")??new le(4);if(!(Ke instanceof le))throw new Error("width must be a number");let qe=te.at(1)??me.get("first")??new Me(!1),je=te.at(2)??me.get("blank")??new Me(!1),st=m.value.split(`
7
- `),Ge=" ".repeat(Ke.value),ct=st.map((ft,Qt)=>!qe.value&&Qt===0||!je.value&&ft.length===0?ft:Ge+ft);return new ce(ct.join(`
8
- `))}case"replace":{let te=m.builtins.get("replace");if(!(te instanceof Ve))throw new Error("replace filter not available");let[me,Ke]=this.evaluateArguments(R.args,C);return te.value([...me,new Ie(Ke)],C)}}throw new Error(`Unknown StringValue filter: ${V}`)}else if(m instanceof Ce){let te=m.builtins.get(V);if(te&&te instanceof Ve){let[me,Ke]=this.evaluateArguments(R.args,C);return Ke.size>0&&me.push(new Ie(Ke)),te.value(me,C)}throw new Error(`Unknown ObjectValue filter: ${V}`)}else throw new Error(`Cannot apply filter "${V}" to type: ${m.type}`)}throw new Error(`Unknown filter: ${j.type}`)}evaluateFilterExpression(m,j){let C=this.evaluate(m.operand,j);return this.applyFilter(C,m.filter,j)}evaluateTestExpression(m,j){let C=this.evaluate(m.operand,j),R=j.tests.get(m.test.value);if(!R)throw new Error(`Unknown test: ${m.test.value}`);let V=R(C);return new Me(m.negate?!V:V)}evaluateSelectExpression(m,j){return this.evaluate(m.test,j).__bool__().value?this.evaluate(m.lhs,j):new Ae}evaluateUnaryExpression(m,j){let C=this.evaluate(m.argument,j);switch(m.operator.value){case"not":return new Me(!C.value);default:throw new SyntaxError(`Unknown operator: ${m.operator.value}`)}}evaluateTernaryExpression(m,j){return this.evaluate(m.condition,j).__bool__().value?this.evaluate(m.trueExpr,j):this.evaluate(m.falseExpr,j)}evalProgram(m,j){return this.evaluateBlock(m.body,j)}evaluateBlock(m,j){let C="";for(let R of m){let V=this.evaluate(R,j);V.type!=="NullValue"&&V.type!=="UndefinedValue"&&(C+=V.toString())}return new ce(C)}evaluateIdentifier(m,j){return j.lookupVariable(m.value)}evaluateCallExpression(m,j){let[C,R]=this.evaluateArguments(m.args,j);R.size>0&&C.push(new Ie(R));let V=this.evaluate(m.callee,j);if(V.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${V.type}`);return V.value(C,j)}evaluateSliceExpression(m,j,C){if(!(m instanceof Fe||m instanceof ce))throw new Error("Slice object must be an array or string");let R=this.evaluate(j.start,C),V=this.evaluate(j.stop,C),te=this.evaluate(j.step,C);if(!(R instanceof le||R instanceof Ae))throw new Error("Slice start must be numeric or undefined");if(!(V instanceof le||V instanceof Ae))throw new Error("Slice stop must be numeric or undefined");if(!(te instanceof le||te instanceof Ae))throw new Error("Slice step must be numeric or undefined");return m instanceof Fe?new Fe(Oe(m.value,R.value,V.value,te.value)):new ce(Oe(Array.from(m.value),R.value,V.value,te.value).join(""))}evaluateMemberExpression(m,j){let C=this.evaluate(m.object,j),R;if(m.computed){if(m.property.type==="SliceExpression")return this.evaluateSliceExpression(C,m.property,j);R=this.evaluate(m.property,j)}else R=new ce(m.property.value);let V;if(C instanceof Ce){if(!(R instanceof ce))throw new Error(`Cannot access property with non-string: got ${R.type}`);V=C.value.get(R.value)??C.builtins.get(R.value)}else if(C instanceof Fe||C instanceof ce)if(R instanceof le)V=C.value.at(R.value),C instanceof ce&&(V=new ce(C.value.at(R.value)));else if(R instanceof ce)V=C.builtins.get(R.value);else throw new Error(`Cannot access property with non-string/non-number: got ${R.type}`);else{if(!(R instanceof ce))throw new Error(`Cannot access property with non-string: got ${R.type}`);V=C.builtins.get(R.value)}return V instanceof ge?V:new Ae}evaluateSet(m,j){let C=m.value?this.evaluate(m.value,j):this.evaluateBlock(m.body,j);if(m.assignee.type==="Identifier"){let R=m.assignee.value;j.setVariable(R,C)}else if(m.assignee.type==="TupleLiteral"){let R=m.assignee;if(!(C instanceof Fe))throw new Error(`Cannot unpack non-iterable type in set: ${C.type}`);let V=C.value;if(V.length!==R.value.length)throw new Error(`Too ${R.value.length>V.length?"few":"many"} items to unpack in set`);for(let te=0;te<R.value.length;++te){let me=R.value[te];if(me.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${me.type}`);j.setVariable(me.value,V[te])}}else if(m.assignee.type==="MemberExpression"){let R=m.assignee,V=this.evaluate(R.object,j);if(!(V instanceof Ce))throw new Error("Cannot assign to member of non-object");if(R.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");V.value.set(R.property.value,C)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(m.assignee)}`);return new ze}evaluateIf(m,j){let C=this.evaluate(m.test,j);return this.evaluateBlock(C.__bool__().value?m.body:m.alternate,j)}evaluateFor(m,j){let C=new et(j),R,V;if(m.iterable.type==="SelectExpression"){let je=m.iterable;V=this.evaluate(je.lhs,C),R=je.test}else V=this.evaluate(m.iterable,C);if(!(V instanceof Fe||V instanceof Ce))throw new Error(`Expected iterable or object type in for loop: got ${V.type}`);V instanceof Ce&&(V=V.keys());let te=[],me=[];for(let je=0;je<V.value.length;++je){let st=new et(C),Ge=V.value[je],ct;if(m.loopvar.type==="Identifier")ct=ft=>ft.setVariable(m.loopvar.value,Ge);else if(m.loopvar.type==="TupleLiteral"){let ft=m.loopvar;if(Ge.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ge.type}`);let Qt=Ge;if(ft.value.length!==Qt.value.length)throw new Error(`Too ${ft.value.length>Qt.value.length?"few":"many"} items to unpack`);ct=Ut=>{for(let ar=0;ar<ft.value.length;++ar){if(ft.value[ar].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${ft.value[ar].type}`);Ut.setVariable(ft.value[ar].value,Qt.value[ar])}}}else throw new Error(`Invalid loop variable(s): ${m.loopvar.type}`);R&&(ct(st),!this.evaluate(R,st).__bool__().value)||(te.push(Ge),me.push(ct))}let Ke="",qe=!0;for(let je=0;je<te.length;++je){let st=new Map([["index",new le(je+1)],["index0",new le(je)],["revindex",new le(te.length-je)],["revindex0",new le(te.length-je-1)],["first",new Me(je===0)],["last",new Me(je===te.length-1)],["length",new le(te.length)],["previtem",je>0?te[je-1]:new Ae],["nextitem",je<te.length-1?te[je+1]:new Ae]]);C.setVariable("loop",new Ce(st)),me[je](C);try{let Ge=this.evaluateBlock(m.body,C);Ke+=Ge.value}catch(Ge){if(Ge instanceof Te)continue;if(Ge instanceof he)break;throw Ge}qe=!1}if(qe){let je=this.evaluateBlock(m.defaultBlock,C);Ke+=je.value}return new ce(Ke)}evaluateMacro(m,j){return j.setVariable(m.name.value,new Ve((C,R)=>{let V=new et(R);C=C.slice();let te;C.at(-1)?.type==="KeywordArgumentsValue"&&(te=C.pop());for(let me=0;me<m.args.length;++me){let Ke=m.args[me],qe=C[me];if(Ke.type==="Identifier"){let je=Ke;if(!qe)throw new Error(`Missing positional argument: ${je.value}`);V.setVariable(je.value,qe)}else if(Ke.type==="KeywordArgumentExpression"){let je=Ke,st=qe??te?.value.get(je.key.value)??this.evaluate(je.value,V);V.setVariable(je.key.value,st)}else throw new Error(`Unknown argument type: ${Ke.type}`)}return this.evaluateBlock(m.body,V)})),new ze}evaluateCallStatement(m,j){let C=new Ve((Ke,qe)=>{let je=new et(qe);if(m.callerArgs)for(let st=0;st<m.callerArgs.length;++st){let Ge=m.callerArgs[st];if(Ge.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${Ge.type}`);je.setVariable(Ge.value,Ke[st]??new Ae)}return this.evaluateBlock(m.body,je)}),[R,V]=this.evaluateArguments(m.call.args,j);R.push(new Ie(V));let te=this.evaluate(m.call.callee,j);if(te.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${te.type}`);let me=new et(j);return me.setVariable("caller",C),te.value(R,me)}evaluateFilterStatement(m,j){let C=this.evaluateBlock(m.body,j);return this.applyFilter(C,m.filter,j)}evaluate(m,j){if(!m)return new Ae;switch(m.type){case"Program":return this.evalProgram(m,j);case"Set":return this.evaluateSet(m,j);case"If":return this.evaluateIf(m,j);case"For":return this.evaluateFor(m,j);case"Macro":return this.evaluateMacro(m,j);case"CallStatement":return this.evaluateCallStatement(m,j);case"Break":throw new he;case"Continue":throw new Te;case"IntegerLiteral":return new le(m.value);case"FloatLiteral":return new ve(m.value);case"StringLiteral":return new ce(m.value);case"ArrayLiteral":return new Fe(m.value.map(C=>this.evaluate(C,j)));case"TupleLiteral":return new Je(m.value.map(C=>this.evaluate(C,j)));case"ObjectLiteral":{let C=new Map;for(let[R,V]of m.value){let te=this.evaluate(R,j);if(!(te instanceof ce))throw new Error(`Object keys must be strings: got ${te.type}`);C.set(te.value,this.evaluate(V,j))}return new Ce(C)}case"Identifier":return this.evaluateIdentifier(m,j);case"CallExpression":return this.evaluateCallExpression(m,j);case"MemberExpression":return this.evaluateMemberExpression(m,j);case"UnaryExpression":return this.evaluateUnaryExpression(m,j);case"BinaryExpression":return this.evaluateBinaryExpression(m,j);case"FilterExpression":return this.evaluateFilterExpression(m,j);case"FilterStatement":return this.evaluateFilterStatement(m,j);case"TestExpression":return this.evaluateTestExpression(m,j);case"SelectExpression":return this.evaluateSelectExpression(m,j);case"Ternary":return this.evaluateTernaryExpression(m,j);case"Comment":return new ze;default:throw new SyntaxError(`Unknown node type: ${m.type}`)}}};function Vt(m){switch(typeof m){case"number":return Number.isInteger(m)?new le(m):new ve(m);case"string":return new ce(m);case"boolean":return new Me(m);case"undefined":return new Ae;case"object":return m===null?new ze:Array.isArray(m)?new Fe(m.map(Vt)):new Ce(new Map(Object.entries(m).map(([j,C])=>[j,Vt(C)])));case"function":return new Ve((j,C)=>{let R=m(...j.map(V=>V.value))??null;return Vt(R)});default:throw new Error(`Cannot convert to runtime value: ${m}`)}}var vt=`
9
- `,Ht="{%- ",ls=" -%}";function cs(m){switch(m.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return m.operator.value==="and"?1:m.operator.value==="in"||m.operator.value==="not in"?2:0}return 0}function ds(m,j=" "){let C=typeof j=="number"?" ".repeat(j):j;return er(m.body,0,C).replace(/\n$/,"")}function St(...m){return Ht+m.join(" ")+ls}function er(m,j,C){return m.map(R=>gr(R,j,C)).join(vt)}function gr(m,j,C){let R=C.repeat(j);switch(m.type){case"Program":return er(m.body,j,C);case"If":return _s(m,j,C);case"For":return rt(m,j,C);case"Set":return Ur(m,j,C);case"Macro":return zr(m,j,C);case"Break":return R+St("break");case"Continue":return R+St("continue");case"CallStatement":return Wr(m,j,C);case"FilterStatement":return pr(m,j,C);case"Comment":return R+"{# "+m.value+" #}";default:return R+"{{- "+_t(m)+" -}}"}}function _s(m,j,C){let R=C.repeat(j),V=[],te=m;for(;te&&(V.push({test:te.test,body:te.body}),te.alternate.length===1&&te.alternate[0].type==="If");)te=te.alternate[0];let me=R+St("if",_t(V[0].test))+vt+er(V[0].body,j+1,C);for(let Ke=1;Ke<V.length;++Ke)me+=vt+R+St("elif",_t(V[Ke].test))+vt+er(V[Ke].body,j+1,C);return te&&te.alternate.length>0&&(me+=vt+R+St("else")+vt+er(te.alternate,j+1,C)),me+=vt+R+St("endif"),me}function rt(m,j,C){let R=C.repeat(j),V="";if(m.iterable.type==="SelectExpression"){let me=m.iterable;V=`${_t(me.lhs)} if ${_t(me.test)}`}else V=_t(m.iterable);let te=R+St("for",_t(m.loopvar),"in",V)+vt+er(m.body,j+1,C);return m.defaultBlock.length>0&&(te+=vt+R+St("else")+vt+er(m.defaultBlock,j+1,C)),te+=vt+R+St("endfor"),te}function Ur(m,j,C){let R=C.repeat(j),V=_t(m.assignee),te=m.value?_t(m.value):"",me=R+St("set",`${V}${m.value?" = "+te:""}`);return m.body.length===0?me:me+vt+er(m.body,j+1,C)+vt+R+St("endset")}function zr(m,j,C){let R=C.repeat(j),V=m.args.map(_t).join(", ");return R+St("macro",`${m.name.value}(${V})`)+vt+er(m.body,j+1,C)+vt+R+St("endmacro")}function Wr(m,j,C){let R=C.repeat(j),V=m.callerArgs&&m.callerArgs.length>0?`(${m.callerArgs.map(_t).join(", ")})`:"",te=_t(m.call),me=R+St(`call${V}`,te)+vt;return me+=er(m.body,j+1,C)+vt,me+=R+St("endcall"),me}function pr(m,j,C){let R=C.repeat(j),V=m.filter.type==="Identifier"?m.filter.value:_t(m.filter),te=R+St("filter",V)+vt;return te+=er(m.body,j+1,C)+vt,te+=R+St("endfilter"),te}function _t(m,j=-1){switch(m.type){case"SpreadExpression":return`*${_t(m.argument)}`;case"Identifier":return m.value;case"IntegerLiteral":return`${m.value}`;case"FloatLiteral":return`${m.value}`;case"StringLiteral":return JSON.stringify(m.value);case"BinaryExpression":{let C=m,R=cs(C),V=_t(C.left,R),te=_t(C.right,R+1),me=`${V} ${C.operator.value} ${te}`;return R<j?`(${me})`:me}case"UnaryExpression":{let C=m;return C.operator.value+(C.operator.value==="not"?" ":"")+_t(C.argument,1/0)}case"CallExpression":{let C=m,R=C.args.map(_t).join(", ");return`${_t(C.callee)}(${R})`}case"MemberExpression":{let C=m,R=_t(C.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(C.object.type)||(R=`(${R})`);let V=_t(C.property);return!C.computed&&C.property.type!=="Identifier"&&(V=`(${V})`),C.computed?`${R}[${V}]`:`${R}.${V}`}case"FilterExpression":{let C=m,R=_t(C.operand,1/0);return C.filter.type==="CallExpression"?`${R} | ${_t(C.filter)}`:`${R} | ${C.filter.value}`}case"SelectExpression":{let C=m;return`${_t(C.lhs)} if ${_t(C.test)}`}case"TestExpression":{let C=m;return`${_t(C.operand)} is${C.negate?" not":""} ${C.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let C=m.value.map(_t),R=m.type==="ArrayLiteral"?"[]":"()";return`${R[0]}${C.join(", ")}${R[1]}`}case"ObjectLiteral":return`{${Array.from(m.value.entries()).map(([R,V])=>`${_t(R)}: ${_t(V)}`).join(", ")}}`;case"SliceExpression":{let C=m,R=C.start?_t(C.start):"",V=C.stop?_t(C.stop):"",te=C.step?`:${_t(C.step)}`:"";return`${R}:${V}${te}`}case"KeywordArgumentExpression":{let C=m;return`${C.key.value}=${_t(C.value)}`}case"Ternary":{let C=m,R=`${_t(C.trueExpr)} if ${_t(C.condition,0)} else ${_t(C.falseExpr)}`;return j>-1?`(${R})`:R}default:throw new Error(`Unknown expression type: ${m.type}`)}}var Gr=class{constructor(m){v(this,"parsed");let j=f(m,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=xe(j)}render(m){let j=new et;if(Ue(j),m)for(let[V,te]of Object.entries(m))j.set(V,te);return new bt(j).run(this.parsed).value}format(m){return ds(this.parsed,m?.indent||" ")}}},"./src/backends/onnx.js":(d,t,e)=>{var r;e.r(t),e.d(t,{Tensor:()=>u.Tensor,createInferenceSession:()=>z,deviceToExecutionProviders:()=>E,isONNXProxy:()=>D,isONNXTensor:()=>x,runInferenceSession:()=>N});var o=e("./src/env.js"),a=e("?2ce3"),h=e("onnxruntime-web"),u=e("onnxruntime-common");let l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),p=[],w,f,i=Symbol.for("onnxruntime");if(i in globalThis)f=globalThis[i];else if(o.apis.IS_NODE_ENV){switch(f=a??(r||(r=e.t(a,2))),process.platform){case"win32":p.push("dml");break;case"linux":process.arch==="x64"&&p.push("cuda");break;case"darwin":break}p.push("cpu"),w=["cpu"]}else f=h,o.apis.IS_WEBNN_AVAILABLE&&p.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&p.push("webgpu"),p.push("wasm"),w=["wasm"];let y=f.InferenceSession;function E(_=null){if(!_)return w;switch(_){case"auto":return p;case"gpu":return p.filter(M=>["webgpu","cuda","dml","webnn-gpu"].includes(M))}if(p.includes(_))return[l[_]??_];throw new Error(`Unsupported device: "${_}". Should be one of: ${p.join(", ")}.`)}let S=null;async function z(_,M,I){S&&await S;let O=y.create(_,M);S??(S=O);let G=await O;return G.config=I,G}let k=Promise.resolve(),A=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;async function N(_,M){let I=()=>_.run(M);return await(A?k=k.then(I):I())}function x(_){return _ instanceof f.Tensor}let P=f?.env;P?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!P.wasm.wasmPaths&&(P.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),P.wasm.proxy=!1),P?.webgpu&&(P.webgpu.powerPreference="high-performance");function D(){return P?.wasm?.proxy}o.env.backends.onnx=P},"./src/base/feature_extraction_utils.js":(d,t,e)=>{e.r(t),e.d(t,{FeatureExtractor:()=>h,validate_audio_inputs:()=>u});var r=e("./src/utils/constants.js"),o=e("./src/utils/generic.js"),a=e("./src/utils/hub.js");class h extends o.Callable{constructor(p){super(),this.config=p}static async from_pretrained(p,w={}){let f=await(0,a.getModelJSON)(p,r.FEATURE_EXTRACTOR_NAME,!0,w);return new this(f)}}function u(l,p){if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${p} expects input to be a Float32Array or a Float64Array, but got ${l?.constructor?.name??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(d,t,e)=>{e.r(t),e.d(t,{ImageProcessor:()=>P,center_to_corners_format:()=>i,post_process_instance_segmentation:()=>x,post_process_object_detection:()=>y,post_process_panoptic_segmentation:()=>N,post_process_semantic_segmentation:()=>E});var r=e("./src/utils/generic.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/maths.js"),h=e("./src/utils/image.js"),u=e("./src/utils/core.js"),l=e("./src/utils/hub.js"),p=e("./src/utils/constants.js");function w(D,_,M=0,I=null){let O=D/_,G=(0,a.bankers_round)(O)*_;return I!==null&&G>I&&(G=Math.floor(O)*_),G<M&&(G=Math.ceil(O)*_),G}function f([D,_],M){return[Math.max(Math.floor(D/M),1)*M,Math.max(Math.floor(_/M),1)*M]}function i([D,_,M,I]){return[D-M/2,_-I/2,D+M/2,_+I/2]}function y(D,_=.5,M=null,I=!1){let O=D.logits,G=D.pred_boxes,[U,B,Q]=O.dims;if(M!==null&&M.length!==U)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let $=[];for(let Y=0;Y<U;++Y){let se=M!==null?M[Y]:null,oe={boxes:[],classes:[],scores:[]},ue=O[Y],be=G[Y];for(let pe=0;pe<B;++pe){let J=ue[pe],F=[],K;if(I){K=J.sigmoid().data;for(let Z=0;Z<K.length;++Z)K[Z]>_&&F.push(Z)}else{let Z=(0,a.max)(J.data)[1];if(Z===Q-1||(K=(0,a.softmax)(J.data),K[Z]<_))continue;F.push(Z)}for(let Z of F){let ie=be[pe].data;ie=i(ie),se!==null&&(ie=ie.map((xe,ye)=>xe*se[(ye+1)%2])),oe.boxes.push(ie),oe.classes.push(Z),oe.scores.push(K[Z])}}$.push(oe)}return $}function E(D,_=null){let M=D.logits,I=M.dims[0];if(_!==null&&_.length!==I)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let O=[];for(let G=0;G<I;++G){let U=_!==null?_[G]:null,B=M[G];U!==null&&(B=(0,o.interpolate)(B,U,"bilinear",!1));let[Q,$]=U??B.dims.slice(-2),Y=new o.Tensor("int32",new Int32Array(Q*$),[Q,$]),se=B[0].data,oe=Y.data;for(let pe=1;pe<B.dims[0];++pe){let J=B[pe].data;for(let F=0;F<J.length;++F)J[F]>se[F]&&(se[F]=J[F],oe[F]=pe)}let ue=new Array(B.dims[0]);for(let pe=0;pe<oe.length;++pe){let J=oe[pe];ue[J]=J}let be=ue.filter(pe=>pe!==void 0);O.push({segmentation:Y,labels:be})}return O}function S(D,_,M,I){let O=[],G=[],U=[];for(let B=0;B<D.dims[0];++B){let Q=D[B],$=_[B],Y=(0,a.max)(Q.data)[1];if(Y===I)continue;let oe=(0,a.softmax)(Q.data)[Y];oe>M&&(O.push($),G.push(oe),U.push(Y))}return[O,G,U]}function z(D,_,M,I=.5,O=.8){let G=[],U=0,B=0,Q=_[M].data;for(let Y=0;Y<D.length;++Y)D[Y]===M&&(G.push(Y),++U),Q[Y]>=I&&++B;let $=U>0&&B>0;return $&&($=U/B>O),[$,G]}function k(D,_,M,I,O,G=null,U=null){let[B,Q]=U??D[0].dims,$=new o.Tensor("int32",new Int32Array(B*Q),[B,Q]),Y=[];if(U!==null)for(let pe=0;pe<D.length;++pe)D[pe]=(0,o.interpolate)(D[pe],U,"bilinear",!1);let se=new Int32Array(D[0].data.length),oe=new Float32Array(D[0].data.length);for(let pe=0;pe<D.length;++pe){let J=_[pe],F=D[pe].data;for(let K=0;K<F.length;++K)F[K]*=J,F[K]>oe[K]&&(se[K]=pe,oe[K]=F[K])}let ue=0,be=$.data;for(let pe=0;pe<M.length;++pe){let J=M[pe],[F,K]=z(se,D,pe,I,O);if(F){++ue;for(let Z of K)be[Z]=ue;Y.push({id:ue,label_id:J,score:_[pe]})}}return[$,Y]}function A(D,_,M=28,I=56*56,O=14*14*4*1280){if(D<M||_<M)throw new Error(`height:${D} or width:${_} must be larger than factor:${M}`);if(Math.max(D,_)/Math.min(D,_)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(D,_)/Math.min(D,_)}`);let G=Math.round(D/M)*M,U=Math.round(_/M)*M;if(G*U>O){let B=Math.sqrt(D*_/O);G=Math.floor(D/B/M)*M,U=Math.floor(_/B/M)*M}else if(G*U<I){let B=Math.sqrt(I/(D*_));G=Math.ceil(D*B/M)*M,U=Math.ceil(_*B/M)*M}return[G,U]}function N(D,_=.5,M=.5,I=.8,O=null,G=null){O===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),O=new Set);let U=D.class_queries_logits??D.logits,Q=(D.masks_queries_logits??D.pred_masks).sigmoid(),[$,Y,se]=U.dims;if(se-=1,G!==null&&G.length!==$)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let oe=[];for(let ue=0;ue<$;++ue){let be=G!==null?G[ue]:null,pe=U[ue],J=Q[ue],[F,K,Z]=S(pe,J,_,se);if(Z.length===0){let[ye,Oe]=be??J.dims.slice(-2),He=new o.Tensor("int32",new Int32Array(ye*Oe).fill(-1),[ye,Oe]);oe.push({segmentation:He,segments_info:[]});continue}let[ie,xe]=k(F,K,Z,M,I,O,be);oe.push({segmentation:ie,segments_info:xe})}return oe}function x(D,_=.5,M=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}class P extends r.Callable{constructor(_){super(),this.image_mean=_.image_mean??_.mean,this.image_std=_.image_std??_.std,this.resample=_.resample??2,this.do_rescale=_.do_rescale??!0,this.rescale_factor=_.rescale_factor??1/255,this.do_normalize=_.do_normalize,this.do_thumbnail=_.do_thumbnail,this.size=_.size??_.image_size,this.do_resize=_.do_resize??this.size!==void 0,this.size_divisibility=_.size_divisibility??_.size_divisor,this.do_center_crop=_.do_center_crop,this.crop_size=_.crop_size,this.do_convert_rgb=_.do_convert_rgb??!0,this.do_crop_margin=_.do_crop_margin,this.pad_size=_.pad_size,this.do_pad=_.do_pad,this.min_pixels=_.min_pixels,this.max_pixels=_.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=_.do_flip_channel_order??!1,this.config=_}async thumbnail(_,M,I=2){let O=_.height,G=_.width,U=M.height,B=M.width,Q=Math.min(O,U),$=Math.min(G,B);return Q===O&&$===G?_:(O>G?$=Math.floor(G*Q/O):G>O&&(Q=Math.floor(O*$/G)),await _.resize($,Q,{resample:I}))}async crop_margin(_,M=200){let I=_.clone().grayscale(),O=(0,a.min)(I.data)[0],U=(0,a.max)(I.data)[0]-O;if(U===0)return _;let B=M/255,Q=I.width,$=I.height,Y=0,se=0,oe=I.data;for(let ue=0;ue<I.height;++ue){let be=ue*I.width;for(let pe=0;pe<I.width;++pe)(oe[be+pe]-O)/U<B&&(Q=Math.min(Q,pe),$=Math.min($,ue),Y=Math.max(Y,pe),se=Math.max(se,ue))}return _=await _.crop([Q,$,Y,se]),_}pad_image(_,M,I,{mode:O="constant",center:G=!1,constant_values:U=0}={}){let[B,Q,$]=M,Y,se;if(typeof I=="number"?(Y=I,se=I):I==="square"?Y=se=Math.max(B,Q):(Y=I.width,se=I.height),Y!==Q||se!==B){let oe=new Float32Array(Y*se*$);if(Array.isArray(U))for(let pe=0;pe<oe.length;++pe)oe[pe]=U[pe%$];else U!==0&&oe.fill(U);let[ue,be]=G?[Math.floor((Y-Q)/2),Math.floor((se-B)/2)]:[0,0];for(let pe=0;pe<B;++pe){let J=(pe+be)*Y,F=pe*Q;for(let K=0;K<Q;++K){let Z=(J+K+ue)*$,ie=(F+K)*$;for(let xe=0;xe<$;++xe)oe[Z+xe]=_[ie+xe]}}if(O==="symmetric"){if(G)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let pe=B-1,J=Q-1;for(let F=0;F<se;++F){let K=F*Y,Z=(0,u.calculateReflectOffset)(F,pe)*Q;for(let ie=0;ie<Y;++ie){if(F<B&&ie<Q)continue;let xe=(K+ie)*$,ye=(Z+(0,u.calculateReflectOffset)(ie,J))*$;for(let Oe=0;Oe<$;++Oe)oe[xe+Oe]=_[ye+Oe]}}}_=oe,M=[se,Y,$]}return[_,M]}rescale(_){for(let M=0;M<_.length;++M)_[M]=this.rescale_factor*_[M]}get_resize_output_image_size(_,M){let[I,O]=_.size,G,U;if(this.do_thumbnail){let{height:B,width:Q}=M;G=Math.min(B,Q)}else Number.isInteger(M)?(G=M,U=this.config.max_size??G):M!==void 0&&(G=M.shortest_edge,U=M.longest_edge);if(G!==void 0||U!==void 0){let B=G===void 0?1:Math.max(G/I,G/O),Q=I*B,$=O*B,Y=U===void 0?1:Math.min(U/Q,U/$),se=Math.floor(Number((Q*Y).toFixed(2))),oe=Math.floor(Number(($*Y).toFixed(2)));return this.size_divisibility!==void 0&&([se,oe]=f([se,oe],this.size_divisibility)),[se,oe]}else if(M!==void 0&&M.width!==void 0&&M.height!==void 0){let B=M.width,Q=M.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let $=Q/O,Y=B/I;Math.abs(1-Y)<Math.abs(1-$)?$=Y:Y=$,Q=w($*O,this.config.ensure_multiple_of),B=w(Y*I,this.config.ensure_multiple_of)}return[B,Q]}else{if(this.size_divisibility!==void 0)return f([I,O],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let B=this.config.patch_size*this.config.merge_size;return A(O,I,B,this.min_pixels,this.max_pixels)}else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(M)}`)}}async resize(_){let[M,I]=this.get_resize_output_image_size(_,this.size);return await _.resize(M,I,{resample:this.resample})}async preprocess(_,{do_normalize:M=null,do_pad:I=null,do_convert_rgb:O=null,do_convert_grayscale:G=null,do_flip_channel_order:U=null}={}){this.do_crop_margin&&(_=await this.crop_margin(_));let[B,Q]=_.size;if(O??this.do_convert_rgb?_=_.rgb():G&&(_=_.grayscale()),this.do_resize&&(_=await this.resize(_)),this.do_thumbnail&&(_=await this.thumbnail(_,this.size,this.resample)),this.do_center_crop){let ue,be;Number.isInteger(this.crop_size)?(ue=this.crop_size,be=this.crop_size):(ue=this.crop_size.width,be=this.crop_size.height),_=await _.center_crop(ue,be)}let $=[_.height,_.width],Y=Float32Array.from(_.data),se=[_.height,_.width,_.channels];if(this.do_rescale&&this.rescale(Y),M??this.do_normalize){let ue=this.image_mean;Array.isArray(this.image_mean)||(ue=new Array(_.channels).fill(ue));let be=this.image_std;if(Array.isArray(this.image_std)||(be=new Array(_.channels).fill(be)),ue.length!==_.channels||be.length!==_.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${ue.length}) and \`image_std\` (${be.length}) must match the number of channels in the image (${_.channels}).`);for(let pe=0;pe<Y.length;pe+=_.channels)for(let J=0;J<_.channels;++J)Y[pe+J]=(Y[pe+J]-ue[J])/be[J]}if(I??this.do_pad){if(this.pad_size)[Y,se]=this.pad_image(Y,[_.height,_.width,_.channels],this.pad_size);else if(this.size_divisibility){let[ue,be]=f([se[1],se[0]],this.size_divisibility);[Y,se]=this.pad_image(Y,se,{width:ue,height:be})}}if(U??this.do_flip_channel_order){if(se[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let ue=0;ue<Y.length;ue+=3){let be=Y[ue];Y[ue]=Y[ue+2],Y[ue+2]=be}}let oe=new o.Tensor("float32",Y,se).permute(2,0,1);return{original_size:[Q,B],reshaped_input_size:$,pixel_values:oe}}async _call(_,...M){Array.isArray(_)||(_=[_]);let I=await Promise.all(_.map(G=>this.preprocess(G)));return{pixel_values:(0,o.stack)(I.map(G=>G.pixel_values),0),original_sizes:I.map(G=>G.original_size),reshaped_input_sizes:I.map(G=>G.reshaped_input_size)}}static async from_pretrained(_,M={}){let I=await(0,l.getModelJSON)(_,p.IMAGE_PROCESSOR_NAME,!0,M);return new this(I)}}},"./src/base/processing_utils.js":(d,t,e)=>{e.r(t),e.d(t,{Processor:()=>h});var r=e("./src/utils/constants.js"),o=e("./src/utils/generic.js"),a=e("./src/utils/hub.js");class h extends o.Callable{constructor(l,p,w){super(),this.config=l,this.components=p,this.chat_template=w}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(l,p={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...p})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...p){for(let w of[this.image_processor,this.feature_extractor,this.tokenizer])if(w)return w(l,...p);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,p={}){let[w,f,i]=await Promise.all([this.uses_processor_config?(0,a.getModelJSON)(l,r.PROCESSOR_NAME,!0,p):{},Promise.all(this.classes.filter(y=>y in this).map(async y=>{let E=await this[y].from_pretrained(l,p);return[y.replace(/_class$/,""),E]})).then(Object.fromEntries),this.uses_chat_template_file?(0,a.getModelText)(l,r.CHAT_TEMPLATE_NAME,!0,p):null]);return new this(w,f,i)}}v(h,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),v(h,"uses_processor_config",!1),v(h,"uses_chat_template_file",!1)},"./src/configs.js":(d,t,e)=>{e.r(t),e.d(t,{AutoConfig:()=>w,PretrainedConfig:()=>p,getCacheShapes:()=>u});var r=e("./src/utils/core.js"),o=e("./src/utils/hub.js");async function a(f,i){return await(0,o.getModelJSON)(f,"config.json",!0,i)}function h(f){let i={},y={};switch(f.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"mistral3":y=h(f.text_config);break;case"moondream1":y=h(f.phi_config);break;case"musicgen":y=h(f.decoder);break;case"multi_modality":y=h(f.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":i.num_heads="n_head",i.num_layers="n_layer",i.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":i.num_heads="num_attention_heads",i.num_layers="num_hidden_layers",i.hidden_size="hidden_size";break;case"llama":case"llama4_text":case"nanochat":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":i.num_heads="num_key_value_heads",i.num_layers="num_hidden_layers",i.hidden_size="hidden_size",i.num_attention_heads="num_attention_heads",i.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"ministral":case"ministral3":i.num_heads="num_key_value_heads",i.num_layers="num_hidden_layers",i.dim_kv="head_dim";break;case"openelm":i.num_heads="num_kv_heads",i.num_layers="num_transformer_layers",i.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":i.num_heads="num_heads",i.num_layers="num_layers",i.hidden_size="hidden_size";break;case"bloom":i.num_heads="n_head",i.num_layers="n_layer",i.hidden_size="hidden_size";break;case"mpt":i.num_heads="n_heads",i.num_layers="n_layers",i.hidden_size="d_model";break;case"exaone":i.num_heads="num_key_value_heads",i.num_layers="num_layers",i.dim_kv="head_dim",i.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":i.num_decoder_layers="num_decoder_layers",i.num_decoder_heads="num_heads",i.decoder_dim_kv="d_kv",i.num_encoder_layers="num_layers",i.num_encoder_heads="num_heads",i.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":i.num_decoder_layers="decoder_layers",i.num_decoder_heads="decoder_attention_heads",i.decoder_hidden_size="d_model",i.num_encoder_layers="encoder_layers",i.num_encoder_heads="encoder_attention_heads",i.encoder_hidden_size="d_model";break;case"speecht5":i.num_decoder_layers="decoder_layers",i.num_decoder_heads="decoder_attention_heads",i.decoder_hidden_size="hidden_size",i.num_encoder_layers="encoder_layers",i.num_encoder_heads="encoder_attention_heads",i.encoder_hidden_size="hidden_size";break;case"trocr":i.num_encoder_layers=i.num_decoder_layers="decoder_layers",i.num_encoder_heads=i.num_decoder_heads="decoder_attention_heads",i.encoder_hidden_size=i.decoder_hidden_size="d_model";break;case"musicgen_decoder":i.num_encoder_layers=i.num_decoder_layers="num_hidden_layers",i.num_encoder_heads=i.num_decoder_heads="num_attention_heads",i.encoder_hidden_size=i.decoder_hidden_size="hidden_size";break;case"moonshine":i.num_decoder_layers="decoder_num_hidden_layers",i.num_decoder_heads="decoder_num_key_value_heads",i.num_encoder_layers="encoder_num_hidden_layers",i.num_encoder_heads="encoder_num_key_value_heads",i.encoder_hidden_size=i.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let S=h(f.decoder),z="num_decoder_layers"in S,k=(0,r.pick)(f,["model_type","is_encoder_decoder"]);return z?(k.num_decoder_layers=S.num_decoder_layers,k.num_decoder_heads=S.num_decoder_heads,k.decoder_hidden_size=S.decoder_hidden_size,k.num_encoder_layers=S.num_encoder_layers,k.num_encoder_heads=S.num_encoder_heads,k.encoder_hidden_size=S.encoder_hidden_size):(k.num_layers=S.num_layers,k.num_heads=S.num_heads,k.hidden_size=S.hidden_size),k}let E={...y,...(0,r.pick)(f,["model_type","multi_query","is_encoder_decoder"])};for(let S in i)E[S]=f[i[S]];return E}function u(f,i){if(f.model_type==="lfm2"){let y=i?.prefix??"past_key_values",E=y==="present"?"present":"past",S={},{layer_types:z,num_attention_heads:k,num_key_value_heads:A,hidden_size:N,conv_L_cache:x}=f,P=N/k,D=i?.batch_size??1;for(let _=0;_<z.length;++_)if(z[_]==="full_attention")for(let M of["key","value"])S[`${y}.${_}.${M}`]=[D,A,0,P];else if(z[_]==="conv")S[`${E}_conv.${_}`]=[D,N,x];else throw new Error(`Unsupported layer type: ${z[_]}`);return S}return l(f,i)}function l(f,{prefix:i="past_key_values",batch_size:y=1}={}){let E={},S=f.normalized_config;if(S.is_encoder_decoder&&"num_encoder_heads"in S&&"num_decoder_heads"in S){let z=S.encoder_dim_kv??S.encoder_hidden_size/S.num_encoder_heads,k=S.decoder_dim_kv??S.decoder_hidden_size/S.num_decoder_heads,A=[y,S.num_encoder_heads,0,z],N=[y,S.num_decoder_heads,0,k];for(let x=0;x<S.num_decoder_layers;++x)E[`${i}.${x}.encoder.key`]=A,E[`${i}.${x}.encoder.value`]=A,E[`${i}.${x}.decoder.key`]=N,E[`${i}.${x}.decoder.value`]=N}else{let z=S.num_heads,k=S.num_layers,A=S.dim_kv??S.hidden_size/(S.num_attention_heads??z);if(S.model_type==="falcon"){let N=[y*z,0,A];for(let x=0;x<k;++x)E[`${i}.${x}.key`]=N,E[`${i}.${x}.value`]=N}else if(S.multi_query){let N=[y*z,0,2*A];for(let x=0;x<k;++x)E[`${i}.${x}.key_value`]=N}else if(S.model_type==="bloom"){let N=[y*z,A,0],x=[y*z,0,A];for(let P=0;P<k;++P)E[`${i}.${P}.key`]=N,E[`${i}.${P}.value`]=x}else if(S.model_type==="openelm")for(let N=0;N<k;++N){let x=[y,z[N],0,A];E[`${i}.${N}.key`]=x,E[`${i}.${N}.value`]=x}else{let N=[y,z,0,A];for(let x=0;x<k;++x)E[`${i}.${x}.key`]=N,E[`${i}.${x}.value`]=N}}return E}class p{constructor(i){v(this,"model_type",null);v(this,"is_encoder_decoder",!1);v(this,"max_position_embeddings");v(this,"transformers.js_config");Object.assign(this,i),this.normalized_config=h(this)}static async from_pretrained(i,{progress_callback:y=null,config:E=null,cache_dir:S=null,local_files_only:z=!1,revision:k="main"}={}){E&&!(E instanceof p)&&(E=new p(E));let A=E??await a(i,{progress_callback:y,config:E,cache_dir:S,local_files_only:z,revision:k});return new this(A)}}class w{static async from_pretrained(...i){return p.from_pretrained(...i)}}},"./src/env.js":(d,t,e)=>{e.r(t),e.d(t,{apis:()=>A,env:()=>M});var r=e("?db59"),o=e("?383f"),a=e("?fa4b");let h="3.8.1",u=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),p=typeof self<"u"&&"caches"in self,w=typeof navigator<"u"&&"gpu"in navigator,f=typeof navigator<"u"&&"ml"in navigator,i=typeof process<"u",y=i&&process?.release?.name==="node",E=!I(r),S=!I(o),z=typeof globalThis.Deno<"u",k=typeof globalThis.Bun<"u",A=Object.freeze({IS_BROWSER_ENV:u,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:p,IS_WEBGPU_AVAILABLE:w,IS_WEBNN_AVAILABLE:f,IS_PROCESS_AVAILABLE:i,IS_NODE_ENV:y,IS_FS_AVAILABLE:E,IS_PATH_AVAILABLE:S}),N=E&&S,x="./";if(N){let O=Object(uS).url;O?x=o.dirname(o.dirname(a.fileURLToPath(O))):typeof __dirname<"u"&&(x=o.dirname(__dirname))}let P=N?o.join(x,"/.cache/"):null,D="/models/",_=N?o.join(x,D):D,M={version:h,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(u||l),localModelPath:_,useFS:E,useBrowserCache:p&&!z,useFSCache:E,cacheDir:P,useCustomCache:!1,customCache:null};function I(O){return Object.keys(O).length===0}},"./src/generation/configuration_utils.js":(d,t,e)=>{e.r(t),e.d(t,{GenerationConfig:()=>o});var r=e("./src/utils/core.js");class o{constructor(h){v(this,"max_length",20);v(this,"max_new_tokens",null);v(this,"min_length",0);v(this,"min_new_tokens",null);v(this,"early_stopping",!1);v(this,"max_time",null);v(this,"do_sample",!1);v(this,"num_beams",1);v(this,"num_beam_groups",1);v(this,"penalty_alpha",null);v(this,"use_cache",!0);v(this,"temperature",1);v(this,"top_k",50);v(this,"top_p",1);v(this,"typical_p",1);v(this,"epsilon_cutoff",0);v(this,"eta_cutoff",0);v(this,"diversity_penalty",0);v(this,"repetition_penalty",1);v(this,"encoder_repetition_penalty",1);v(this,"length_penalty",1);v(this,"no_repeat_ngram_size",0);v(this,"bad_words_ids",null);v(this,"force_words_ids",null);v(this,"renormalize_logits",!1);v(this,"constraints",null);v(this,"forced_bos_token_id",null);v(this,"forced_eos_token_id",null);v(this,"remove_invalid_values",!1);v(this,"exponential_decay_length_penalty",null);v(this,"suppress_tokens",null);v(this,"streamer",null);v(this,"begin_suppress_tokens",null);v(this,"forced_decoder_ids",null);v(this,"guidance_scale",null);v(this,"num_return_sequences",1);v(this,"output_attentions",!1);v(this,"output_hidden_states",!1);v(this,"output_scores",!1);v(this,"return_dict_in_generate",!1);v(this,"pad_token_id",null);v(this,"bos_token_id",null);v(this,"eos_token_id",null);v(this,"encoder_no_repeat_ngram_size",0);v(this,"decoder_start_token_id",null);v(this,"generation_kwargs",{});Object.assign(this,(0,r.pick)(h,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(d,t,e)=>{e.r(t),e.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>A,ForcedBOSTokenLogitsProcessor:()=>p,ForcedEOSTokenLogitsProcessor:()=>w,LogitsProcessor:()=>h,LogitsProcessorList:()=>l,LogitsWarper:()=>u,MinLengthLogitsProcessor:()=>S,MinNewTokensLengthLogitsProcessor:()=>z,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>y,RepetitionPenaltyLogitsProcessor:()=>E,SuppressTokensAtBeginLogitsProcessor:()=>f,TemperatureLogitsWarper:()=>N,TopKLogitsWarper:()=>P,TopPLogitsWarper:()=>x,WhisperTimeStampLogitsProcessor:()=>i});var r=e("./src/utils/generic.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/maths.js");class h extends r.Callable{_call(_,M){throw Error("`_call` should be implemented in a subclass")}}class u extends r.Callable{_call(_,M){throw Error("`_call` should be implemented in a subclass")}}class l extends r.Callable{constructor(){super(),this.processors=[]}push(_){this.processors.push(_)}extend(_){this.processors.push(..._)}_call(_,M){let I=M;for(let O of this.processors)I=O(_,I);return I}[Symbol.iterator](){return this.processors.values()}}class p extends h{constructor(_){super(),this.bos_token_id=_}_call(_,M){for(let I=0;I<_.length;++I)if(_[I].length===1){let O=M[I].data;O.fill(-1/0),O[this.bos_token_id]=0}return M}}class w extends h{constructor(_,M){super(),this.max_length=_,this.eos_token_id=Array.isArray(M)?M:[M]}_call(_,M){for(let I=0;I<_.length;++I)if(_[I].length===this.max_length-1){let O=M[I].data;O.fill(-1/0);for(let G of this.eos_token_id)O[G]=0}return M}}class f extends h{constructor(_,M){super(),this.begin_suppress_tokens=_,this.begin_index=M}_call(_,M){for(let I=0;I<_.length;++I)if(_[I].length===this.begin_index){let O=M[I].data;for(let G of this.begin_suppress_tokens)O[G]=-1/0}return M}}class i extends h{constructor(_,M){super(),this.eos_token_id=Array.isArray(_.eos_token_id)?_.eos_token_id[0]:_.eos_token_id,this.no_timestamps_token_id=_.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=M.length,M.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=_.max_initial_timestamp_index}_call(_,M){for(let I=0;I<_.length;++I){let O=M[I].data;if(O[this.no_timestamps_token_id]=-1/0,_[I].length===this.begin_index-1){O.fill(-1/0),O[this.timestamp_begin]=0;continue}let G=_[I].slice(this.begin_index),U=G.length>=1&&G[G.length-1]>=this.timestamp_begin,B=G.length<2||G[G.length-2]>=this.timestamp_begin;if(U&&(B?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),_[I].length===this.begin_index&&this.max_initial_timestamp_index!==null){let se=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(se+1).fill(-1/0)}let Q=(0,a.log_softmax)(O),$=Math.log(Q.subarray(this.timestamp_begin).map(Math.exp).reduce((se,oe)=>se+oe)),Y=(0,a.max)(Q.subarray(0,this.timestamp_begin))[0];$>Y&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return M}}class y extends h{constructor(_){super(),this.no_repeat_ngram_size=_}getNgrams(_){let M=_.length,I=[];for(let G=0;G<M+1-this.no_repeat_ngram_size;++G){let U=[];for(let B=0;B<this.no_repeat_ngram_size;++B)U.push(_[G+B]);I.push(U.map(Number))}let O=new Map;for(let G of I){let U=G.slice(0,G.length-1),B=JSON.stringify(U),Q=O.get(B)??[];Q.push(G[G.length-1]),O.set(B,Q)}return O}getGeneratedNgrams(_,M){let I=M.slice(M.length+1-this.no_repeat_ngram_size,M.length);return _.get(JSON.stringify(I.map(Number)))??[]}calcBannedNgramTokens(_){let M=[];if(_.length+1<this.no_repeat_ngram_size)return M;{let I=this.getNgrams(_);return this.getGeneratedNgrams(I,_)}}_call(_,M){for(let I=0;I<_.length;++I){let O=M[I].data,G=this.calcBannedNgramTokens(_[I]);for(let U of G)O[U]=-1/0}return M}}class E extends h{constructor(_){super(),this.penalty=_}_call(_,M){for(let I=0;I<_.length;++I){let O=M[I].data;for(let G of new Set(_[I])){let U=Number(G);O[U]<0?O[U]*=this.penalty:O[U]/=this.penalty}}return M}}class S extends h{constructor(_,M){super(),this.min_length=_,this.eos_token_id=Array.isArray(M)?M:[M]}_call(_,M){for(let I=0;I<_.length;++I)if(_[I].length<this.min_length){let O=M[I].data;for(let G of this.eos_token_id)O[G]=-1/0}return M}}class z extends h{constructor(_,M,I){super(),this.prompt_length_to_skip=_,this.min_new_tokens=M,this.eos_token_id=Array.isArray(I)?I:[I]}_call(_,M){for(let I=0;I<_.length;++I)if(_[I].length-this.prompt_length_to_skip<this.min_new_tokens){let G=M[I].data;for(let U of this.eos_token_id)G[U]=-1/0}return M}}class k extends h{constructor(_,M){super(),this.bad_words_ids=_,this.eos_token_id=Array.isArray(M)?M:[M]}_call(_,M){for(let I=0;I<_.length;++I){let O=M[I].data,G=_[I];for(let U of this.bad_words_ids){if(G.length<U.length-1)continue;let B=!0;for(let Q=1;Q<=U.length-1;++Q)if(U.at(-Q-1)!=G.at(-Q)){B=!1;break}B&&(O[U.at(-1)]=-1/0)}}return M}}class A extends h{constructor(_){if(super(),_<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${_}.`);this.guidance_scale=_}_call(_,M){if(M.dims[0]!==2*_.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 ${M.dims[0]} for the logits and ${_.length} for the input ids.`);let I=_.length,O=M.slice([0,I],null),G=M.slice([I,M.dims[0]],null);for(let U=0;U<G.data.length;++U)G.data[U]+=(O.data[U]-G.data[U])*this.guidance_scale;return G}}class N extends u{constructor(_){if(super(),typeof _!="number"||_<=0){let M=`\`temperature\` (=${_}) must be a strictly positive float, otherwise your next token scores will be invalid.`;_===0&&(M+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=_}_call(_,M){let I=M.data;for(let O=0;O<I.length;++O)I[O]/=this.temperature;return M}}class x extends u{constructor(_,{filter_value:M=-1/0,min_tokens_to_keep:I=1}={}){if(super(),_<0||_>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${_}`);if(!Number.isInteger(I)||I<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${I}`);this.top_p=_,this.filter_value=M,this.min_tokens_to_keep=I}}class P extends u{constructor(_,{filter_value:M=-1/0,min_tokens_to_keep:I=1}={}){if(super(),!Number.isInteger(_)||_<0)throw new Error(`\`top_k\` must be a positive integer, but is ${_}`);this.top_k=Math.max(_,I),this.filter_value=M}}},"./src/generation/logits_sampler.js":(d,t,e)=>{e.r(t),e.d(t,{LogitsSampler:()=>u});var r=e("./src/utils/generic.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/maths.js"),h=e("./src/generation/configuration_utils.js");class u extends r.Callable{constructor(i){super(),this.generation_config=i}async _call(i){return this.sample(i)}async sample(i){throw Error("sample should be implemented in subclasses.")}getLogits(i,y){let E=i.dims.at(-1),S=i.data;if(y===-1)S=S.slice(-E);else{let z=y*E;S=S.slice(z,z+E)}return S}randomSelect(i){let y=0;for(let S=0;S<i.length;++S)y+=i[S];let E=Math.random()*y;for(let S=0;S<i.length;++S)if(E-=i[S],E<=0)return S;return 0}static getSampler(i){if(i.do_sample)return new p(i);if(i.num_beams>1)return new w(i);if(i.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${i.num_return_sequences}.`);return new l(i)}}class l extends u{async sample(i){let y=(0,a.max)(i.data)[1];return[[BigInt(y),0]]}}class p extends u{async sample(i){let y=i.dims.at(-1);this.generation_config.top_k>0&&(y=Math.min(this.generation_config.top_k,y));let[E,S]=await(0,o.topk)(i,y),z=(0,a.softmax)(E.data);return Array.from({length:this.generation_config.num_beams},()=>{let k=this.randomSelect(z);return[S.data[k],Math.log(z[k])]})}}class w extends u{async sample(i){let y=i.dims.at(-1);this.generation_config.top_k>0&&(y=Math.min(this.generation_config.top_k,y));let[E,S]=await(0,o.topk)(i,y),z=(0,a.softmax)(E.data);return Array.from({length:this.generation_config.num_beams},(k,A)=>[S.data[A],Math.log(z[A])])}}},"./src/generation/stopping_criteria.js":(d,t,e)=>{e.r(t),e.d(t,{EosTokenCriteria:()=>u,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>h,StoppingCriteria:()=>o,StoppingCriteriaList:()=>a});var r=e("./src/utils/generic.js");class o extends r.Callable{_call(w,f){throw Error("StoppingCriteria needs to be subclassed")}}class a extends r.Callable{constructor(){super(),this.criteria=[]}push(w){this.criteria.push(w)}extend(w){w instanceof a?w=w.criteria:w instanceof o&&(w=[w]),this.criteria.push(...w)}_call(w,f){let i=new Array(w.length).fill(!1);for(let y of this.criteria){let E=y(w,f);for(let S=0;S<i.length;++S)i[S]||(i[S]=E[S])}return i}[Symbol.iterator](){return this.criteria.values()}}class h extends o{constructor(w,f=null){super(),this.max_length=w,this.max_position_embeddings=f}_call(w){return w.map(f=>f.length>=this.max_length)}}class u extends o{constructor(w){super(),Array.isArray(w)||(w=[w]),this.eos_token_id=w}_call(w,f){return w.map(i=>{let y=i.at(-1);return this.eos_token_id.some(E=>y==E)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(w,f){return new Array(w.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(d,t,e)=>{e.r(t),e.d(t,{BaseStreamer:()=>h,TextStreamer:()=>l,WhisperTextStreamer:()=>p});var r=e("./src/utils/core.js"),o=e("./src/tokenizers.js"),a=e("./src/env.js");class h{put(f){throw Error("Not implemented")}end(){throw Error("Not implemented")}}let u=a.apis.IS_PROCESS_AVAILABLE?w=>process.stdout.write(w):w=>console.log(w);class l extends h{constructor(f,{skip_prompt:i=!1,callback_function:y=null,token_callback_function:E=null,skip_special_tokens:S=!0,decode_kwargs:z={},...k}={}){super(),this.tokenizer=f,this.skip_prompt=i,this.callback_function=y??u,this.token_callback_function=E,this.decode_kwargs={skip_special_tokens:S,...z,...k},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(f){if(f.length>1)throw Error("TextStreamer only supports batch size of 1");let i=this.next_tokens_are_prompt;if(i&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let y=f[0];this.token_callback_function?.(y),this.token_cache=(0,r.mergeArrays)(this.token_cache,y);let E=this.tokenizer.decode(this.token_cache,this.decode_kwargs),S;i||E.endsWith(`
10
- `)?(S=E.slice(this.print_len),this.token_cache=[],this.print_len=0):E.length>0&&(0,o.is_chinese_char)(E.charCodeAt(E.length-1))?(S=E.slice(this.print_len),this.print_len+=S.length):(S=E.slice(this.print_len,E.lastIndexOf(" ")+1),this.print_len+=S.length),this.on_finalized_text(S,!1)}end(){let f;this.token_cache.length>0?(f=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):f="",this.next_tokens_are_prompt=!0,this.on_finalized_text(f,!0)}on_finalized_text(f,i){f.length>0&&this.callback_function?.(f),i&&this.callback_function===u&&a.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
11
- `)}}class p extends l{constructor(f,{skip_prompt:i=!1,callback_function:y=null,token_callback_function:E=null,on_chunk_start:S=null,on_chunk_end:z=null,on_finalize:k=null,time_precision:A=.02,skip_special_tokens:N=!0,decode_kwargs:x={}}={}){super(f,{skip_prompt:i,skip_special_tokens:N,callback_function:y,token_callback_function:E,decode_kwargs:x}),this.timestamp_begin=f.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=z,this.on_finalize=k,this.time_precision=A,this.waiting_for_timestamp=!1}put(f){if(f.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let i=f[0];if(i.length===1){let y=Number(i[0])-this.timestamp_begin;if(y>=0){let E=y*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(E):this.on_chunk_start?.(E),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(i);return}}return super.put(f)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(d,t,e)=>{e.r(t),e.d(t,{ASTForAudioClassification:()=>Vi,ASTModel:()=>ji,ASTPreTrainedModel:()=>nn,AlbertForMaskedLM:()=>$e,AlbertForQuestionAnswering:()=>Be,AlbertForSequenceClassification:()=>We,AlbertModel:()=>Le,AlbertPreTrainedModel:()=>fe,ArceeForCausalLM:()=>Ll,ArceeModel:()=>Dl,ArceePreTrainedModel:()=>Cn,AutoModel:()=>Qa,AutoModelForAudioClassification:()=>tm,AutoModelForAudioFrameClassification:()=>sm,AutoModelForAudioTextToText:()=>um,AutoModelForCTC:()=>em,AutoModelForCausalLM:()=>Wp,AutoModelForDepthEstimation:()=>im,AutoModelForDocumentQuestionAnswering:()=>om,AutoModelForImageClassification:()=>Hp,AutoModelForImageFeatureExtraction:()=>dm,AutoModelForImageMatting:()=>nm,AutoModelForImageSegmentation:()=>Qp,AutoModelForImageTextToText:()=>_m,AutoModelForImageToImage:()=>am,AutoModelForMaskGeneration:()=>Zp,AutoModelForMaskedLM:()=>Gp,AutoModelForNormalEstimation:()=>lm,AutoModelForObjectDetection:()=>qp,AutoModelForPoseEstimation:()=>cm,AutoModelForQuestionAnswering:()=>Kp,AutoModelForSemanticSegmentation:()=>Xp,AutoModelForSeq2SeqLM:()=>jp,AutoModelForSequenceClassification:()=>Bp,AutoModelForSpeechSeq2Seq:()=>Vp,AutoModelForTextToSpectrogram:()=>Up,AutoModelForTextToWaveform:()=>zp,AutoModelForTokenClassification:()=>Np,AutoModelForUniversalSegmentation:()=>Jp,AutoModelForVision2Seq:()=>$p,AutoModelForXVector:()=>rm,AutoModelForZeroShotObjectDetection:()=>Yp,BartForConditionalGeneration:()=>At,BartForSequenceClassification:()=>Kt,BartModel:()=>Or,BartPretrainedModel:()=>Jt,BaseModelOutput:()=>de,BeitForImageClassification:()=>rd,BeitModel:()=>td,BeitPreTrainedModel:()=>aa,BertForMaskedLM:()=>ge,BertForQuestionAnswering:()=>ce,BertForSequenceClassification:()=>le,BertForTokenClassification:()=>ve,BertModel:()=>Te,BertPreTrainedModel:()=>he,BlenderbotForConditionalGeneration:()=>Rt,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>zt,BlenderbotSmallForConditionalGeneration:()=>us,BlenderbotSmallModel:()=>dr,BlenderbotSmallPreTrainedModel:()=>Lt,BloomForCausalLM:()=>xc,BloomModel:()=>bc,BloomPreTrainedModel:()=>Qn,CLIPModel:()=>el,CLIPPreTrainedModel:()=>Jr,CLIPSegForImageSegmentation:()=>ul,CLIPSegModel:()=>_l,CLIPSegPreTrainedModel:()=>gn,CLIPTextModel:()=>Ph,CLIPTextModelWithProjection:()=>tl,CLIPVisionModel:()=>bh,CLIPVisionModelWithProjection:()=>rl,CamembertForMaskedLM:()=>te,CamembertForQuestionAnswering:()=>qe,CamembertForSequenceClassification:()=>me,CamembertForTokenClassification:()=>Ke,CamembertModel:()=>V,CamembertPreTrainedModel:()=>R,CausalLMOutput:()=>Nr,CausalLMOutputWithPast:()=>Nh,ChineseCLIPModel:()=>il,ChineseCLIPPreTrainedModel:()=>al,ClapAudioModelWithProjection:()=>wu,ClapModel:()=>gu,ClapPreTrainedModel:()=>io,ClapTextModelWithProjection:()=>Mu,CodeGenForCausalLM:()=>El,CodeGenModel:()=>yl,CodeGenPreTrainedModel:()=>xn,CohereForCausalLM:()=>rc,CohereModel:()=>tc,CoherePreTrainedModel:()=>Nn,ConvBertForMaskedLM:()=>rt,ConvBertForQuestionAnswering:()=>Wr,ConvBertForSequenceClassification:()=>Ur,ConvBertForTokenClassification:()=>zr,ConvBertModel:()=>_s,ConvBertPreTrainedModel:()=>gr,ConvNextForImageClassification:()=>Jd,ConvNextModel:()=>Xd,ConvNextPreTrainedModel:()=>va,ConvNextV2ForImageClassification:()=>Yd,ConvNextV2Model:()=>qd,ConvNextV2PreTrainedModel:()=>Pa,DFineForObjectDetection:()=>hd,DFineModel:()=>md,DFinePreTrainedModel:()=>ua,DINOv3ConvNextModel:()=>a_,DINOv3ConvNextPreTrainedModel:()=>n_,DINOv3ViTModel:()=>o_,DINOv3ViTPreTrainedModel:()=>s_,DPTForDepthEstimation:()=>Id,DPTModel:()=>Ad,DPTPreTrainedModel:()=>Ma,DacDecoderModel:()=>ip,DacDecoderOutput:()=>op,DacEncoderModel:()=>ap,DacEncoderOutput:()=>sp,DacModel:()=>np,DacPreTrainedModel:()=>ho,DebertaForMaskedLM:()=>Ge,DebertaForQuestionAnswering:()=>Qt,DebertaForSequenceClassification:()=>ct,DebertaForTokenClassification:()=>ft,DebertaModel:()=>st,DebertaPreTrainedModel:()=>je,DebertaV2ForMaskedLM:()=>Xt,DebertaV2ForQuestionAnswering:()=>Fr,DebertaV2ForSequenceClassification:()=>Cr,DebertaV2ForTokenClassification:()=>kr,DebertaV2Model:()=>ar,DebertaV2PreTrainedModel:()=>Ut,DecisionTransformerModel:()=>Vu,DecisionTransformerPreTrainedModel:()=>ju,DeiTForImageClassification:()=>Td,DeiTModel:()=>wd,DeiTPreTrainedModel:()=>ma,DepthAnythingForDepthEstimation:()=>Dd,DepthAnythingPreTrainedModel:()=>Sd,DepthProForDepthEstimation:()=>Nd,DepthProPreTrainedModel:()=>Bd,DetrForObjectDetection:()=>od,DetrForSegmentation:()=>ia,DetrModel:()=>sd,DetrObjectDetectionOutput:()=>la,DetrPreTrainedModel:()=>eo,DetrSegmentationOutput:()=>nd,Dinov2ForImageClassification:()=>e_,Dinov2Model:()=>Zd,Dinov2PreTrainedModel:()=>ba,Dinov2WithRegistersForImageClassification:()=>r_,Dinov2WithRegistersModel:()=>t_,Dinov2WithRegistersPreTrainedModel:()=>xa,DistilBertForMaskedLM:()=>Mr,DistilBertForQuestionAnswering:()=>mr,DistilBertForSequenceClassification:()=>Ar,DistilBertForTokenClassification:()=>$r,DistilBertModel:()=>Kr,DistilBertPreTrainedModel:()=>cr,DonutSwinModel:()=>Qd,DonutSwinPreTrainedModel:()=>Hd,EdgeTamModel:()=>g_,EfficientNetForImageClassification:()=>Eu,EfficientNetModel:()=>yu,EfficientNetPreTrainedModel:()=>Na,ElectraForMaskedLM:()=>Gr,ElectraForQuestionAnswering:()=>C,ElectraForSequenceClassification:()=>m,ElectraForTokenClassification:()=>j,ElectraModel:()=>_t,ElectraPreTrainedModel:()=>pr,Ernie4_5ForCausalLM:()=>uu,Ernie4_5Model:()=>_u,Ernie4_5PreTrainedModel:()=>Da,EsmForMaskedLM:()=>Ir,EsmForSequenceClassification:()=>Sr,EsmForTokenClassification:()=>Dr,EsmModel:()=>Hr,EsmPreTrainedModel:()=>wr,ExaoneForCausalLM:()=>Gl,ExaoneModel:()=>Wl,ExaonePreTrainedModel:()=>Sn,FalconForCausalLM:()=>fu,FalconModel:()=>hu,FalconPreTrainedModel:()=>Oa,FastViTForImageClassification:()=>Gc,FastViTModel:()=>Wc,FastViTPreTrainedModel:()=>ta,Florence2ForConditionalGeneration:()=>Hi,Florence2PreTrainedModel:()=>$i,GLPNForDepthEstimation:()=>$d,GLPNModel:()=>Kd,GLPNPreTrainedModel:()=>Ta,GPT2LMHeadModel:()=>ml,GPT2Model:()=>pl,GPT2PreTrainedModel:()=>Mn,GPTBigCodeForCausalLM:()=>xl,GPTBigCodeModel:()=>bl,GPTBigCodePreTrainedModel:()=>bn,GPTJForCausalLM:()=>Pl,GPTJModel:()=>vl,GPTJPreTrainedModel:()=>Pn,GPTNeoForCausalLM:()=>Ml,GPTNeoModel:()=>gl,GPTNeoPreTrainedModel:()=>Tn,GPTNeoXForCausalLM:()=>Tl,GPTNeoXModel:()=>wl,GPTNeoXPreTrainedModel:()=>vn,Gemma2ForCausalLM:()=>ac,Gemma2Model:()=>nc,Gemma2PreTrainedModel:()=>Vn,Gemma3ForCausalLM:()=>dc,Gemma3Model:()=>cc,Gemma3PreTrainedModel:()=>zn,Gemma3nForConditionalGeneration:()=>pn,Gemma3nPreTrainedModel:()=>qi,GemmaForCausalLM:()=>oc,GemmaModel:()=>sc,GemmaPreTrainedModel:()=>jn,GlmForCausalLM:()=>zl,GlmModel:()=>Ul,GlmPreTrainedModel:()=>In,GraniteForCausalLM:()=>Yl,GraniteModel:()=>ql,GraniteMoeHybridForCausalLM:()=>ec,GraniteMoeHybridModel:()=>Zl,GraniteMoeHybridPreTrainedModel:()=>Bn,GranitePreTrainedModel:()=>Rn,GroundingDinoForObjectDetection:()=>l_,GroundingDinoPreTrainedModel:()=>i_,GroupViTModel:()=>zc,GroupViTPreTrainedModel:()=>Uc,HeliumForCausalLM:()=>Vl,HeliumModel:()=>jl,HeliumPreTrainedModel:()=>An,HieraForImageClassification:()=>Pd,HieraModel:()=>vd,HieraPreTrainedModel:()=>ha,HubertForCTC:()=>G_,HubertForSequenceClassification:()=>K_,HubertModel:()=>W_,HubertPreTrainedModel:()=>xh,IJepaForImageClassification:()=>Sc,IJepaModel:()=>Ic,IJepaPreTrainedModel:()=>Yn,Idefics3ForConditionalGeneration:()=>Ys,Idefics3PreTrainedModel:()=>Yi,ImageMattingOutput:()=>mm,JAISLMHeadModel:()=>fl,JAISModel:()=>hl,JAISPreTrainedModel:()=>wn,JinaCLIPModel:()=>ll,JinaCLIPPreTrainedModel:()=>Zs,JinaCLIPTextModel:()=>cl,JinaCLIPVisionModel:()=>dl,Lfm2ForCausalLM:()=>Rl,Lfm2Model:()=>Ol,Lfm2PreTrainedModel:()=>kn,LiteWhisperForConditionalGeneration:()=>zi,Llama4ForCausalLM:()=>Al,Llama4PreTrainedModel:()=>Fl,LlamaForCausalLM:()=>kl,LlamaModel:()=>Cl,LlamaPreTrainedModel:()=>yn,LlavaForConditionalGeneration:()=>qs,LlavaOnevisionForConditionalGeneration:()=>Gi,LlavaPreTrainedModel:()=>_n,LlavaQwen2ForCausalLM:()=>un,LongT5ForConditionalGeneration:()=>tr,LongT5Model:()=>Pt,LongT5PreTrainedModel:()=>It,M2M100ForConditionalGeneration:()=>P_,M2M100Model:()=>v_,M2M100PreTrainedModel:()=>Ca,MBartForCausalLM:()=>br,MBartForConditionalGeneration:()=>yr,MBartForSequenceClassification:()=>sr,MBartModel:()=>Pr,MBartPreTrainedModel:()=>qt,MPNetForMaskedLM:()=>Lr,MPNetForQuestionAnswering:()=>re,MPNetForSequenceClassification:()=>Xr,MPNetForTokenClassification:()=>Is,MPNetModel:()=>Qr,MPNetPreTrainedModel:()=>xt,MT5ForConditionalGeneration:()=>vr,MT5Model:()=>lr,MT5PreTrainedModel:()=>rr,MarianMTModel:()=>T_,MarianModel:()=>w_,MarianPreTrainedModel:()=>Ea,MaskFormerForInstanceSegmentation:()=>Gd,MaskFormerModel:()=>Wd,MaskFormerPreTrainedModel:()=>wa,MaskedLMOutput:()=>Wt,Metric3DForDepthEstimation:()=>Vd,Metric3DPreTrainedModel:()=>jd,Metric3Dv2ForDepthEstimation:()=>zd,Metric3Dv2PreTrainedModel:()=>Ud,MgpstrForSceneTextRecognition:()=>Ku,MgpstrModelOutput:()=>Wu,MgpstrPreTrainedModel:()=>Gu,MimiDecoderModel:()=>rp,MimiDecoderOutput:()=>Zu,MimiEncoderModel:()=>tp,MimiEncoderOutput:()=>Yu,MimiModel:()=>ep,MimiPreTrainedModel:()=>mo,Ministral3ForCausalLM:()=>du,Ministral3Model:()=>cu,Ministral3PreTrainedModel:()=>Sa,MinistralForCausalLM:()=>lu,MinistralModel:()=>iu,MinistralPreTrainedModel:()=>Ia,Mistral3ForConditionalGeneration:()=>Ji,MistralForCausalLM:()=>au,MistralModel:()=>nu,MistralPreTrainedModel:()=>Aa,MobileBertForMaskedLM:()=>ke,MobileBertForQuestionAnswering:()=>Qe,MobileBertForSequenceClassification:()=>De,MobileBertModel:()=>ir,MobileBertPreTrainedModel:()=>Tr,MobileLLMForCausalLM:()=>$l,MobileLLMModel:()=>Kl,MobileLLMPreTrainedModel:()=>Dn,MobileNetV1ForImageClassification:()=>ku,MobileNetV1ForSemanticSegmentation:()=>Fu,MobileNetV1Model:()=>Cu,MobileNetV1PreTrainedModel:()=>co,MobileNetV2ForImageClassification:()=>Iu,MobileNetV2ForSemanticSegmentation:()=>Su,MobileNetV2Model:()=>Au,MobileNetV2PreTrainedModel:()=>_o,MobileNetV3ForImageClassification:()=>Lu,MobileNetV3ForSemanticSegmentation:()=>Ou,MobileNetV3Model:()=>Du,MobileNetV3PreTrainedModel:()=>uo,MobileNetV4ForImageClassification:()=>Bu,MobileNetV4ForSemanticSegmentation:()=>Nu,MobileNetV4Model:()=>Ru,MobileNetV4PreTrainedModel:()=>po,MobileViTForImageClassification:()=>Qc,MobileViTModel:()=>Hc,MobileViTPreTrainedModel:()=>ra,MobileViTV2ForImageClassification:()=>Jc,MobileViTV2Model:()=>Xc,MobileViTV2PreTrainedModel:()=>sa,ModelOutput:()=>X,ModernBertDecoderForCausalLM:()=>bt,ModernBertDecoderModel:()=>mt,ModernBertDecoderPreTrainedModel:()=>lt,ModernBertForMaskedLM:()=>Ae,ModernBertForSequenceClassification:()=>et,ModernBertForTokenClassification:()=>Ue,ModernBertModel:()=>ze,ModernBertPreTrainedModel:()=>Ve,Moondream1ForConditionalGeneration:()=>Ki,MoonshineForConditionalGeneration:()=>Wi,MoonshineModel:()=>vh,MoonshinePreTrainedModel:()=>cn,MptForCausalLM:()=>Ec,MptModel:()=>yc,MptPreTrainedModel:()=>Xn,MultiModalityCausalLM:()=>zu,MultiModalityPreTrainedModel:()=>Uu,MusicgenForCausalLM:()=>kh,MusicgenForConditionalGeneration:()=>Va,MusicgenModel:()=>Ch,MusicgenPreTrainedModel:()=>ja,NanoChatForCausalLM:()=>Sl,NanoChatModel:()=>Il,NanoChatPreTrainedModel:()=>En,NeoBertForMaskedLM:()=>Ce,NeoBertForQuestionAnswering:()=>Je,NeoBertForSequenceClassification:()=>Ie,NeoBertForTokenClassification:()=>Fe,NeoBertModel:()=>Re,NeoBertPreTrainedModel:()=>Me,NomicBertModel:()=>vt,NomicBertPreTrainedModel:()=>Vt,OPTForCausalLM:()=>kc,OPTModel:()=>Cc,OPTPreTrainedModel:()=>Jn,Olmo2ForCausalLM:()=>Jl,Olmo2Model:()=>Xl,Olmo2PreTrainedModel:()=>On,OlmoForCausalLM:()=>Ql,OlmoModel:()=>Hl,OlmoPreTrainedModel:()=>Ln,OpenELMForCausalLM:()=>uc,OpenELMModel:()=>_c,OpenELMPreTrainedModel:()=>Wn,OwlViTForObjectDetection:()=>Yc,OwlViTModel:()=>qc,OwlViTPreTrainedModel:()=>oa,Owlv2ForObjectDetection:()=>ed,Owlv2Model:()=>Zc,Owlv2PreTrainedModel:()=>na,PaliGemmaForConditionalGeneration:()=>Xi,PaliGemmaPreTrainedModel:()=>Qi,ParakeetForCTC:()=>k_,ParakeetPreTrainedModel:()=>C_,PatchTSMixerForPrediction:()=>Xu,PatchTSMixerModel:()=>Qu,PatchTSMixerPreTrainedModel:()=>za,PatchTSTForPrediction:()=>Hu,PatchTSTModel:()=>$u,PatchTSTPreTrainedModel:()=>Ua,Phi3ForCausalLM:()=>Pc,Phi3Model:()=>vc,Phi3PreTrainedModel:()=>Hn,Phi3VForCausalLM:()=>hn,Phi3VPreTrainedModel:()=>Zi,PhiForCausalLM:()=>Tc,PhiModel:()=>wc,PhiPreTrainedModel:()=>$n,PreTrainedModel:()=>T,PretrainedMixin:()=>gt,PvtForImageClassification:()=>Rc,PvtModel:()=>Oc,PvtPreTrainedModel:()=>Zn,PyAnnoteForAudioFrameClassification:()=>A_,PyAnnoteModel:()=>F_,PyAnnotePreTrainedModel:()=>ka,QuestionAnsweringModelOutput:()=>Yt,Qwen2ForCausalLM:()=>mc,Qwen2Model:()=>pc,Qwen2PreTrainedModel:()=>Gn,Qwen2VLForConditionalGeneration:()=>Mc,Qwen2VLPreTrainedModel:()=>gc,Qwen3ForCausalLM:()=>fc,Qwen3Model:()=>hc,Qwen3PreTrainedModel:()=>Kn,RFDetrForObjectDetection:()=>ud,RFDetrModel:()=>_d,RFDetrObjectDetectionOutput:()=>pd,RFDetrPreTrainedModel:()=>_a,RTDetrForObjectDetection:()=>id,RTDetrModel:()=>ad,RTDetrObjectDetectionOutput:()=>Ss,RTDetrPreTrainedModel:()=>ca,RTDetrV2ForObjectDetection:()=>cd,RTDetrV2Model:()=>ld,RTDetrV2ObjectDetectionOutput:()=>dd,RTDetrV2PreTrainedModel:()=>da,ResNetForImageClassification:()=>xd,ResNetModel:()=>bd,ResNetPreTrainedModel:()=>fa,RoFormerForMaskedLM:()=>cs,RoFormerForQuestionAnswering:()=>er,RoFormerForSequenceClassification:()=>ds,RoFormerForTokenClassification:()=>St,RoFormerModel:()=>ls,RoFormerPreTrainedModel:()=>Ht,RobertaForMaskedLM:()=>yi,RobertaForQuestionAnswering:()=>ki,RobertaForSequenceClassification:()=>Ei,RobertaForTokenClassification:()=>Ci,RobertaModel:()=>xi,RobertaPreTrainedModel:()=>Rr,Sam2ImageSegmentationOutput:()=>h_,Sam2Model:()=>so,Sam2PreTrainedModel:()=>f_,Sam3TrackerModel:()=>M_,SamImageSegmentationOutput:()=>m_,SamModel:()=>p_,SamPreTrainedModel:()=>u_,SapiensForDepthEstimation:()=>Od,SapiensForNormalEstimation:()=>Rd,SapiensForSemanticSegmentation:()=>Ld,SapiensPreTrainedModel:()=>ro,SegformerForImageClassification:()=>vu,SegformerForSemanticSegmentation:()=>Pu,SegformerModel:()=>Eh,SegformerPreTrainedModel:()=>lo,Seq2SeqLMOutput:()=>Bh,SequenceClassifierOutput:()=>at,SiglipModel:()=>sl,SiglipPreTrainedModel:()=>fn,SiglipTextModel:()=>ol,SiglipVisionModel:()=>nl,SmolLM3ForCausalLM:()=>Nl,SmolLM3Model:()=>Bl,SmolLM3PreTrainedModel:()=>Fn,SmolVLMForConditionalGeneration:()=>mn,SnacDecoderModel:()=>dp,SnacEncoderModel:()=>cp,SnacModel:()=>lp,SnacPreTrainedModel:()=>fo,SpeechT5ForSpeechToText:()=>Z_,SpeechT5ForTextToSpeech:()=>eu,SpeechT5HifiGan:()=>tu,SpeechT5Model:()=>yh,SpeechT5PreTrainedModel:()=>ao,SqueezeBertForMaskedLM:()=>W,SqueezeBertForQuestionAnswering:()=>ee,SqueezeBertForSequenceClassification:()=>q,SqueezeBertModel:()=>L,SqueezeBertPreTrainedModel:()=>g,StableLmForCausalLM:()=>xu,StableLmModel:()=>bu,StableLmPreTrainedModel:()=>Ba,Starcoder2ForCausalLM:()=>mu,Starcoder2Model:()=>pu,Starcoder2PreTrainedModel:()=>La,StyleTextToSpeech2Model:()=>Y_,StyleTextToSpeech2PreTrainedModel:()=>q_,SupertonicForConditionalGeneration:()=>Fa,SupertonicPreTrainedModel:()=>ru,Swin2SRForImageSuperResolution:()=>Fd,Swin2SRModel:()=>kd,Swin2SRPreTrainedModel:()=>ga,SwinForImageClassification:()=>Ed,SwinForSemanticSegmentation:()=>Cd,SwinModel:()=>yd,SwinPreTrainedModel:()=>to,T5ForConditionalGeneration:()=>Tt,T5Model:()=>Mt,T5PreTrainedModel:()=>ot,TableTransformerForObjectDetection:()=>gd,TableTransformerModel:()=>fd,TableTransformerObjectDetectionOutput:()=>Md,TableTransformerPreTrainedModel:()=>pa,TokenClassifierOutput:()=>Bt,TrOCRForCausalLM:()=>ou,TrOCRPreTrainedModel:()=>su,UltravoxModel:()=>Wa,UltravoxPreTrainedModel:()=>Ju,UniSpeechForCTC:()=>L_,UniSpeechForSequenceClassification:()=>O_,UniSpeechModel:()=>D_,UniSpeechPreTrainedModel:()=>oo,UniSpeechSatForAudioFrameClassification:()=>j_,UniSpeechSatForCTC:()=>B_,UniSpeechSatForSequenceClassification:()=>N_,UniSpeechSatModel:()=>R_,UniSpeechSatPreTrainedModel:()=>Ds,VaultGemmaForCausalLM:()=>lc,VaultGemmaModel:()=>ic,VaultGemmaPreTrainedModel:()=>Un,ViTForImageClassification:()=>Ac,ViTMAEModel:()=>Nc,ViTMAEPreTrainedModel:()=>Bc,ViTMSNForImageClassification:()=>Vc,ViTMSNModel:()=>jc,ViTMSNPreTrainedModel:()=>ea,ViTModel:()=>Fc,ViTPreTrainedModel:()=>qn,VisionEncoderDecoderModel:()=>dn,VitMatteForImageMatting:()=>$c,VitMattePreTrainedModel:()=>Kc,VitPoseForPoseEstimation:()=>Lc,VitPosePreTrainedModel:()=>Dc,VitsModel:()=>Ra,VitsModelOutput:()=>hm,VitsPreTrainedModel:()=>Tu,VoxtralForConditionalGeneration:()=>qu,Wav2Vec2BertForCTC:()=>U_,Wav2Vec2BertForSequenceClassification:()=>z_,Wav2Vec2BertModel:()=>V_,Wav2Vec2BertPreTrainedModel:()=>no,Wav2Vec2ForAudioFrameClassification:()=>E_,Wav2Vec2ForCTC:()=>x_,Wav2Vec2ForSequenceClassification:()=>y_,Wav2Vec2Model:()=>b_,Wav2Vec2PreTrainedModel:()=>Br,WavLMForAudioFrameClassification:()=>J_,WavLMForCTC:()=>H_,WavLMForSequenceClassification:()=>Q_,WavLMForXVector:()=>X_,WavLMModel:()=>$_,WavLMPreTrainedModel:()=>hs,WeSpeakerResNetModel:()=>S_,WeSpeakerResNetPreTrainedModel:()=>I_,WhisperForConditionalGeneration:()=>ln,WhisperModel:()=>Ui,WhisperPreTrainedModel:()=>an,XLMForQuestionAnswering:()=>Di,XLMForSequenceClassification:()=>Ii,XLMForTokenClassification:()=>Si,XLMModel:()=>Fi,XLMPreTrainedModel:()=>ps,XLMRobertaForMaskedLM:()=>Oi,XLMRobertaForQuestionAnswering:()=>Ni,XLMRobertaForSequenceClassification:()=>Ri,XLMRobertaForTokenClassification:()=>Bi,XLMRobertaModel:()=>Li,XLMRobertaPreTrainedModel:()=>ms,XLMWithLMHeadModel:()=>Ai,XVectorOutput:()=>pm,YolosForObjectDetection:()=>d_,YolosModel:()=>c_,YolosObjectDetectionOutput:()=>__,YolosPreTrainedModel:()=>ya});var r=e("./src/configs.js"),o=e("./src/backends/onnx.js"),a=e("./src/utils/dtypes.js"),h=e("./src/utils/generic.js"),u=e("./src/utils/core.js"),l=e("./src/utils/hub.js"),p=e("./src/utils/constants.js"),w=e("./src/generation/logits_process.js"),f=e("./src/generation/configuration_utils.js"),i=e("./src/utils/tensor.js"),y=e("./src/utils/image.js"),E=e("./src/utils/maths.js"),S=e("./src/generation/stopping_criteria.js"),z=e("./src/generation/logits_sampler.js"),k=e("./src/env.js"),A=e("./src/models/whisper/generation_whisper.js"),N=e("./src/models/whisper/common_whisper.js");let x={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12,Supertonic:13},P=new Map,D=new Map,_=new Map;async function M(n,c,b){let H=b.config?.["transformers.js_config"]??{},ae=b.device??H.device;ae&&typeof ae!="string"&&(ae.hasOwnProperty(c)?ae=ae[c]:(console.warn(`device not specified for "${c}". Using the default device.`),ae=null));let ne=ae??(k.apis.IS_NODE_ENV?"cpu":"wasm"),_e=(0,o.deviceToExecutionProviders)(ne),Ee=H.device_config??{};Ee.hasOwnProperty(ne)&&(H={...H,...Ee[ne]});let Se=b.dtype??H.dtype;if(typeof Se!="string"&&(Se&&Se.hasOwnProperty(c)?Se=Se[c]:(Se=a.DEFAULT_DEVICE_DTYPE_MAPPING[ne]??a.DATA_TYPES.fp32,console.warn(`dtype not specified for "${c}". Using the default dtype (${Se}) for this device (${ne}).`))),Se===a.DATA_TYPES.auto){let pt=H.dtype;typeof pt!="string"&&(pt=pt?.[c]),pt&&pt!==a.DATA_TYPES.auto&&a.DATA_TYPES.hasOwnProperty(pt)?Se=pt:Se=a.DEFAULT_DEVICE_DTYPE_MAPPING[ne]??a.DATA_TYPES.fp32}let Ne=Se;if(a.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ne)){if(Ne===a.DATA_TYPES.fp16&&ne==="webgpu"&&!await(0,a.isWebGpuFp16Supported)())throw new Error(`The device (${ne}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ne}. Should be one of: ${Object.keys(a.DATA_TYPES).join(", ")}`);let Ye=H.kv_cache_dtype,tt=Ye?typeof Ye=="string"?Ye:Ye[Ne]??"float32":void 0;if(tt&&!["float32","float16"].includes(tt))throw new Error(`Invalid kv_cache_dtype: ${tt}. Should be one of: float32, float16`);let nt={dtype:Ne,kv_cache_dtype:tt,device:ne},ut=a.DEFAULT_DTYPE_SUFFIX_MAPPING[Ne],Ze=`${c}${ut}.onnx`,it=`${b.subfolder??""}/${Ze}`,Xe={...b.session_options};Xe.executionProviders??(Xe.executionProviders=_e);let dt=H.free_dimension_overrides;dt?Xe.freeDimensionOverrides??(Xe.freeDimensionOverrides=dt):ne.startsWith("webnn")&&!Xe.freeDimensionOverrides&&console.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"]["${ne}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let ht=k.apis.IS_NODE_ENV&&k.env.useFSCache,yt=(0,l.getModelFile)(n,it,!0,b,ht),Et=b.use_external_data_format??H.use_external_data_format,Ct=[];if(Et){let pt;typeof Et=="object"?Et.hasOwnProperty(Ze)?pt=Et[Ze]:Et.hasOwnProperty(c)?pt=Et[c]:pt=!1:pt=Et;let kt=+pt;if(kt>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${kt}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let $t=0;$t<kt;++$t){let xr=`${Ze}_data${$t===0?"":"_"+$t}`,Ls=`${b.subfolder??""}/${xr}`;Ct.push(new Promise(async(nr,hr)=>{let gs=await(0,l.getModelFile)(n,Ls,!0,b,ht);nr(gs instanceof Uint8Array?{path:xr,data:gs}:xr)}))}}else Xe.externalData!==void 0&&(Ct=Xe.externalData.map(async pt=>{if(typeof pt.data=="string"){let kt=await(0,l.getModelFile)(n,pt.data,!0,b);return{...pt,data:kt}}return pt}));if(Ct.length>0){let pt=await Promise.all(Ct);k.apis.IS_NODE_ENV||(Xe.externalData=pt)}if(ne==="webgpu"){let pt=(0,r.getCacheShapes)(b.config,{prefix:"present"});if(Object.keys(pt).length>0&&!(0,o.isONNXProxy)()){let kt={};for(let $t in pt)kt[$t]="gpu-buffer";Xe.preferredOutputLocation=kt}}return{buffer_or_path:await yt,session_options:Xe,session_config:nt}}async function I(n,c,b){return Object.fromEntries(await Promise.all(Object.keys(c).map(async H=>{let{buffer_or_path:ae,session_options:ne,session_config:_e}=await M(n,c[H],b),Ee=await(0,o.createInferenceSession)(ae,ne,_e);return[H,Ee]})))}async function O(n,c,b){return Object.fromEntries(await Promise.all(Object.keys(c).map(async H=>{let ae=await(0,l.getModelJSON)(n,c[H],!1,b);return[H,ae]})))}function G(n,c){let b=Object.create(null),H=[];for(let _e of n.inputNames){let Ee=c[_e];if(!(Ee instanceof i.Tensor)){H.push(_e);continue}b[_e]=(0,o.isONNXProxy)()?Ee.clone():Ee}if(H.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${H.join(", ")}.`);let ae=Object.keys(c).length,ne=n.inputNames.length;if(ae>ne){let _e=Object.keys(c).filter(Ee=>!n.inputNames.includes(Ee));console.warn(`WARNING: Too many inputs were provided (${ae} > ${ne}). The following inputs will be ignored: "${_e.join(", ")}".`)}return b}async function U(n,c){let b=G(n,c);try{let H=Object.fromEntries(Object.entries(b).map(([ne,_e])=>[ne,_e.ort_tensor])),ae=await(0,o.runInferenceSession)(n,H);return B(ae)}catch(H){let ae=Object.fromEntries(Object.entries(b).map(([ne,_e])=>{let Ee={type:_e.type,dims:_e.dims,location:_e.location};return Ee.location!=="gpu-buffer"&&(Ee.data=_e.data),[ne,Ee]}));throw console.error(`An error occurred during model execution: "${H}".`),console.error("Inputs given to model:",ae),H}}function B(n){for(let c in n)(0,o.isONNXTensor)(n[c])?n[c]=new i.Tensor(n[c]):typeof n[c]=="object"&&B(n[c]);return n}function Q(n){if(n instanceof i.Tensor)return n;if(n.length===0)throw Error("items must be non-empty");if(Array.isArray(n[0])){if(n.some(c=>c.length!==n[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 i.Tensor("int64",BigInt64Array.from(n.flat().map(c=>BigInt(c))),[n.length,n[0].length])}else return new i.Tensor("int64",BigInt64Array.from(n.map(c=>BigInt(c))),[1,n.length])}function $(n){return new i.Tensor("bool",[n],[1])}async function Y(n,c){let{encoder_outputs:b,input_ids:H,decoder_input_ids:ae,...ne}=c;if(!b){let Ee=(0,u.pick)(c,n.sessions.model.inputNames);b=(await se(n,Ee)).last_hidden_state}return ne.input_ids=ae,ne.encoder_hidden_states=b,n.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ne.encoder_attention_mask=c.attention_mask),await ue(n,ne,!0)}async function se(n,c){let b=n.sessions.model,H=(0,u.pick)(c,b.inputNames);if(b.inputNames.includes("inputs_embeds")&&!H.inputs_embeds){if(!c.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");H.inputs_embeds=await n.encode_text({input_ids:c.input_ids})}if(b.inputNames.includes("token_type_ids")&&!H.token_type_ids){if(!H.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");H.token_type_ids=(0,i.zeros_like)(H.input_ids)}if(b.inputNames.includes("pixel_mask")&&!H.pixel_mask){if(!H.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let ae=H.pixel_values.dims;H.pixel_mask=(0,i.ones)([ae[0],ae[2],ae[3]])}return await U(b,H)}async function oe(n,c){let b=await n.encode(c);return await n.decode(b)}async function ue(n,c,b=!1){let H=n.sessions[b?"decoder_model_merged":"model"],{past_key_values:ae,...ne}=c;if(H.inputNames.includes("use_cache_branch")&&(ne.use_cache_branch=$(!!ae)),H.inputNames.includes("position_ids")&&ne.attention_mask&&!ne.position_ids){let Ee=["paligemma","gemma3_text","gemma3"].includes(n.config.model_type)?1:0;ne.position_ids=xe(ne,ae,Ee)}n.addPastKeyValues(ne,ae);let _e=(0,u.pick)(ne,H.inputNames);return await U(H,_e)}function be({modality_token_id:n,inputs_embeds:c,modality_features:b,input_ids:H,attention_mask:ae}){let ne=H.tolist().map(Ne=>Ne.reduce((Ye,tt,nt)=>(tt==n&&Ye.push(nt),Ye),[])),_e=ne.reduce((Ne,Ye)=>Ne+Ye.length,0),Ee=b.dims[0];if(_e!==Ee)throw new Error(`Number of tokens and features do not match: tokens: ${_e}, features ${Ee}`);let Se=0;for(let Ne=0;Ne<ne.length;++Ne){let Ye=ne[Ne],tt=c[Ne];for(let nt=0;nt<Ye.length;++nt)tt[Ye[nt]].data.set(b[Se++].data)}return{inputs_embeds:c,attention_mask:ae}}function pe({image_token_id:n,inputs_embeds:c,image_features:b,input_ids:H,attention_mask:ae}){return be({modality_token_id:n,inputs_embeds:c,modality_features:b,input_ids:H,attention_mask:ae})}function J({audio_token_id:n,inputs_embeds:c,audio_features:b,input_ids:H,attention_mask:ae}){return be({modality_token_id:n,inputs_embeds:c,modality_features:b,input_ids:H,attention_mask:ae})}async function F(n,{encode_function:c,merge_function:b,modality_input_name:H,modality_output_name:ae,input_ids:ne=null,attention_mask:_e=null,position_ids:Ee=null,inputs_embeds:Se=null,past_key_values:Ne=null,generation_config:Ye=null,logits_processor:tt=null,...nt}){let ut=nt[H];if(!Se){if(Se=await n.encode_text({input_ids:ne,...nt}),ut&&ne.dims[1]!==1){let it=await c({[H]:ut,...nt});({inputs_embeds:Se,attention_mask:_e}=b({[ae]:it,inputs_embeds:Se,input_ids:ne,attention_mask:_e}))}else if(Ne&&ut&&ne.dims[1]===1){let it=ne.dims[1],Xe=Object.values(Ne)[0].dims.at(-2);_e=(0,i.cat)([(0,i.ones)([ne.dims[0],Xe]),_e.slice(null,[_e.dims[1]-it,_e.dims[1]])],1)}}if(!Ee&&n.config.model_type==="qwen2_vl"){let{image_grid_thw:it,video_grid_thw:Xe}=nt;[Ee]=n.get_rope_index(ne,it,Xe,_e)}return await ue(n,{inputs_embeds:Se,past_key_values:Ne,attention_mask:_e,position_ids:Ee,generation_config:Ye,logits_processor:tt},!0)}async function K(n,c){return await F(n,{...c,modality_input_name:"audio_values",modality_output_name:"audio_features",encode_function:n.encode_audio.bind(n),merge_function:n._merge_input_ids_with_audio_features.bind(n)})}async function Z(n,c){return await F(n,{...c,modality_input_name:"pixel_values",modality_output_name:"image_features",encode_function:n.encode_image.bind(n),merge_function:n._merge_input_ids_with_image_features.bind(n)})}function ie(n,c=0){let[b,H]=n.dims,ae=n.data,ne=new BigInt64Array(ae.length);for(let _e=0;_e<b;++_e){let Ee=_e*H,Se=BigInt(c);for(let Ne=0;Ne<H;++Ne){let Ye=Ee+Ne;ae[Ye]===0n?ne[Ye]=BigInt(1):(ne[Ye]=Se,Se+=ae[Ye])}}return{data:ne,dims:n.dims}}function xe(n,c=null,b=0){let{input_ids:H,inputs_embeds:ae,attention_mask:ne}=n,{data:_e,dims:Ee}=ie(ne,b),Se=new i.Tensor("int64",_e,Ee);if(c){let Ne=-(H??ae).dims.at(1);Se=Se.slice(null,[Ne,null])}return Se}function ye(n,c,b,H){let ae=b.past_key_values?Object.values(b.past_key_values)[0].dims.at(-2):0;if(!b.attention_mask){let ne;for(let _e of["input_ids","inputs_embeds","position_ids"])if(b[_e]){ne=b[_e].dims;break}if(!ne)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");b.attention_mask=(0,i.ones)([ne[0],ae+ne[1]])}if(b.past_key_values){let{input_ids:ne,attention_mask:_e}=b;_e&&_e.dims[1]>ne.dims[1]||ae<ne.dims[1]&&(b.input_ids=ne.slice(null,[ae,null]))}return b}function Oe(n,c,b,H){return b.past_key_values&&(c=c.map(ae=>[ae.at(-1)])),{...b,decoder_input_ids:Q(c)}}function He(n,...c){return n.config.is_encoder_decoder?Oe(n,...c):ye(n,...c)}function we(n,c,b,H){let ae=!!b.past_key_values;return H.guidance_scale!==null&&H.guidance_scale>1&&(ae?b.input_ids=(0,i.cat)([b.input_ids,b.input_ids],0):(b.input_ids=(0,i.cat)([b.input_ids,(0,i.full_like)(b.input_ids,BigInt(H.pad_token_id))],0),b.attention_mask=(0,i.cat)([b.attention_mask,(0,i.full_like)(b.attention_mask,0n)],0))),(ae||!b.pixel_values)&&(b.pixel_values=(0,i.full)([0,0,3,384,384],1)),ae&&(b.images_seq_mask=new i.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),b.images_emb_mask=new i.Tensor("bool",new Array(0).fill(!1),[1,1,0])),b}class T extends h.Callable{constructor(b,H,ae){super();v(this,"main_input_name","input_ids");v(this,"forward_params",["input_ids","attention_mask"]);this.config=b,this.sessions=H,this.configs=ae;let ne=_.get(this.constructor),_e=P.get(ne);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,_e){case x.DecoderOnly:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=ye;break;case x.Seq2Seq:case x.Vision2Seq:case x.Musicgen:this.can_generate=!0,this._forward=Y,this._prepare_inputs_for_generation=Oe;break;case x.EncoderDecoder:this._forward=Y;break;case x.ImageTextToText:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=He;break;case x.AudioTextToText:this.can_generate=!0,this._forward=K,this._prepare_inputs_for_generation=He;break;case x.Phi3V:case x.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=He;break;case x.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=we;break;case x.AutoEncoder:this._forward=oe;break;default:this._forward=se;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let b=[];for(let H of Object.values(this.sessions))H?.handler?.dispose&&b.push(H.handler.dispose());return await Promise.all(b)}static async from_pretrained(b,{progress_callback:H=null,config:ae=null,cache_dir:ne=null,local_files_only:_e=!1,revision:Ee="main",model_file_name:Se=null,subfolder:Ne="onnx",device:Ye=null,dtype:tt=null,use_external_data_format:nt=null,session_options:ut={}}={}){let Ze={progress_callback:H,config:ae,cache_dir:ne,local_files_only:_e,revision:Ee,model_file_name:Se,subfolder:Ne,device:Ye,dtype:tt,use_external_data_format:nt,session_options:ut},it=_.get(this),Xe=P.get(it);ae=Ze.config=await r.AutoConfig.from_pretrained(b,Ze);let dt;if(Xe===x.DecoderOnly)dt=await Promise.all([I(b,{model:Ze.model_file_name??"model"},Ze),O(b,{generation_config:"generation_config.json"},Ze)]);else if(Xe===x.Seq2Seq||Xe===x.Vision2Seq)dt=await Promise.all([I(b,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ze),O(b,{generation_config:"generation_config.json"},Ze)]);else if(Xe===x.MaskGeneration)dt=await Promise.all([I(b,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Ze)]);else if(Xe===x.EncoderDecoder)dt=await Promise.all([I(b,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Ze)]);else if(Xe===x.ImageTextToText){let ht={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(ht.model="encoder_model"),dt=await Promise.all([I(b,ht,Ze),O(b,{generation_config:"generation_config.json"},Ze)])}else if(Xe===x.AudioTextToText){let ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};dt=await Promise.all([I(b,ht,Ze),O(b,{generation_config:"generation_config.json"},Ze)])}else if(Xe===x.ImageAudioTextToText){let ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};dt=await Promise.all([I(b,ht,Ze),O(b,{generation_config:"generation_config.json"},Ze)])}else if(Xe===x.Musicgen)dt=await Promise.all([I(b,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Ze),O(b,{generation_config:"generation_config.json"},Ze)]);else if(Xe===x.MultiModality)dt=await Promise.all([I(b,{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"},Ze),O(b,{generation_config:"generation_config.json"},Ze)]);else if(Xe===x.Phi3V)dt=await Promise.all([I(b,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Ze),O(b,{generation_config:"generation_config.json"},Ze)]);else if(Xe===x.AutoEncoder)dt=await Promise.all([I(b,{encoder_model:"encoder_model",decoder_model:"decoder_model"},Ze)]);else if(Xe===x.Supertonic)dt=await Promise.all([I(b,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},Ze)]);else{if(Xe!==x.EncoderOnly){let ht=it??ae?.model_type;ht!=="custom"&&console.warn(`Model type for '${ht}' not found, assuming encoder-only architecture. Please report this at ${p.GITHUB_ISSUE_URL}.`)}dt=await Promise.all([I(b,{model:Ze.model_file_name??"model"},Ze)])}return new this(ae,...dt)}async _call(b){return await this.forward(b)}async forward(b){return await this._forward(this,b)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(b,H,ae=null){let ne=new w.LogitsProcessorList;if(b.repetition_penalty!==null&&b.repetition_penalty!==1&&ne.push(new w.RepetitionPenaltyLogitsProcessor(b.repetition_penalty)),b.no_repeat_ngram_size!==null&&b.no_repeat_ngram_size>0&&ne.push(new w.NoRepeatNGramLogitsProcessor(b.no_repeat_ngram_size)),b.bad_words_ids!==null&&ne.push(new w.NoBadWordsLogitsProcessor(b.bad_words_ids,b.eos_token_id)),b.min_length!==null&&b.eos_token_id!==null&&b.min_length>0&&ne.push(new w.MinLengthLogitsProcessor(b.min_length,b.eos_token_id)),b.min_new_tokens!==null&&b.eos_token_id!==null&&b.min_new_tokens>0&&ne.push(new w.MinNewTokensLengthLogitsProcessor(H,b.min_new_tokens,b.eos_token_id)),b.forced_bos_token_id!==null&&ne.push(new w.ForcedBOSTokenLogitsProcessor(b.forced_bos_token_id)),b.forced_eos_token_id!==null&&ne.push(new w.ForcedEOSTokenLogitsProcessor(b.max_length,b.forced_eos_token_id)),b.begin_suppress_tokens!==null){let _e=H>1||b.forced_bos_token_id===null?H:H+1;ne.push(new w.SuppressTokensAtBeginLogitsProcessor(b.begin_suppress_tokens,_e))}return b.guidance_scale!==null&&b.guidance_scale>1&&ne.push(new w.ClassifierFreeGuidanceLogitsProcessor(b.guidance_scale)),b.temperature===0&&b.do_sample&&(console.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`."),b.do_sample=!1),b.do_sample&&b.temperature!==null&&b.temperature!==1&&ne.push(new w.TemperatureLogitsWarper(b.temperature)),ae!==null&&ne.extend(ae),ne}_prepare_generation_config(b,H,ae=f.GenerationConfig){let ne={...this.config};for(let Ee of["decoder","generator","text_config"])Ee in ne&&Object.assign(ne,ne[Ee]);let _e=new ae(ne);return Object.assign(_e,this.generation_config??{}),b&&Object.assign(_e,b),H&&Object.assign(_e,(0,u.pick)(H,Object.getOwnPropertyNames(_e))),_e}_get_stopping_criteria(b,H=null){let ae=new S.StoppingCriteriaList;return b.max_length!==null&&ae.push(new S.MaxLengthCriteria(b.max_length,this.config.max_position_embeddings??null)),b.eos_token_id!==null&&ae.push(new S.EosTokenCriteria(b.eos_token_id)),H&&ae.extend(H),ae}_validate_model_class(){if(!this.can_generate){let b=[$a,Ha,Ka,Ga],H=_.get(this.constructor),ae=new Set,ne=this.config.model_type;for(let Ee of b){let Se=Ee.get(ne);Se&&ae.add(Se[0])}let _e=`The current model class (${H}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(_e+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(_e)}}prepare_inputs_for_generation(...b){return this._prepare_inputs_for_generation(this,...b)}_update_model_kwargs_for_generation({generated_input_ids:b,outputs:H,model_inputs:ae,is_encoder_decoder:ne}){return ae.past_key_values=this.getPastKeyValues(H,ae.past_key_values),ae.input_ids=new i.Tensor("int64",b.flat(),[b.length,1]),ne?"decoder_attention_mask"in ae:ae.attention_mask=(0,i.cat)([ae.attention_mask,(0,i.ones)([ae.attention_mask.dims[0],1])],1),ae.position_ids=null,ae}_prepare_model_inputs({inputs:b,bos_token_id:H,model_kwargs:ae}){let ne=(0,u.pick)(ae,this.forward_params),_e=this.main_input_name;if(_e in ne){if(b)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else ne[_e]=b;return{inputs_tensor:ne[_e],model_inputs:ne,model_input_name:_e}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:b,model_inputs:H,model_input_name:ae,generation_config:ne}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!H.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:Ee,pixel_values:Se,attention_mask:Ne,...Ye}=H,tt=await this._prepare_inputs_embeds(H);H={...Ye,...(0,u.pick)(tt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_e}=await se(this,H);if(ne.guidance_scale!==null&&ne.guidance_scale>1)_e=(0,i.cat)([_e,(0,i.full_like)(_e,0)],0),"attention_mask"in H&&(H.attention_mask=(0,i.cat)([H.attention_mask,(0,i.zeros_like)(H.attention_mask)],0));else if(H.decoder_input_ids){let Ee=Q(H.decoder_input_ids).dims[0];if(Ee!==_e.dims[0]){if(_e.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_e.dims[0]}) than the decoder inputs (${Ee}).`);_e=(0,i.cat)(Array.from({length:Ee},()=>_e),0)}}return H.encoder_outputs=_e,H}_prepare_decoder_input_ids_for_generation({batch_size:b,model_input_name:H,model_kwargs:ae,decoder_start_token_id:ne,bos_token_id:_e,generation_config:Ee}){let{decoder_input_ids:Se,...Ne}=ae;if(!(Se instanceof i.Tensor)){if(Se)Array.isArray(Se[0])||(Se=Array.from({length:b},()=>Se));else if(ne??(ne=_e),this.config.model_type==="musicgen")Se=Array.from({length:b*this.config.decoder.num_codebooks},()=>[ne]);else if(Array.isArray(ne)){if(ne.length!==b)throw new Error(`\`decoder_start_token_id\` expcted to have length ${b} but got ${ne.length}`);Se=ne}else Se=Array.from({length:b},()=>[ne]);Se=Q(Se)}return ae.decoder_attention_mask=(0,i.ones_like)(Se),{input_ids:Se,model_inputs:Ne}}async generate({inputs:b=null,generation_config:H=null,logits_processor:ae=null,stopping_criteria:ne=null,streamer:_e=null,...Ee}){this._validate_model_class(),H=this._prepare_generation_config(H,Ee);let{inputs_tensor:Se,model_inputs:Ne,model_input_name:Ye}=this._prepare_model_inputs({inputs:b,model_kwargs:Ee}),tt=this.config.is_encoder_decoder;tt&&("encoder_outputs"in Ne||(Ne=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Se,model_inputs:Ne,model_input_name:Ye,generation_config:H})));let nt;tt?{input_ids:nt,model_inputs:Ne}=this._prepare_decoder_input_ids_for_generation({batch_size:Ne[Ye].dims.at(0),model_input_name:Ye,model_kwargs:Ne,decoder_start_token_id:H.decoder_start_token_id,bos_token_id:H.bos_token_id,generation_config:H}):nt=Ne[Ye];let ut=nt.dims.at(-1);H.max_new_tokens!==null&&(H.max_length=ut+H.max_new_tokens);let Ze=this._get_logits_processor(H,ut,ae),it=this._get_stopping_criteria(H,ne),Xe=Ne[Ye].dims.at(0),dt=z.LogitsSampler.getSampler(H),ht=new Array(Xe).fill(0),yt=nt.tolist();_e&&_e.put(yt);let Et,Ct={};for(;;){if(Ne=this.prepare_inputs_for_generation(yt,Ne,H),Et=await this.forward(Ne),H.output_attentions&&H.return_dict_in_generate){let nr=this.getAttentions(Et);for(let hr in nr)hr in Ct||(Ct[hr]=[]),Ct[hr].push(nr[hr])}let kt=Et.logits.slice(null,-1,null),$t=Ze(yt,kt),xr=[];for(let nr=0;nr<$t.dims.at(0);++nr){let hr=$t[nr],gs=await dt(hr);for(let[go,Mo]of gs){let wo=BigInt(go);ht[nr]+=Mo,yt[nr].push(wo),xr.push([wo]);break}}if(_e&&_e.put(xr),it(yt).every(nr=>nr))break;Ne=this._update_model_kwargs_for_generation({generated_input_ids:xr,outputs:Et,model_inputs:Ne,is_encoder_decoder:tt})}_e&&_e.end();let Ot=this.getPastKeyValues(Et,Ne.past_key_values,!0),pt=new i.Tensor("int64",yt.flat(),[yt.length,yt[0].length]);if(H.return_dict_in_generate)return{sequences:pt,past_key_values:Ot,...Ct};for(let kt of Object.values(Et))kt.location==="gpu-buffer"&&kt.dispose();return pt}getPastKeyValues(b,H,ae=!1){let ne=Object.create(null);for(let _e in b)if(_e.startsWith("present")){let Ee=_e.replace("present_conv","past_conv").replace("present","past_key_values"),Se=_e.includes("encoder");if(Se&&H?ne[Ee]=H[Ee]:ne[Ee]=b[_e],H&&(!Se||ae)){let Ne=H[Ee];Ne.location==="gpu-buffer"&&Ne.dispose()}}return ne}getAttentions(b){let H={};for(let ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(let ne in b)ne.startsWith(ae)&&(ae in H||(H[ae]=[]),H[ae].push(b[ne]));return H}addPastKeyValues(b,H){if(H)Object.assign(b,H);else{let ae=this.sessions.decoder_model_merged??this.sessions.model,ne=(b[this.main_input_name]??b.attention_mask)?.dims?.[0]??1,_e=ae?.config?.kv_cache_dtype??"float32",Ee=_e==="float16"?i.DataTypeMap.float16:i.DataTypeMap.float32,Se=(0,r.getCacheShapes)(this.config,{batch_size:ne});for(let Ne in Se){let Ye=Se[Ne].reduce((tt,nt)=>tt*nt,1);b[Ne]=new i.Tensor(_e,new Ee(Ye),Se[Ne])}}}async encode_image({pixel_values:b}){return(await U(this.sessions.vision_encoder,{pixel_values:b})).image_features}async encode_text({input_ids:b}){return(await U(this.sessions.embed_tokens,{input_ids:b})).inputs_embeds}async encode_audio({audio_values:b}){return(await U(this.sessions.audio_encoder,{audio_values:b})).audio_features}}class X{}class de extends X{constructor({last_hidden_state:c,hidden_states:b=null,attentions:H=null}){super(),this.last_hidden_state=c,this.hidden_states=b,this.attentions=H}}class he extends T{}class Te extends he{}class ge extends he{async _call(c){return new Wt(await super._call(c))}}class le extends he{async _call(c){return new at(await super._call(c))}}class ve extends he{async _call(c){return new Bt(await super._call(c))}}class ce extends he{async _call(c){return new Yt(await super._call(c))}}class Me extends T{}class Re extends Me{}class Ce extends Me{async _call(c){return new Wt(await super._call(c))}}class Ie extends Me{async _call(c){return new at(await super._call(c))}}class Fe extends Me{async _call(c){return new Bt(await super._call(c))}}class Je extends Me{async _call(c){return new Yt(await super._call(c))}}class Ve extends T{}class ze extends Ve{}class Ae extends Ve{async _call(c){return new Wt(await super._call(c))}}class et extends Ve{async _call(c){return new at(await super._call(c))}}class Ue extends Ve{async _call(c){return new Bt(await super._call(c))}}class lt extends T{}class mt extends lt{}class bt extends lt{}class Vt extends T{}class vt extends Vt{}class Ht extends T{}class ls extends Ht{}class cs extends Ht{async _call(c){return new Wt(await super._call(c))}}class ds extends Ht{async _call(c){return new at(await super._call(c))}}class St extends Ht{async _call(c){return new Bt(await super._call(c))}}class er extends Ht{async _call(c){return new Yt(await super._call(c))}}class gr extends T{}class _s extends gr{}class rt extends gr{async _call(c){return new Wt(await super._call(c))}}class Ur extends gr{async _call(c){return new at(await super._call(c))}}class zr extends gr{async _call(c){return new Bt(await super._call(c))}}class Wr extends gr{async _call(c){return new Yt(await super._call(c))}}class pr extends T{}class _t extends pr{}class Gr extends pr{async _call(c){return new Wt(await super._call(c))}}class m extends pr{async _call(c){return new at(await super._call(c))}}class j extends pr{async _call(c){return new Bt(await super._call(c))}}class C extends pr{async _call(c){return new Yt(await super._call(c))}}class R extends T{}class V extends R{}class te extends R{async _call(c){return new Wt(await super._call(c))}}class me extends R{async _call(c){return new at(await super._call(c))}}class Ke extends R{async _call(c){return new Bt(await super._call(c))}}class qe extends R{async _call(c){return new Yt(await super._call(c))}}class je extends T{}class st extends je{}class Ge extends je{async _call(c){return new Wt(await super._call(c))}}class ct extends je{async _call(c){return new at(await super._call(c))}}class ft extends je{async _call(c){return new Bt(await super._call(c))}}class Qt extends je{async _call(c){return new Yt(await super._call(c))}}class Ut extends T{}class ar extends Ut{}class Xt extends Ut{async _call(c){return new Wt(await super._call(c))}}class Cr extends Ut{async _call(c){return new at(await super._call(c))}}class kr extends Ut{async _call(c){return new Bt(await super._call(c))}}class Fr extends Ut{async _call(c){return new Yt(await super._call(c))}}class cr extends T{}class Kr extends cr{}class Ar extends cr{async _call(c){return new at(await super._call(c))}}class $r extends cr{async _call(c){return new Bt(await super._call(c))}}class mr extends cr{async _call(c){return new Yt(await super._call(c))}}class Mr extends cr{async _call(c){return new Wt(await super._call(c))}}class wr extends T{}class Hr extends wr{}class Ir extends wr{async _call(c){return new Wt(await super._call(c))}}class Sr extends wr{async _call(c){return new at(await super._call(c))}}class Dr extends wr{async _call(c){return new Bt(await super._call(c))}}class Tr extends T{}class ir extends Tr{}class ke extends Tr{async _call(c){return new Wt(await super._call(c))}}class De extends Tr{async _call(c){return new at(await super._call(c))}}class Qe extends Tr{async _call(c){return new Yt(await super._call(c))}}class xt extends T{}class Qr extends xt{}class Lr extends xt{async _call(c){return new Wt(await super._call(c))}}class Xr extends xt{async _call(c){return new at(await super._call(c))}}class Is extends xt{async _call(c){return new Bt(await super._call(c))}}class re extends xt{async _call(c){return new Yt(await super._call(c))}}class g extends T{}class L extends g{}class W extends g{async _call(c){return new Wt(await super._call(c))}}class q extends g{async _call(c){return new at(await super._call(c))}}class ee extends g{async _call(c){return new Yt(await super._call(c))}}class fe extends T{}class Le extends fe{}class We extends fe{async _call(c){return new at(await super._call(c))}}class Be extends fe{async _call(c){return new Yt(await super._call(c))}}class $e extends fe{async _call(c){return new Wt(await super._call(c))}}class ot extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Mt extends ot{}class Tt extends ot{}class It extends T{}class Pt extends It{}class tr extends It{}class rr extends T{}class lr extends rr{}class vr extends rr{}class Jt extends T{}class Or extends Jt{}class At extends Jt{}class Kt extends Jt{async _call(c){return new at(await super._call(c))}}class qt extends T{}class Pr extends qt{}class yr extends qt{}class sr extends qt{async _call(c){return new at(await super._call(c))}}class br extends qt{}class zt extends T{}class Dt extends zt{}class Rt extends zt{}class Lt extends T{}class dr extends Lt{}class us extends Lt{}class Rr extends T{}class xi extends Rr{}class yi extends Rr{async _call(c){return new Wt(await super._call(c))}}class Ei extends Rr{async _call(c){return new at(await super._call(c))}}class Ci extends Rr{async _call(c){return new Bt(await super._call(c))}}class ki extends Rr{async _call(c){return new Yt(await super._call(c))}}class ps extends T{}class Fi extends ps{}class Ai extends ps{async _call(c){return new Wt(await super._call(c))}}class Ii extends ps{async _call(c){return new at(await super._call(c))}}class Si extends ps{async _call(c){return new Bt(await super._call(c))}}class Di extends ps{async _call(c){return new Yt(await super._call(c))}}class ms extends T{}class Li extends ms{}class Oi extends ms{async _call(c){return new Wt(await super._call(c))}}class Ri extends ms{async _call(c){return new at(await super._call(c))}}class Bi extends ms{async _call(c){return new Bt(await super._call(c))}}class Ni extends ms{async _call(c){return new Yt(await super._call(c))}}class nn extends T{}class ji extends nn{}class Vi extends nn{}class an extends T{constructor(){super(...arguments);v(this,"requires_attention_mask",!1);v(this,"main_input_name","input_features");v(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ui extends an{}class ln extends an{_prepare_generation_config(c,b){return super._prepare_generation_config(c,b,A.WhisperGenerationConfig)}_retrieve_init_tokens(c){let b=[c.decoder_start_token_id],H=c.language,ae=c.task;if(c.is_multilingual){H||(console.warn("No language specified - defaulting to English (en)."),H="en");let _e=`<|${(0,N.whisper_language_to_code)(H)}|>`;b.push(c.lang_to_id[_e]),b.push(c.task_to_id[ae??"transcribe"])}else if(H||ae)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!c.return_timestamps&&c.no_timestamps_token_id&&b.at(-1)!==c.no_timestamps_token_id?b.push(c.no_timestamps_token_id):c.return_timestamps&&b.at(-1)===c.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),b.pop()),b.filter(ne=>ne!=null)}async generate({inputs:c=null,generation_config:b=null,logits_processor:H=null,stopping_criteria:ae=null,...ne}){b=this._prepare_generation_config(b,ne);let _e=ne.decoder_input_ids??this._retrieve_init_tokens(b);if(b.return_timestamps&&(H??(H=new w.LogitsProcessorList),H.push(new w.WhisperTimeStampLogitsProcessor(b,_e))),b.begin_suppress_tokens&&(H??(H=new w.LogitsProcessorList),H.push(new w.SuppressTokensAtBeginLogitsProcessor(b.begin_suppress_tokens,_e.length))),b.return_token_timestamps){if(!b.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.");b.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),b.output_attentions=!0,b.return_dict_in_generate=!0}let Ee=await super.generate({inputs:c,generation_config:b,logits_processor:H,decoder_input_ids:_e,...ne});return b.return_token_timestamps&&(Ee.token_timestamps=this._extract_token_timestamps(Ee,b.alignment_heads,b.num_frames)),Ee}_extract_token_timestamps(c,b,H=null,ae=.02){if(!c.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`.");H==null&&console.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 ne=this.config.median_filter_width;ne===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ne=7);let _e=c.cross_attentions,Ee=Array.from({length:this.config.decoder_layers},(it,Xe)=>(0,i.cat)(_e.map(dt=>dt[Xe]),2)),Se=(0,i.stack)(b.map(([it,Xe])=>{if(it>=Ee.length)throw new Error(`Layer index ${it} is out of bounds for cross attentions (length ${Ee.length}).`);return H?Ee[it].slice(null,Xe,null,[0,H]):Ee[it].slice(null,Xe)})).transpose(1,0,2,3),[Ne,Ye]=(0,i.std_mean)(Se,-2,0,!0),tt=Se.clone();for(let it=0;it<tt.dims[0];++it){let Xe=tt[it];for(let dt=0;dt<Xe.dims[0];++dt){let ht=Xe[dt],yt=Ne[it][dt][0].data,Et=Ye[it][dt][0].data;for(let Ct=0;Ct<ht.dims[0];++Ct){let Ot=ht[Ct].data;for(let pt=0;pt<Ot.length;++pt)Ot[pt]=(Ot[pt]-Et[pt])/yt[pt];Ot.set((0,E.medianFilter)(Ot,ne))}}}let nt=[(0,i.mean)(tt,1)],ut=c.sequences.dims,Ze=new i.Tensor("float32",new Float32Array(ut[0]*ut[1]),ut);for(let it=0;it<ut[0];++it){let Xe=nt[it].neg().squeeze_(0),[dt,ht]=(0,E.dynamic_time_warping)(Xe.tolist()),yt=Array.from({length:dt.length-1},(Ot,pt)=>dt[pt+1]-dt[pt]),Et=(0,u.mergeArrays)([1],yt).map(Ot=>!!Ot),Ct=[];for(let Ot=0;Ot<Et.length;++Ot)Et[Ot]&&Ct.push(ht[Ot]*ae);Ze[it].data.set(Ct,1)}return Ze}}class zi extends ln{}class cn extends T{constructor(){super(...arguments);v(this,"requires_attention_mask",!1);v(this,"main_input_name","input_values");v(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}}class vh extends cn{}class Wi extends cn{}class dn extends T{constructor(){super(...arguments);v(this,"main_input_name","pixel_values");v(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}}class _n extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}}class qs extends _n{_merge_input_ids_with_image_features(c){let b=c.image_features.dims.at(-1),H=c.image_features.view(-1,b);return pe({image_token_id:this.config.image_token_index,...c,image_features:H})}}class Gi extends qs{}class Ki extends qs{}class $i extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);v(this,"main_input_name","inputs_embeds")}}class Hi extends $i{_merge_input_ids_with_image_features({inputs_embeds:c,image_features:b,input_ids:H,attention_mask:ae}){return{inputs_embeds:(0,i.cat)([b,c],1),attention_mask:(0,i.cat)([(0,i.ones)(b.dims.slice(0,2)),ae],1)}}async _prepare_inputs_embeds({input_ids:c,pixel_values:b,inputs_embeds:H,attention_mask:ae}){if(!c&&!b)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let ne,_e;return c&&(ne=await this.encode_text({input_ids:c})),b&&(_e=await this.encode_image({pixel_values:b})),ne&&_e?{inputs_embeds:H,attention_mask:ae}=this._merge_input_ids_with_image_features({inputs_embeds:ne,image_features:_e,input_ids:c,attention_mask:ae}):H=ne||_e,{inputs_embeds:H,attention_mask:ae}}async forward({input_ids:c,pixel_values:b,attention_mask:H,decoder_input_ids:ae,decoder_attention_mask:ne,encoder_outputs:_e,past_key_values:Ee,inputs_embeds:Se,decoder_inputs_embeds:Ne}){if(Se||({inputs_embeds:Se,attention_mask:H}=await this._prepare_inputs_embeds({input_ids:c,pixel_values:b,inputs_embeds:Se,attention_mask:H})),!_e){let{last_hidden_state:nt}=await se(this,{inputs_embeds:Se,attention_mask:H});_e=nt}if(!Ne){if(!ae)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");Ne=await this.encode_text({input_ids:ae})}return await ue(this,{inputs_embeds:Ne,attention_mask:ne,encoder_attention_mask:H,encoder_hidden_states:_e,past_key_values:Ee},!0)}}class Qi extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}}class Xi extends Qi{_merge_input_ids_with_image_features(c){let b=c.image_features.dims.at(-1),H=c.image_features.view(-1,b);return pe({image_token_id:this.config.image_token_index,...c,image_features:H})}}class un extends _n{_merge_input_ids_with_image_features(c){let b=c.image_features.dims.at(-1),H=c.image_features.view(-1,b);return pe({image_token_id:this.config.image_token_index,...c,image_features:H})}}class Ji extends un{}class qi extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}}class pn extends qi{async forward({input_ids:c=null,attention_mask:b=null,pixel_values:H=null,input_features:ae=null,input_features_mask:ne=null,position_ids:_e=null,inputs_embeds:Ee=null,per_layer_inputs:Se=null,past_key_values:Ne=null,generation_config:Ye=null,logits_processor:tt=null,...nt}){if((!Ee||!Se)&&({inputs_embeds:Ee,per_layer_inputs:Se}=await U(this.sessions.embed_tokens,{input_ids:c}),c.dims[1]!==1)){if(H){let{image_features:Ze}=await U(this.sessions.vision_encoder,{pixel_values:H});({inputs_embeds:Ee,attention_mask:b}=this._merge_input_ids_with_image_features({image_features:Ze,inputs_embeds:Ee,input_ids:c,attention_mask:b}))}if(ae){let{audio_features:Ze}=await U(this.sessions.audio_encoder,{input_features:ae,input_features_mask:ne});({inputs_embeds:Ee,attention_mask:b}=this._merge_input_ids_with_audio_features({audio_features:Ze,inputs_embeds:Ee,input_ids:c,attention_mask:b}))}}return await ue(this,{inputs_embeds:Ee,per_layer_inputs:Se,past_key_values:Ne,attention_mask:b,position_ids:_e,generation_config:Ye,logits_processor:tt},!0)}_merge_input_ids_with_image_features(c){let b=c.image_features.dims.at(-1),H=c.image_features.view(-1,b);return pe({image_token_id:this.config.image_token_id,...c,image_features:H})}_merge_input_ids_with_audio_features(c){let b=c.audio_features.dims.at(-1),H=c.audio_features.view(-1,b);return J({audio_token_id:this.config.audio_token_id,...c,audio_features:H})}}class Yi extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}}class Ys extends Yi{async encode_image({pixel_values:c,pixel_attention_mask:b}){return(await U(this.sessions.vision_encoder,{pixel_values:c,pixel_attention_mask:b})).image_features}_merge_input_ids_with_image_features(c){let b=c.image_features.dims.at(-1),H=c.image_features.view(-1,b);return pe({image_token_id:this.config.image_token_id,...c,image_features:H})}}class mn extends Ys{}class Zi extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}}class hn extends Zi{async forward({input_ids:c=null,attention_mask:b=null,pixel_values:H=null,image_sizes:ae=null,position_ids:ne=null,inputs_embeds:_e=null,past_key_values:Ee=null,generation_config:Se=null,logits_processor:Ne=null,...Ye}){if(!_e){let nt;if(H&&c.dims[1]!==1){if(!ae)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:nt}=await U(this.sessions.vision_encoder,{pixel_values:H,image_sizes:ae}))}else{let ut=this.config.normalized_config.hidden_size;nt=new i.Tensor("float32",[],[0,ut])}({inputs_embeds:_e}=await U(this.sessions.prepare_inputs_embeds,{input_ids:c,image_features:nt}))}return await ue(this,{inputs_embeds:_e,past_key_values:Ee,attention_mask:b,position_ids:ne,generation_config:Se,logits_processor:Ne},!1)}}class Jr extends T{}class el extends Jr{}class Ph extends Jr{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"text_model"})}}class tl extends Jr{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"text_model"})}}class bh extends Jr{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"vision_model"})}}class rl extends Jr{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"vision_model"})}}class fn extends T{}class sl extends fn{}class ol extends fn{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"text_model"})}}class nl extends Jr{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"vision_model"})}}class al extends T{}class il extends al{}class Zs extends T{}class ll extends Zs{async forward(c){let b=!c.input_ids,H=!c.pixel_values;if(b&&H)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(b&&(c.input_ids=(0,i.ones)([c.pixel_values.dims[0],1])),H){let{image_size:Ne}=this.config.vision_config;c.pixel_values=(0,i.full)([0,3,Ne,Ne],0)}let{text_embeddings:ae,image_embeddings:ne,l2norm_text_embeddings:_e,l2norm_image_embeddings:Ee}=await super.forward(c),Se={};return b||(Se.text_embeddings=ae,Se.l2norm_text_embeddings=_e),H||(Se.image_embeddings=ne,Se.l2norm_image_embeddings=Ee),Se}}class cl extends Zs{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"text_model"})}}class dl extends Zs{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"vision_model"})}}class gn extends T{}class _l extends gn{}class ul extends gn{}class Mn extends T{}class pl extends Mn{}class ml extends Mn{}class wn extends T{}class hl extends wn{}class fl extends wn{}class Tn extends T{}class gl extends Tn{}class Ml extends Tn{}class vn extends T{}class wl extends vn{}class Tl extends vn{}class Pn extends T{}class vl extends Pn{}class Pl extends Pn{}class bn extends T{}class bl extends bn{}class xl extends bn{}class xn extends T{}class yl extends xn{}class El extends xn{}class yn extends T{}class Cl extends yn{}class kl extends yn{}class Fl extends T{}class Al extends Fl{}class En extends T{}class Il extends En{}class Sl extends En{}class Cn extends T{}class Dl extends Cn{}class Ll extends Cn{}class kn extends T{}class Ol extends kn{}class Rl extends kn{}class Fn extends T{}class Bl extends Fn{}class Nl extends Fn{}class An extends T{}class jl extends An{}class Vl extends An{}class In extends T{}class Ul extends In{}class zl extends In{}class Sn extends T{}class Wl extends Sn{}class Gl extends Sn{}class Dn extends T{}class Kl extends Dn{}class $l extends Dn{}class Ln extends T{}class Hl extends Ln{}class Ql extends Ln{}class On extends T{}class Xl extends On{}class Jl extends On{}class Rn extends T{}class ql extends Rn{}class Yl extends Rn{}class Bn extends T{}class Zl extends Bn{}class ec extends Bn{}class Nn extends T{}class tc extends Nn{}class rc extends Nn{}class jn extends T{}class sc extends jn{}class oc extends jn{}class Vn extends T{}class nc extends Vn{}class ac extends Vn{}class Un extends T{}class ic extends Un{}class lc extends Un{}class zn extends T{}class cc extends zn{}class dc extends zn{}class Wn extends T{}class _c extends Wn{}class uc extends Wn{}class Gn extends T{}class pc extends Gn{}class mc extends Gn{}class Kn extends T{}class hc extends Kn{}class fc extends Kn{}class gc extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}}class Mc extends gc{get_rope_index(c,b,H,ae){let{vision_config:ne,image_token_id:_e,video_token_id:Ee,vision_start_token_id:Se}=this.config,Ne=ne.spatial_merge_size??2,Ye=[];if(b||H){let tt=c.tolist();ae||(ae=(0,i.ones_like)(c));let nt=ae.tolist(),ut=Array.from({length:3},ht=>Array.from({length:c.dims[0]},yt=>Array.from({length:c.dims[1]},Et=>1))),Ze=b?b.tolist():[],it=H?H.tolist():[],Xe=0,dt=0;for(let ht=0;ht<tt.length;++ht){let yt=tt[ht].filter((Ft,Nt)=>nt[ht][Nt]==1),Ct=yt.reduce((Ft,Nt,jr)=>(Nt==Se&&Ft.push(jr),Ft),[]).map(Ft=>yt[Ft+1]),Ot=Ct.filter(Ft=>Ft==_e).length,pt=Ct.filter(Ft=>Ft==Ee).length,kt=[],$t=0,xr=Ot,Ls=pt;for(let Ft=0;Ft<Ct.length;++Ft){let Nt=yt.findIndex((Yr,fr)=>fr>$t&&Yr==_e),jr=yt.findIndex((Yr,fr)=>fr>$t&&Yr==Ee),qr=xr>0&&Nt!==-1?Nt:yt.length+1,Ms=Ls>0&&jr!==-1?jr:yt.length+1,To,Xa,Ja,qa;qr<Ms?([Xa,Ja,qa]=Ze[Xe],++Xe,--xr,To=qr):([Xa,Ja,qa]=it[dt],++dt,--Ls,To=Ms);let[jh,Ya,vo]=[Number(Xa),Math.floor(Number(Ja)/Ne),Math.floor(Number(qa)/Ne)],Za=To-$t,fm=kt.length>0?(0,E.max)(kt.at(-1))[0]+1:0;kt.push(Array.from({length:3*Za},(Yr,fr)=>fm+fr%Za));let ei=Za+fm,Po=jh*Ya*vo,Vh=Array.from({length:Po},(Yr,fr)=>ei+Math.floor(fr/(Ya*vo))),Uh=Array.from({length:Po},(Yr,fr)=>ei+Math.floor(fr/vo)%Ya),zh=Array.from({length:Po},(Yr,fr)=>ei+fr%vo);kt.push([Vh,Uh,zh].flat()),$t=To+Po}if($t<yt.length){let Ft=kt.length>0?(0,E.max)(kt.at(-1))[0]+1:0,Nt=yt.length-$t;kt.push(Array.from({length:3*Nt},(jr,qr)=>Ft+qr%Nt))}let nr=kt.reduce((Ft,Nt)=>Ft+Nt.length,0),hr=new Array(nr),gs=0;for(let Ft=0;Ft<3;++Ft)for(let Nt=0;Nt<kt.length;++Nt){let jr=kt[Nt],qr=jr.length/3;for(let Ms=Ft*qr;Ms<(Ft+1)*qr;++Ms)hr[gs++]=jr[Ms]}let go=0,Mo=nt[ht];for(let Ft=0;Ft<Mo.length;++Ft)if(Mo[Ft]==1){for(let Nt=0;Nt<3;++Nt)ut[Nt][ht][Ft]=hr[Nt*nr/3+go];++go}let wo=(0,E.max)(hr)[0];Ye.push(wo+1-tt[ht].length)}return[new i.Tensor("int64",ut.flat(1/0),[3,c.dims[0],c.dims[1]]),new i.Tensor("int64",Ye,[Ye.length,1])]}else if(ae){let{data:tt,dims:nt}=ie(ae),ut=BigInt64Array.from({length:3*tt.length},(it,Xe)=>tt[Xe%tt.length]),Ze=Array.from({length:nt[0]},(it,Xe)=>(0,E.max)(tt.subarray(nt[1]*Xe,nt[1]*(Xe+1)))[0]+1n+BigInt(nt[1]));return[new i.Tensor("int64",ut,[3,...nt]),new i.Tensor("int64",Ze,[Ze.length,1])]}else{let[tt,nt]=c.dims,ut=BigInt64Array.from({length:3*tt*nt},(Ze,it)=>BigInt(Math.floor(it%nt/tt)));return[new i.Tensor("int64",ut,[3,...c.dims]),(0,i.zeros)([tt,1])]}}async encode_image({pixel_values:c,image_grid_thw:b}){return(await U(this.sessions.vision_encoder,{pixel_values:c,grid_thw:b})).image_features}_merge_input_ids_with_image_features(c){return pe({image_token_id:this.config.image_token_id,...c})}prepare_inputs_for_generation(c,b,H){if(b.attention_mask&&!b.position_ids)if(!b.past_key_values)[b.position_ids,b.rope_deltas]=this.get_rope_index(b.input_ids,b.image_grid_thw,b.video_grid_thw,b.attention_mask);else{b.pixel_values=null;let ae=BigInt(Object.values(b.past_key_values)[0].dims.at(-2)),ne=b.rope_deltas.map(_e=>ae+_e);b.position_ids=(0,i.stack)([ne,ne,ne],0)}return b}}class $n extends T{}class wc extends $n{}class Tc extends $n{}class Hn extends T{}class vc extends Hn{}class Pc extends Hn{}class Qn extends T{}class bc extends Qn{}class xc extends Qn{}class Xn extends T{}class yc extends Xn{}class Ec extends Xn{}class Jn extends T{}class Cc extends Jn{}class kc extends Jn{}class qn extends T{}class Fc extends qn{}class Ac extends qn{async _call(c){return new at(await super._call(c))}}class Yn extends T{}class Ic extends Yn{}class Sc extends Yn{async _call(c){return new at(await super._call(c))}}class Dc extends T{}class Lc extends Dc{}class Zn extends T{}class Oc extends Zn{}class Rc extends Zn{async _call(c){return new at(await super._call(c))}}class Bc extends T{}class Nc extends Bc{}class ea extends T{}class jc extends ea{}class Vc extends ea{async _call(c){return new at(await super._call(c))}}class Uc extends T{}class zc extends Uc{}class ta extends T{}class Wc extends ta{}class Gc extends ta{async _call(c){return new at(await super._call(c))}}class Kc extends T{}class $c extends Kc{async _call(c){return new mm(await super._call(c))}}class ra extends T{}class Hc extends ra{}class Qc extends ra{async _call(c){return new at(await super._call(c))}}class sa extends T{}class Xc extends sa{}class Jc extends sa{async _call(c){return new at(await super._call(c))}}class oa extends T{}class qc extends oa{}class Yc extends oa{}class na extends T{}class Zc extends na{}class ed extends na{}class aa extends T{}class td extends aa{}class rd extends aa{async _call(c){return new at(await super._call(c))}}class eo extends T{}class sd extends eo{}class od extends eo{async _call(c){return new la(await super._call(c))}}class ia extends eo{async _call(c){return new nd(await super._call(c))}}class la extends X{constructor({logits:c,pred_boxes:b}){super(),this.logits=c,this.pred_boxes=b}}class nd extends X{constructor({logits:c,pred_boxes:b,pred_masks:H}){super(),this.logits=c,this.pred_boxes=b,this.pred_masks=H}}class ca extends T{}class ad extends ca{}class id extends ca{async _call(c){return new Ss(await super._call(c))}}class Ss extends X{constructor({logits:c,pred_boxes:b}){super(),this.logits=c,this.pred_boxes=b}}class da extends T{}class ld extends da{}class cd extends da{async _call(c){return new dd(await super._call(c))}}class dd extends Ss{}class _a extends T{}class _d extends _a{}class ud extends _a{async _call(c){return new pd(await super._call(c))}}class pd extends Ss{}class ua extends T{}class md extends ua{}class hd extends ua{async _call(c){return new Ss(await super._call(c))}}class pa extends T{}class fd extends pa{}class gd extends pa{async _call(c){return new Md(await super._call(c))}}class Md extends la{}class ma extends T{}class wd extends ma{}class Td extends ma{async _call(c){return new at(await super._call(c))}}class ha extends T{}class vd extends ha{}class Pd extends ha{async _call(c){return new at(await super._call(c))}}class fa extends T{}class bd extends fa{}class xd extends fa{async _call(c){return new at(await super._call(c))}}class to extends T{}class yd extends to{}class Ed extends to{async _call(c){return new at(await super._call(c))}}class Cd extends to{}class ga extends T{}class kd extends ga{}class Fd extends ga{}class Ma extends T{}class Ad extends Ma{}class Id extends Ma{}class Sd extends T{}class Dd extends Sd{}class ro extends T{}class Ld extends ro{}class Od extends ro{}class Rd extends ro{}class Bd extends T{}class Nd extends Bd{}class jd extends T{}class Vd extends jd{}class Ud extends T{}class zd extends Ud{}class wa extends T{}class Wd extends wa{}class Gd extends wa{}class Ta extends T{}class Kd extends Ta{}class $d extends Ta{}class Hd extends T{}class Qd extends Hd{}class va extends T{}class Xd extends va{}class Jd extends va{async _call(c){return new at(await super._call(c))}}class Pa extends T{}class qd extends Pa{}class Yd extends Pa{async _call(c){return new at(await super._call(c))}}class ba extends T{}class Zd extends ba{}class e_ extends ba{async _call(c){return new at(await super._call(c))}}class xa extends T{}class t_ extends xa{}class r_ extends xa{async _call(c){return new at(await super._call(c))}}class s_ extends T{}class o_ extends s_{}class n_ extends T{}class a_ extends n_{}class i_ extends T{}class l_ extends i_{}class ya extends T{}class c_ extends ya{}class d_ extends ya{async _call(c){return new __(await super._call(c))}}class __ extends X{constructor({logits:c,pred_boxes:b}){super(),this.logits=c,this.pred_boxes=b}}class u_ extends T{}class p_ extends u_{async get_image_embeddings({pixel_values:c}){return await se(this,{pixel_values:c})}async forward(c){!c.image_embeddings||!c.image_positional_embeddings?c={...c,...await this.get_image_embeddings(c)}:c={...c},c.input_labels??(c.input_labels=(0,i.ones)(c.input_points.dims.slice(0,-1)));let b={image_embeddings:c.image_embeddings,image_positional_embeddings:c.image_positional_embeddings};return c.input_points&&(b.input_points=c.input_points),c.input_labels&&(b.input_labels=c.input_labels),c.input_boxes&&(b.input_boxes=c.input_boxes),await U(this.sessions.prompt_encoder_mask_decoder,b)}async _call(c){return new m_(await super._call(c))}}class m_ extends X{constructor({iou_scores:c,pred_masks:b}){super(),this.iou_scores=c,this.pred_masks=b}}class h_ extends X{constructor({iou_scores:c,pred_masks:b,object_score_logits:H}){super(),this.iou_scores=c,this.pred_masks=b,this.object_score_logits=H}}class f_ extends T{}class so extends f_{async get_image_embeddings({pixel_values:c}){return await se(this,{pixel_values:c})}async forward(c){let{num_feature_levels:b}=this.config.vision_config;if(Array.from({length:b},(_e,Ee)=>`image_embeddings.${Ee}`).some(_e=>!c[_e])?c={...c,...await this.get_image_embeddings(c)}:c={...c},c.input_points){if(c.input_boxes&&c.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.");let _e=c.input_points.dims;c.input_labels??(c.input_labels=(0,i.ones)(_e.slice(0,-1))),c.input_boxes??(c.input_boxes=(0,i.full)([_e[0],0,4],0))}else if(c.input_boxes){let _e=c.input_boxes.dims;c.input_labels=(0,i.full)([_e[0],_e[1],0],-1n),c.input_points=(0,i.full)([_e[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let ae=this.sessions.prompt_encoder_mask_decoder,ne=(0,u.pick)(c,ae.inputNames);return await U(ae,ne)}async _call(c){return new h_(await super._call(c))}}class g_ extends so{}class M_ extends so{}class Ea extends T{}class w_ extends Ea{}class T_ extends Ea{}class Ca extends T{}class v_ extends Ca{}class P_ extends Ca{}class Br extends T{}class b_ extends Br{}class x_ extends Br{async _call(c){return new Nr(await super._call(c))}}class y_ extends Br{async _call(c){return new at(await super._call(c))}}class E_ extends Br{async _call(c){return new Bt(await super._call(c))}}class C_ extends T{}class k_ extends C_{async _call(c){return new Nr(await super._call(c))}}class ka extends T{}class F_ extends ka{}class A_ extends ka{async _call(c){return new Bt(await super._call(c))}}class I_ extends T{}class S_ extends I_{}class oo extends T{}class D_ extends oo{}class L_ extends oo{async _call(c){return new Nr(await super._call(c))}}class O_ extends oo{async _call(c){return new at(await super._call(c))}}class Ds extends T{}class R_ extends Ds{}class B_ extends Ds{async _call(c){return new Nr(await super._call(c))}}class N_ extends Ds{async _call(c){return new at(await super._call(c))}}class j_ extends Ds{async _call(c){return new Bt(await super._call(c))}}class no extends T{}class V_ extends no{}class U_ extends no{async _call(c){return new Nr(await super._call(c))}}class z_ extends no{async _call(c){return new at(await super._call(c))}}class xh extends T{}class W_ extends Br{}class G_ extends Br{async _call(c){return new Nr(await super._call(c))}}class K_ extends Br{async _call(c){return new at(await super._call(c))}}class hs extends T{}class $_ extends hs{}class H_ extends hs{async _call(c){return new Nr(await super._call(c))}}class Q_ extends hs{async _call(c){return new at(await super._call(c))}}class X_ extends hs{async _call(c){return new pm(await super._call(c))}}class J_ extends hs{async _call(c){return new Bt(await super._call(c))}}class q_ extends T{}class Y_ extends q_{}class ao extends T{}class yh extends ao{}class Z_ extends ao{}class eu extends ao{async generate_speech(c,b,{threshold:H=.5,minlenratio:ae=0,maxlenratio:ne=20,vocoder:_e=null}={}){let Ee={input_ids:c},{encoder_outputs:Se,encoder_attention_mask:Ne}=await se(this,Ee),Ye=Se.dims[1]/this.config.reduction_factor,tt=Math.floor(Ye*ne),nt=Math.floor(Ye*ae),ut=this.config.num_mel_bins,Ze=[],it=null,Xe=null,dt=0;for(;;){++dt;let Et=$(!!Xe),Ct;Xe?Ct=Xe.output_sequence_out:Ct=new i.Tensor("float32",new Float32Array(ut),[1,1,ut]);let Ot={use_cache_branch:Et,output_sequence:Ct,encoder_attention_mask:Ne,speaker_embeddings:b,encoder_hidden_states:Se};this.addPastKeyValues(Ot,it),Xe=await U(this.sessions.decoder_model_merged,Ot),it=this.getPastKeyValues(Xe,it);let{prob:pt,spectrum:kt}=Xe;if(Ze.push(kt),dt>=nt&&(Array.from(pt.data).filter($t=>$t>=H).length>0||dt>=tt))break}let ht=(0,i.cat)(Ze),{waveform:yt}=await U(_e.sessions.model,{spectrogram:ht});return{spectrogram:ht,waveform:yt}}}class tu extends T{constructor(){super(...arguments);v(this,"main_input_name","spectrogram")}}class ru extends T{}class Fa extends ru{async generate_speech({input_ids:c,attention_mask:b,style:H,num_inference_steps:ae=5,speed:ne=1.05}){let{sampling_rate:_e,chunk_compress_factor:Ee,base_chunk_size:Se,latent_dim:Ne}=this.config,{last_hidden_state:Ye,durations:tt}=await U(this.sessions.text_encoder,{input_ids:c,attention_mask:b,style:H});tt.div_(ne);let nt=tt.max().item()*_e,ut=Se*Ee,Ze=Math.floor((nt+ut-1)/ut),it=c.dims[0],Xe=(0,i.ones)([it,Ze]),dt=(0,i.full)([it],ae),ht=(0,i.randn)([it,Ne*Ee,Ze]);for(let Et=0;Et<ae;++Et){let Ct=(0,i.full)([it],Et);({denoised_latents:ht}=await U(this.sessions.latent_denoiser,{style:H,noisy_latents:ht,latent_mask:Xe,encoder_outputs:Ye,attention_mask:b,timestep:Ct,num_inference_steps:dt}))}let{waveform:yt}=await U(this.sessions.voice_decoder,{latents:ht});return{waveform:yt,durations:tt}}}class su extends T{}class ou extends su{}class Aa extends T{}class nu extends Aa{}class au extends Aa{}class Ia extends T{}class iu extends Ia{}class lu extends Ia{}class Sa extends T{}class cu extends Sa{}class du extends Sa{}class Da extends T{}class _u extends Da{}class uu extends Da{}class La extends T{}class pu extends La{}class mu extends La{}class Oa extends T{}class hu extends Oa{}class fu extends Oa{}class io extends T{}class gu extends io{}class Mu extends io{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"text_model"})}}class wu extends io{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"audio_model"})}}class Tu extends T{}class Ra extends Tu{async _call(c){return new hm(await super._call(c))}}class lo extends T{}class Eh extends lo{}class vu extends lo{}class Pu extends lo{}class Ba extends T{}class bu extends Ba{}class xu extends Ba{}class Na extends T{}class yu extends Na{}class Eu extends Na{async _call(c){return new at(await super._call(c))}}class ja extends T{}class Ch extends ja{}class kh extends ja{}class Va extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(b){let[H,ae]=b.dims,ne=this.config.decoder.num_codebooks,_e=ae-ne,Ee=0;for(let Ye=0;Ye<b.size;++Ye){if(b.data[Ye]===this.config.decoder.pad_token_id)continue;let tt=Ye%ae,nt=Math.floor(Ye/ae)%ne,ut=tt-nt;ut>0&&ut<=_e&&(b.data[Ee++]=b.data[Ye])}let Se=Math.floor(H/ne),Ne=Ee/(Se*ne);return new i.Tensor(b.type,b.data.slice(0,Ee),[Se,ne,Ne])}prepare_inputs_for_generation(b,H,ae){let ne=structuredClone(b);for(let Ee=0;Ee<ne.length;++Ee)for(let Se=0;Se<ne[Ee].length;++Se)Ee%this.config.decoder.num_codebooks>=Se&&(ne[Ee][Se]=BigInt(this.config.decoder.pad_token_id));return ae.guidance_scale!==null&&ae.guidance_scale>1&&(ne=ne.concat(ne)),super.prepare_inputs_for_generation(ne,H,ae)}async generate(b){let H=await super.generate(b),ae=this._apply_and_filter_by_delay_pattern_mask(H).unsqueeze_(0),{audio_values:ne}=await U(this.sessions.encodec_decode,{audio_codes:ae});return ne}}class co extends T{}class Cu extends co{}class ku extends co{async _call(c){return new at(await super._call(c))}}class Fu extends co{}class _o extends T{}class Au extends _o{}class Iu extends _o{async _call(c){return new at(await super._call(c))}}class Su extends _o{}class uo extends T{}class Du extends uo{}class Lu extends uo{async _call(c){return new at(await super._call(c))}}class Ou extends uo{}class po extends T{}class Ru extends po{}class Bu extends po{async _call(c){return new at(await super._call(c))}}class Nu extends po{}class ju extends T{}class Vu extends ju{}class Uu extends T{}class zu extends Uu{constructor(...b){super(...b);v(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(b){let H=this._generation_mode??"text",ae;if(H==="text"||!b.past_key_values){let Ne=this.sessions.prepare_inputs_embeds,Ye=(0,u.pick)(b,Ne.inputNames);ae=await U(Ne,Ye)}else{let Ne=this.sessions.gen_img_embeds,Ye=(0,u.pick)({image_ids:b.input_ids},Ne.inputNames);ae=await U(Ne,Ye)}let ne={...b,...ae},_e=await ue(this,ne),Ee=this.sessions[H==="text"?"lm_head":"gen_head"];if(!Ee)throw new Error(`Unable to find "${Ee}" generation head`);let Se=await U(Ee,(0,u.pick)(_e,Ee.inputNames));return{...ae,..._e,...Se}}async generate(b){return this._generation_mode="text",super.generate(b)}async generate_images(b){this._generation_mode="image";let H=(b.inputs??b[this.main_input_name]).dims[1],ne=(await super.generate(b)).slice(null,[H,null]),_e=this.sessions.image_decode,{decoded_image:Ee}=await U(_e,{generated_tokens:ne}),Se=Ee.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ne=[];for(let Ye of Se){let tt=y.RawImage.fromTensor(Ye);Ne.push(tt)}return Ne}}class Wu extends X{constructor({char_logits:c,bpe_logits:b,wp_logits:H}){super(),this.char_logits=c,this.bpe_logits=b,this.wp_logits=H}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Gu extends T{}class Ku extends Gu{async _call(c){return new Wu(await super._call(c))}}class Ua extends T{}class $u extends Ua{}class Hu extends Ua{}class za extends T{}class Qu extends za{}class Xu extends za{}class Ju extends T{constructor(){super(...arguments);v(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Wa extends Ju{_merge_input_ids_with_audio_features(c){let b=c.audio_features.dims.at(-1),H=c.audio_features.view(-1,b);return J({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...c,audio_features:H})}}class qu extends Wa{}class mo extends T{constructor(){super(...arguments);v(this,"main_input_name","input_values");v(this,"forward_params",["input_values"])}}class Yu extends X{constructor({audio_codes:c}){super(),this.audio_codes=c}}class Zu extends X{constructor({audio_values:c}){super(),this.audio_values=c}}class ep extends mo{async encode(c){return new Yu(await U(this.sessions.encoder_model,c))}async decode(c){return new Zu(await U(this.sessions.decoder_model,c))}}class tp extends mo{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"encoder_model"})}}class rp extends mo{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"decoder_model"})}}class ho extends T{constructor(){super(...arguments);v(this,"main_input_name","input_values");v(this,"forward_params",["input_values"])}}class sp extends X{constructor({audio_codes:c}){super(),this.audio_codes=c}}class op extends X{constructor({audio_values:c}){super(),this.audio_values=c}}class np extends ho{async encode(c){return new sp(await U(this.sessions.encoder_model,c))}async decode(c){return new op(await U(this.sessions.decoder_model,c))}}class ap extends ho{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"encoder_model"})}}class ip extends ho{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"decoder_model"})}}class fo extends T{constructor(){super(...arguments);v(this,"main_input_name","input_values");v(this,"forward_params",["input_values"])}}class lp extends fo{async encode(c){return await U(this.sessions.encoder_model,c)}async decode(c){return await U(this.sessions.decoder_model,c)}}class cp extends fo{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"encoder_model"})}}class dp extends fo{static async from_pretrained(c,b={}){return super.from_pretrained(c,{...b,model_file_name:b.model_file_name??"decoder_model"})}}class gt{static async from_pretrained(c,{progress_callback:b=null,config:H=null,cache_dir:ae=null,local_files_only:ne=!1,revision:_e="main",model_file_name:Ee=null,subfolder:Se="onnx",device:Ne=null,dtype:Ye=null,use_external_data_format:tt=null,session_options:nt={}}={}){let ut={progress_callback:b,config:H,cache_dir:ae,local_files_only:ne,revision:_e,model_file_name:Ee,subfolder:Se,device:Ne,dtype:Ye,use_external_data_format:tt,session_options:nt};if(ut.config=await r.AutoConfig.from_pretrained(c,ut),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let Ze=ut.config.model_type;for(let it of this.MODEL_CLASS_MAPPINGS){let Xe=it.get(Ze);if(!Xe){for(let dt of it.values())if(dt[0]===Ze){Xe=dt;break}if(!Xe)continue}return await Xe[1].from_pretrained(c,ut)}if(this.BASE_IF_FAIL)return Rp.has(Ze)||console.warn(`Unknown model class "${Ze}", attempting to construct from base class.`),await T.from_pretrained(c,ut);throw Error(`Unsupported model type: ${Ze}`)}}v(gt,"MODEL_CLASS_MAPPINGS",null),v(gt,"BASE_IF_FAIL",!1);let Fh=new Map([["bert",["BertModel",Te]],["neobert",["NeoBertModel",Re]],["modernbert",["ModernBertModel",ze]],["nomic_bert",["NomicBertModel",vt]],["roformer",["RoFormerModel",ls]],["electra",["ElectraModel",_t]],["esm",["EsmModel",Hr]],["convbert",["ConvBertModel",_s]],["camembert",["CamembertModel",V]],["deberta",["DebertaModel",st]],["deberta-v2",["DebertaV2Model",ar]],["mpnet",["MPNetModel",Qr]],["albert",["AlbertModel",Le]],["distilbert",["DistilBertModel",Kr]],["roberta",["RobertaModel",xi]],["xlm",["XLMModel",Fi]],["xlm-roberta",["XLMRobertaModel",Li]],["clap",["ClapModel",gu]],["clip",["CLIPModel",el]],["clipseg",["CLIPSegModel",_l]],["chinese_clip",["ChineseCLIPModel",il]],["siglip",["SiglipModel",sl]],["jina_clip",["JinaCLIPModel",ll]],["mobilebert",["MobileBertModel",ir]],["squeezebert",["SqueezeBertModel",L]],["wav2vec2",["Wav2Vec2Model",b_]],["wav2vec2-bert",["Wav2Vec2BertModel",V_]],["unispeech",["UniSpeechModel",D_]],["unispeech-sat",["UniSpeechSatModel",R_]],["hubert",["HubertModel",W_]],["wavlm",["WavLMModel",$_]],["audio-spectrogram-transformer",["ASTModel",ji]],["vits",["VitsModel",Ra]],["pyannote",["PyAnnoteModel",F_]],["wespeaker-resnet",["WeSpeakerResNetModel",S_]],["detr",["DetrModel",sd]],["rt_detr",["RTDetrModel",ad]],["rt_detr_v2",["RTDetrV2Model",ld]],["rf_detr",["RFDetrModel",_d]],["d_fine",["DFineModel",md]],["table-transformer",["TableTransformerModel",fd]],["vit",["ViTModel",Fc]],["ijepa",["IJepaModel",Ic]],["pvt",["PvtModel",Oc]],["vit_msn",["ViTMSNModel",jc]],["vit_mae",["ViTMAEModel",Nc]],["groupvit",["GroupViTModel",zc]],["fastvit",["FastViTModel",Wc]],["mobilevit",["MobileViTModel",Hc]],["mobilevitv2",["MobileViTV2Model",Xc]],["owlvit",["OwlViTModel",qc]],["owlv2",["Owlv2Model",Zc]],["beit",["BeitModel",td]],["deit",["DeiTModel",wd]],["hiera",["HieraModel",vd]],["convnext",["ConvNextModel",Xd]],["convnextv2",["ConvNextV2Model",qd]],["dinov2",["Dinov2Model",Zd]],["dinov2_with_registers",["Dinov2WithRegistersModel",t_]],["dinov3_vit",["DINOv3ViTModel",o_]],["dinov3_convnext",["DINOv3ConvNextModel",a_]],["resnet",["ResNetModel",bd]],["swin",["SwinModel",yd]],["swin2sr",["Swin2SRModel",kd]],["donut-swin",["DonutSwinModel",Qd]],["yolos",["YolosModel",c_]],["dpt",["DPTModel",Ad]],["glpn",["GLPNModel",Kd]],["hifigan",["SpeechT5HifiGan",tu]],["efficientnet",["EfficientNetModel",yu]],["decision_transformer",["DecisionTransformerModel",Vu]],["patchtst",["PatchTSTForPrediction",$u]],["patchtsmixer",["PatchTSMixerForPrediction",Qu]],["mobilenet_v1",["MobileNetV1Model",Cu]],["mobilenet_v2",["MobileNetV2Model",Au]],["mobilenet_v3",["MobileNetV3Model",Du]],["mobilenet_v4",["MobileNetV4Model",Ru]],["maskformer",["MaskFormerModel",Wd]],["mgp-str",["MgpstrForSceneTextRecognition",Ku]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Y_]]]),Ah=new Map([["t5",["T5Model",Mt]],["longt5",["LongT5Model",Pt]],["mt5",["MT5Model",lr]],["bart",["BartModel",Or]],["mbart",["MBartModel",Pr]],["marian",["MarianModel",w_]],["whisper",["WhisperModel",Ui]],["m2m_100",["M2M100Model",v_]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",dr]]]),Ih=new Map([["mimi",["MimiModel",ep]],["dac",["DacModel",np]],["snac",["SnacModel",lp]]]),Sh=new Map([["bloom",["BloomModel",bc]],["jais",["JAISModel",hl]],["gpt2",["GPT2Model",pl]],["gptj",["GPTJModel",vl]],["gpt_bigcode",["GPTBigCodeModel",bl]],["gpt_neo",["GPTNeoModel",gl]],["gpt_neox",["GPTNeoXModel",wl]],["codegen",["CodeGenModel",yl]],["llama",["LlamaModel",Cl]],["nanochat",["NanoChatModel",Il]],["arcee",["ArceeModel",Dl]],["lfm2",["Lfm2Model",Ol]],["smollm3",["SmolLM3Model",Bl]],["exaone",["ExaoneModel",Wl]],["olmo",["OlmoModel",Hl]],["olmo2",["Olmo2Model",Xl]],["mobilellm",["MobileLLMModel",Kl]],["granite",["GraniteModel",ql]],["granitemoehybrid",["GraniteMoeHybridModel",Zl]],["cohere",["CohereModel",tc]],["gemma",["GemmaModel",sc]],["gemma2",["Gemma2Model",nc]],["vaultgemma",["VaultGemmaModel",ic]],["gemma3_text",["Gemma3Model",cc]],["helium",["HeliumModel",jl]],["glm",["GlmModel",Ul]],["openelm",["OpenELMModel",_c]],["qwen2",["Qwen2Model",pc]],["qwen3",["Qwen3Model",hc]],["phi",["PhiModel",wc]],["phi3",["Phi3Model",vc]],["mpt",["MptModel",yc]],["opt",["OPTModel",Cc]],["mistral",["MistralModel",nu]],["ministral",["MinistralModel",iu]],["ministral3",["Ministral3Model",cu]],["ernie4_5",["Ernie4_5Model",_u]],["starcoder2",["Starcoder2Model",pu]],["falcon",["FalconModel",hu]],["stablelm",["StableLmModel",bu]],["modernbert-decoder",["ModernBertDecoderModel",mt]]]),Ga=new Map([["speecht5",["SpeechT5ForSpeechToText",Z_]],["whisper",["WhisperForConditionalGeneration",ln]],["lite-whisper",["LiteWhisperForConditionalGeneration",zi]],["moonshine",["MoonshineForConditionalGeneration",Wi]]]),_p=new Map([["speecht5",["SpeechT5ForTextToSpeech",eu]]]),up=new Map([["vits",["VitsModel",Ra]],["musicgen",["MusicgenForConditionalGeneration",Va]],["supertonic",["SupertonicForConditionalGeneration",Fa]]]),pp=new Map([["bert",["BertForSequenceClassification",le]],["neobert",["NeoBertForSequenceClassification",Ie]],["modernbert",["ModernBertForSequenceClassification",et]],["roformer",["RoFormerForSequenceClassification",ds]],["electra",["ElectraForSequenceClassification",m]],["esm",["EsmForSequenceClassification",Sr]],["convbert",["ConvBertForSequenceClassification",Ur]],["camembert",["CamembertForSequenceClassification",me]],["deberta",["DebertaForSequenceClassification",ct]],["deberta-v2",["DebertaV2ForSequenceClassification",Cr]],["mpnet",["MPNetForSequenceClassification",Xr]],["albert",["AlbertForSequenceClassification",We]],["distilbert",["DistilBertForSequenceClassification",Ar]],["roberta",["RobertaForSequenceClassification",Ei]],["xlm",["XLMForSequenceClassification",Ii]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ri]],["bart",["BartForSequenceClassification",Kt]],["mbart",["MBartForSequenceClassification",sr]],["mobilebert",["MobileBertForSequenceClassification",De]],["squeezebert",["SqueezeBertForSequenceClassification",q]]]),mp=new Map([["bert",["BertForTokenClassification",ve]],["neobert",["NeoBertForTokenClassification",Fe]],["modernbert",["ModernBertForTokenClassification",Ue]],["roformer",["RoFormerForTokenClassification",St]],["electra",["ElectraForTokenClassification",j]],["esm",["EsmForTokenClassification",Dr]],["convbert",["ConvBertForTokenClassification",zr]],["camembert",["CamembertForTokenClassification",Ke]],["deberta",["DebertaForTokenClassification",ft]],["deberta-v2",["DebertaV2ForTokenClassification",kr]],["mpnet",["MPNetForTokenClassification",Is]],["distilbert",["DistilBertForTokenClassification",$r]],["roberta",["RobertaForTokenClassification",Ci]],["xlm",["XLMForTokenClassification",Si]],["xlm-roberta",["XLMRobertaForTokenClassification",Bi]]]),Ka=new Map([["t5",["T5ForConditionalGeneration",Tt]],["longt5",["LongT5ForConditionalGeneration",tr]],["mt5",["MT5ForConditionalGeneration",vr]],["bart",["BartForConditionalGeneration",At]],["mbart",["MBartForConditionalGeneration",yr]],["marian",["MarianMTModel",T_]],["m2m_100",["M2M100ForConditionalGeneration",P_]],["blenderbot",["BlenderbotForConditionalGeneration",Rt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",us]]]),$a=new Map([["bloom",["BloomForCausalLM",xc]],["gpt2",["GPT2LMHeadModel",ml]],["jais",["JAISLMHeadModel",fl]],["gptj",["GPTJForCausalLM",Pl]],["gpt_bigcode",["GPTBigCodeForCausalLM",xl]],["gpt_neo",["GPTNeoForCausalLM",Ml]],["gpt_neox",["GPTNeoXForCausalLM",Tl]],["codegen",["CodeGenForCausalLM",El]],["llama",["LlamaForCausalLM",kl]],["nanochat",["NanoChatForCausalLM",Sl]],["llama4_text",["Llama4ForCausalLM",Al]],["arcee",["ArceeForCausalLM",Ll]],["lfm2",["Lfm2ForCausalLM",Rl]],["smollm3",["SmolLM3ForCausalLM",Nl]],["exaone",["ExaoneForCausalLM",Gl]],["olmo",["OlmoForCausalLM",Ql]],["olmo2",["Olmo2ForCausalLM",Jl]],["mobilellm",["MobileLLMForCausalLM",$l]],["granite",["GraniteForCausalLM",Yl]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",ec]],["cohere",["CohereForCausalLM",rc]],["gemma",["GemmaForCausalLM",oc]],["gemma2",["Gemma2ForCausalLM",ac]],["vaultgemma",["VaultGemmaForCausalLM",lc]],["gemma3_text",["Gemma3ForCausalLM",dc]],["helium",["HeliumForCausalLM",Vl]],["glm",["GlmForCausalLM",zl]],["openelm",["OpenELMForCausalLM",uc]],["qwen2",["Qwen2ForCausalLM",mc]],["qwen3",["Qwen3ForCausalLM",fc]],["phi",["PhiForCausalLM",Tc]],["phi3",["Phi3ForCausalLM",Pc]],["mpt",["MptForCausalLM",Ec]],["opt",["OPTForCausalLM",kc]],["mbart",["MBartForCausalLM",br]],["mistral",["MistralForCausalLM",au]],["ministral",["MinistralForCausalLM",lu]],["ministral3",["Ministral3ForCausalLM",du]],["ernie4_5",["Ernie4_5ForCausalLM",uu]],["starcoder2",["Starcoder2ForCausalLM",mu]],["falcon",["FalconForCausalLM",fu]],["trocr",["TrOCRForCausalLM",ou]],["stablelm",["StableLmForCausalLM",xu]],["modernbert-decoder",["ModernBertDecoderForCausalLM",bt]],["phi3_v",["Phi3VForCausalLM",hn]]]),Dh=new Map([["multi_modality",["MultiModalityCausalLM",zu]]]),hp=new Map([["bert",["BertForMaskedLM",ge]],["neobert",["NeoBertForMaskedLM",Ce]],["modernbert",["ModernBertForMaskedLM",Ae]],["roformer",["RoFormerForMaskedLM",cs]],["electra",["ElectraForMaskedLM",Gr]],["esm",["EsmForMaskedLM",Ir]],["convbert",["ConvBertForMaskedLM",rt]],["camembert",["CamembertForMaskedLM",te]],["deberta",["DebertaForMaskedLM",Ge]],["deberta-v2",["DebertaV2ForMaskedLM",Xt]],["mpnet",["MPNetForMaskedLM",Lr]],["albert",["AlbertForMaskedLM",$e]],["distilbert",["DistilBertForMaskedLM",Mr]],["roberta",["RobertaForMaskedLM",yi]],["xlm",["XLMWithLMHeadModel",Ai]],["xlm-roberta",["XLMRobertaForMaskedLM",Oi]],["mobilebert",["MobileBertForMaskedLM",ke]],["squeezebert",["SqueezeBertForMaskedLM",W]]]),fp=new Map([["bert",["BertForQuestionAnswering",ce]],["neobert",["NeoBertForQuestionAnswering",Je]],["roformer",["RoFormerForQuestionAnswering",er]],["electra",["ElectraForQuestionAnswering",C]],["convbert",["ConvBertForQuestionAnswering",Wr]],["camembert",["CamembertForQuestionAnswering",qe]],["deberta",["DebertaForQuestionAnswering",Qt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Fr]],["mpnet",["MPNetForQuestionAnswering",re]],["albert",["AlbertForQuestionAnswering",Be]],["distilbert",["DistilBertForQuestionAnswering",mr]],["roberta",["RobertaForQuestionAnswering",ki]],["xlm",["XLMForQuestionAnswering",Di]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ni]],["mobilebert",["MobileBertForQuestionAnswering",Qe]],["squeezebert",["SqueezeBertForQuestionAnswering",ee]]]),Ha=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",dn]],["idefics3",["Idefics3ForConditionalGeneration",Ys]],["smolvlm",["SmolVLMForConditionalGeneration",mn]]]),gp=new Map([["llava",["LlavaForConditionalGeneration",qs]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Gi]],["moondream1",["Moondream1ForConditionalGeneration",Ki]],["florence2",["Florence2ForConditionalGeneration",Hi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Mc]],["idefics3",["Idefics3ForConditionalGeneration",Ys]],["smolvlm",["SmolVLMForConditionalGeneration",mn]],["paligemma",["PaliGemmaForConditionalGeneration",Xi]],["llava_qwen2",["LlavaQwen2ForCausalLM",un]],["gemma3n",["Gemma3nForConditionalGeneration",pn]],["mistral3",["Mistral3ForConditionalGeneration",Ji]]]),Mp=new Map([["ultravox",["UltravoxModel",Wa]],["voxtral",["VoxtralForConditionalGeneration",qu]]]),Lh=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",dn]]]),wp=new Map([["vit",["ViTForImageClassification",Ac]],["ijepa",["IJepaForImageClassification",Sc]],["pvt",["PvtForImageClassification",Rc]],["vit_msn",["ViTMSNForImageClassification",Vc]],["fastvit",["FastViTForImageClassification",Gc]],["mobilevit",["MobileViTForImageClassification",Qc]],["mobilevitv2",["MobileViTV2ForImageClassification",Jc]],["beit",["BeitForImageClassification",rd]],["deit",["DeiTForImageClassification",Td]],["hiera",["HieraForImageClassification",Pd]],["convnext",["ConvNextForImageClassification",Jd]],["convnextv2",["ConvNextV2ForImageClassification",Yd]],["dinov2",["Dinov2ForImageClassification",e_]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",r_]],["resnet",["ResNetForImageClassification",xd]],["swin",["SwinForImageClassification",Ed]],["segformer",["SegformerForImageClassification",vu]],["efficientnet",["EfficientNetForImageClassification",Eu]],["mobilenet_v1",["MobileNetV1ForImageClassification",ku]],["mobilenet_v2",["MobileNetV2ForImageClassification",Iu]],["mobilenet_v3",["MobileNetV3ForImageClassification",Lu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Bu]]]),Tp=new Map([["detr",["DetrForObjectDetection",od]],["rt_detr",["RTDetrForObjectDetection",id]],["rt_detr_v2",["RTDetrV2ForObjectDetection",cd]],["rf_detr",["RFDetrForObjectDetection",ud]],["d_fine",["DFineForObjectDetection",hd]],["table-transformer",["TableTransformerForObjectDetection",gd]],["yolos",["YolosForObjectDetection",d_]]]),vp=new Map([["owlvit",["OwlViTForObjectDetection",Yc]],["owlv2",["Owlv2ForObjectDetection",ed]],["grounding-dino",["GroundingDinoForObjectDetection",l_]]]),fs=new Map([["detr",["DetrForSegmentation",ia]],["clipseg",["CLIPSegForImageSegmentation",ul]]]),Pp=new Map([["segformer",["SegformerForSemanticSegmentation",Pu]],["sapiens",["SapiensForSemanticSegmentation",Ld]],["swin",["SwinForSemanticSegmentation",Cd]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Fu]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Su]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Ou]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Nu]]]),bp=new Map([["detr",["DetrForSegmentation",ia]],["maskformer",["MaskFormerForInstanceSegmentation",Gd]]]),xp=new Map([["sam",["SamModel",p_]],["sam2",["Sam2Model",so]],["edgetam",["EdgeTamModel",g_]],["sam3_tracker",["Sam3TrackerModel",M_]]]),yp=new Map([["wav2vec2",["Wav2Vec2ForCTC",x_]],["wav2vec2-bert",["Wav2Vec2BertForCTC",U_]],["unispeech",["UniSpeechForCTC",L_]],["unispeech-sat",["UniSpeechSatForCTC",B_]],["wavlm",["WavLMForCTC",H_]],["hubert",["HubertForCTC",G_]],["parakeet_ctc",["ParakeetForCTC",k_]]]),Ep=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",y_]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",z_]],["unispeech",["UniSpeechForSequenceClassification",O_]],["unispeech-sat",["UniSpeechSatForSequenceClassification",N_]],["wavlm",["WavLMForSequenceClassification",Q_]],["hubert",["HubertForSequenceClassification",K_]],["audio-spectrogram-transformer",["ASTForAudioClassification",Vi]]]),Cp=new Map([["wavlm",["WavLMForXVector",X_]]]),kp=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",j_]],["wavlm",["WavLMForAudioFrameClassification",J_]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",E_]],["pyannote",["PyAnnoteForAudioFrameClassification",A_]]]),Fp=new Map([["vitmatte",["VitMatteForImageMatting",$c]]]),Oh=new Map([["patchtst",["PatchTSTForPrediction",Hu]],["patchtsmixer",["PatchTSMixerForPrediction",Xu]]]),Ap=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Fd]]]),Ip=new Map([["dpt",["DPTForDepthEstimation",Id]],["depth_anything",["DepthAnythingForDepthEstimation",Dd]],["glpn",["GLPNForDepthEstimation",$d]],["sapiens",["SapiensForDepthEstimation",Od]],["depth_pro",["DepthProForDepthEstimation",Nd]],["metric3d",["Metric3DForDepthEstimation",Vd]],["metric3dv2",["Metric3Dv2ForDepthEstimation",zd]]]),Sp=new Map([["sapiens",["SapiensForNormalEstimation",Rd]]]),Dp=new Map([["vitpose",["VitPoseForPoseEstimation",Lc]]]),Lp=new Map([["clip",["CLIPVisionModelWithProjection",rl]],["siglip",["SiglipVisionModel",nl]],["jina_clip",["JinaCLIPVisionModel",dl]]]),Op=[[Fh,x.EncoderOnly],[Ah,x.EncoderDecoder],[Sh,x.DecoderOnly],[Ih,x.AutoEncoder],[pp,x.EncoderOnly],[mp,x.EncoderOnly],[Ka,x.Seq2Seq],[Ga,x.Seq2Seq],[$a,x.DecoderOnly],[Dh,x.MultiModality],[hp,x.EncoderOnly],[fp,x.EncoderOnly],[Ha,x.Vision2Seq],[gp,x.ImageTextToText],[Mp,x.AudioTextToText],[wp,x.EncoderOnly],[fs,x.EncoderOnly],[bp,x.EncoderOnly],[Pp,x.EncoderOnly],[Fp,x.EncoderOnly],[Oh,x.EncoderOnly],[Ap,x.EncoderOnly],[Ip,x.EncoderOnly],[Sp,x.EncoderOnly],[Dp,x.EncoderOnly],[Tp,x.EncoderOnly],[vp,x.EncoderOnly],[xp,x.MaskGeneration],[yp,x.EncoderOnly],[Ep,x.EncoderOnly],[_p,x.Seq2Seq],[up,x.EncoderOnly],[Cp,x.EncoderOnly],[kp,x.EncoderOnly],[Lp,x.EncoderOnly]];for(let[n,c]of Op)for(let[b,H]of n.values())P.set(b,c),_.set(H,b),D.set(b,H);let Rh=[["MusicgenForConditionalGeneration",Va,x.Musicgen],["Phi3VForCausalLM",hn,x.Phi3V],["CLIPTextModelWithProjection",tl,x.EncoderOnly],["SiglipTextModel",ol,x.EncoderOnly],["JinaCLIPTextModel",cl,x.EncoderOnly],["ClapTextModelWithProjection",Mu,x.EncoderOnly],["ClapAudioModelWithProjection",wu,x.EncoderOnly],["DacEncoderModel",ap,x.EncoderOnly],["DacDecoderModel",ip,x.EncoderOnly],["MimiEncoderModel",tp,x.EncoderOnly],["MimiDecoderModel",rp,x.EncoderOnly],["SnacEncoderModel",cp,x.EncoderOnly],["SnacDecoderModel",dp,x.EncoderOnly],["Gemma3nForConditionalGeneration",pn,x.ImageAudioTextToText],["SupertonicForConditionalGeneration",Fa,x.Supertonic]];for(let[n,c,b]of Rh)P.set(n,b),_.set(c,n),D.set(n,c);let Rp=new Map([["modnet",fs],["birefnet",fs],["isnet",fs],["ben",fs]]);for(let[n,c]of Rp.entries())c.set(n,["PreTrainedModel",T]),P.set(n,x.EncoderOnly),_.set(T,n),D.set(n,T);class Qa extends gt{}v(Qa,"MODEL_CLASS_MAPPINGS",Op.map(c=>c[0])),v(Qa,"BASE_IF_FAIL",!0);class Bp extends gt{}v(Bp,"MODEL_CLASS_MAPPINGS",[pp]);class Np extends gt{}v(Np,"MODEL_CLASS_MAPPINGS",[mp]);class jp extends gt{}v(jp,"MODEL_CLASS_MAPPINGS",[Ka]);class Vp extends gt{}v(Vp,"MODEL_CLASS_MAPPINGS",[Ga]);class Up extends gt{}v(Up,"MODEL_CLASS_MAPPINGS",[_p]);class zp extends gt{}v(zp,"MODEL_CLASS_MAPPINGS",[up]);class Wp extends gt{}v(Wp,"MODEL_CLASS_MAPPINGS",[$a]);class Gp extends gt{}v(Gp,"MODEL_CLASS_MAPPINGS",[hp]);class Kp extends gt{}v(Kp,"MODEL_CLASS_MAPPINGS",[fp]);class $p extends gt{}v($p,"MODEL_CLASS_MAPPINGS",[Ha]);class Hp extends gt{}v(Hp,"MODEL_CLASS_MAPPINGS",[wp]);class Qp extends gt{}v(Qp,"MODEL_CLASS_MAPPINGS",[fs]);class Xp extends gt{}v(Xp,"MODEL_CLASS_MAPPINGS",[Pp]);class Jp extends gt{}v(Jp,"MODEL_CLASS_MAPPINGS",[bp]);class qp extends gt{}v(qp,"MODEL_CLASS_MAPPINGS",[Tp]);class Yp extends gt{}v(Yp,"MODEL_CLASS_MAPPINGS",[vp]);class Zp extends gt{}v(Zp,"MODEL_CLASS_MAPPINGS",[xp]);class em extends gt{}v(em,"MODEL_CLASS_MAPPINGS",[yp]);class tm extends gt{}v(tm,"MODEL_CLASS_MAPPINGS",[Ep]);class rm extends gt{}v(rm,"MODEL_CLASS_MAPPINGS",[Cp]);class sm extends gt{}v(sm,"MODEL_CLASS_MAPPINGS",[kp]);class om extends gt{}v(om,"MODEL_CLASS_MAPPINGS",[Lh]);class nm extends gt{}v(nm,"MODEL_CLASS_MAPPINGS",[Fp]);class am extends gt{}v(am,"MODEL_CLASS_MAPPINGS",[Ap]);class im extends gt{}v(im,"MODEL_CLASS_MAPPINGS",[Ip]);class lm extends gt{}v(lm,"MODEL_CLASS_MAPPINGS",[Sp]);class cm extends gt{}v(cm,"MODEL_CLASS_MAPPINGS",[Dp]);class dm extends gt{}v(dm,"MODEL_CLASS_MAPPINGS",[Lp]);class _m extends gt{}v(_m,"MODEL_CLASS_MAPPINGS",[gp]);class um extends gt{}v(um,"MODEL_CLASS_MAPPINGS",[Mp]);class Bh extends X{constructor({logits:c,past_key_values:b,encoder_outputs:H,decoder_attentions:ae=null,cross_attentions:ne=null}){super(),this.logits=c,this.past_key_values=b,this.encoder_outputs=H,this.decoder_attentions=ae,this.cross_attentions=ne}}class at extends X{constructor({logits:c,...b}){super(),this.logits=c;let H=Object.values(b);H.length>0&&(this.attentions=H)}}class pm extends X{constructor({logits:c,embeddings:b}){super(),this.logits=c,this.embeddings=b}}class Bt extends X{constructor({logits:c}){super(),this.logits=c}}class Wt extends X{constructor({logits:c}){super(),this.logits=c}}class Yt extends X{constructor({start_logits:c,end_logits:b}){super(),this.start_logits=c,this.end_logits=b}}class Nr extends X{constructor({logits:c}){super(),this.logits=c}}class Nh extends X{constructor({logits:c,past_key_values:b}){super(),this.logits=c,this.past_key_values=b}}class mm extends X{constructor({alphas:c}){super(),this.alphas=c}}class hm extends X{constructor({waveform:c,spectrogram:b}){super(),this.waveform=c,this.spectrogram=b}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(d,t,e)=>{e.r(t),e.d(t,{ASTFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");class h extends r.FeatureExtractor{constructor(l){super(l);let p=this.config.sampling_rate,w=(0,a.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(p/2),p,null,"kaldi",!0);this.mel_filters=w,this.window=(0,a.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(l,p){return(0,a.spectrogram)(l,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:p,transpose:!0})}async _call(l){(0,r.validate_audio_inputs)(l,"ASTFeatureExtractor");let p=await this._extract_fbank_features(l,this.config.max_length);if(this.config.do_normalize){let w=this.std*2,f=p.data;for(let i=0;i<f.length;++i)f[i]=(f[i]-this.mean)/w}return{input_values:p.unsqueeze_(0)}}}},"./src/models/auto/feature_extraction_auto.js":(d,t,e)=>{e.r(t),e.d(t,{AutoFeatureExtractor:()=>u});var r=e("./src/utils/constants.js"),o=e("./src/utils/hub.js"),a=e("./src/base/feature_extraction_utils.js"),h=e("./src/models/feature_extractors.js");class u{static async from_pretrained(p,w={}){let f=await(0,o.getModelJSON)(p,r.FEATURE_EXTRACTOR_NAME,!0,w),i=f.feature_extractor_type,y=h[i];if(!y)throw new Error(`Unknown feature_extractor_type: '${i}'. Please report this at ${r.GITHUB_ISSUE_URL}.`);return new y(f)}}},"./src/models/auto/image_processing_auto.js":(d,t,e)=>{e.r(t),e.d(t,{AutoImageProcessor:()=>u});var r=e("./src/utils/constants.js"),o=e("./src/utils/hub.js"),a=e("./src/base/image_processors_utils.js"),h=e("./src/models/image_processors.js");class u{static async from_pretrained(p,w={}){let f=await(0,o.getModelJSON)(p,r.IMAGE_PROCESSOR_NAME,!0,w),i=f.image_processor_type??f.feature_extractor_type,y=h[i?.replace(/Fast$/,"")];return y||(i!==void 0&&console.warn(`Image processor type '${i}' not found, assuming base ImageProcessor. Please report this at ${r.GITHUB_ISSUE_URL}.`),y=a.ImageProcessor),new y(f)}}},"./src/models/auto/processing_auto.js":(d,t,e)=>{e.r(t),e.d(t,{AutoProcessor:()=>p});var r=e("./src/utils/constants.js"),o=e("./src/utils/hub.js"),a=e("./src/base/processing_utils.js"),h=e("./src/models/processors.js"),u=e("./src/models/image_processors.js"),l=e("./src/models/feature_extractors.js");class p{static async from_pretrained(f,i={}){let y=await(0,o.getModelJSON)(f,r.IMAGE_PROCESSOR_NAME,!0,i),{image_processor_type:E,feature_extractor_type:S,processor_class:z}=y;if(z&&h[z])return h[z].from_pretrained(f,i);if(!E&&!S)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let k={};if(E){let N=u[E.replace(/Fast$/,"")];if(!N)throw new Error(`Unknown image_processor_type: '${E}'.`);k.image_processor=new N(y)}if(S){let N=u[S];if(N)k.image_processor=new N(y);else{let x=l[S];if(!x)throw new Error(`Unknown feature_extractor_type: '${S}'.`);k.feature_extractor=new x(y)}}let A={};return new a.Processor(A,k,null)}}},"./src/models/beit/image_processing_beit.js":(d,t,e)=>{e.r(t),e.d(t,{BeitFeatureExtractor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(d,t,e)=>{e.r(t),e.d(t,{BitImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(d,t,e)=>{e.r(t),e.d(t,{ChineseCLIPFeatureExtractor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(d,t,e)=>{e.r(t),e.d(t,{ClapFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");class h extends r.FeatureExtractor{constructor(l){super(l),this.mel_filters=(0,a.mel_filter_bank)(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=(0,a.mel_filter_bank)(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=(0,a.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(l,p,w,f){let i,y=!1,E=l.length-p;if(E>0)if(w==="rand_trunc"){y=!0;let S=Math.floor(Math.random()*(E+1));l=l.subarray(S,S+p),i=await this._extract_fbank_features(l,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${w}" not implemented`);else{if(E<0){let S=new Float64Array(p);if(S.set(l),f==="repeat")for(let z=l.length;z<p;z+=l.length)S.set(l.subarray(0,Math.min(l.length,p-z)),z);else if(f==="repeatpad")for(let z=l.length;z<-E;z+=l.length)S.set(l,z);l=S}if(w==="fusion")throw new Error(`Truncation strategy "${w}" not implemented`);i=await this._extract_fbank_features(l,this.mel_filters_slaney,this.config.nb_max_samples)}return i.unsqueeze_(0)}async _extract_fbank_features(l,p,w=null){return(0,a.spectrogram)(l,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:p,log_mel:"dB",max_num_frames:w,do_pad:!1,transpose:!0})}async _call(l,{max_length:p=null}={}){return(0,r.validate_audio_inputs)(l,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(l,p??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}},"./src/models/clip/image_processing_clip.js":(d,t,e)=>{e.r(t),e.d(t,{CLIPFeatureExtractor:()=>a,CLIPImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/convnext/image_processing_convnext.js":(d,t,e)=>{e.r(t),e.d(t,{ConvNextFeatureExtractor:()=>a,ConvNextImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{constructor(u){super(u),this.crop_pct=this.config.crop_pct??224/256}async resize(u){let l=this.size?.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){let p=Math.floor(l/this.crop_pct),[w,f]=this.get_resize_output_image_size(u,{shortest_edge:p});u=await u.resize(w,f,{resample:this.resample}),u=await u.center_crop(l,l)}else u=await u.resize(l,l,{resample:this.resample});return u}}class a extends o{}},"./src/models/dac/feature_extraction_dac.js":(d,t,e)=>{e.r(t),e.d(t,{DacFeatureExtractor:()=>o});var r=e("./src/models/encodec/feature_extraction_encodec.js");class o extends r.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(d,t,e)=>{e.r(t),e.d(t,{DeiTFeatureExtractor:()=>a,DeiTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/detr/image_processing_detr.js":(d,t,e)=>{e.r(t),e.d(t,{DetrFeatureExtractor:()=>h,DetrImageProcessor:()=>a});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");class a extends r.ImageProcessor{async _call(l){let p=await super._call(l),w=[p.pixel_values.dims[0],64,64],f=(0,o.full)(w,1n);return{...p,pixel_mask:f}}post_process_object_detection(...l){return(0,r.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,r.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,r.post_process_instance_segmentation)(...l)}}class h extends a{}},"./src/models/dinov3_vit/image_processing_dinov3_vit.js":(d,t,e)=>{e.r(t),e.d(t,{DINOv3ViTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/donut/image_processing_donut.js":(d,t,e)=>{e.r(t),e.d(t,{DonutFeatureExtractor:()=>a,DonutImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{pad_image(u,l,p,w={}){let[f,i,y]=l,E=this.image_mean;Array.isArray(this.image_mean)||(E=new Array(y).fill(E));let S=this.image_std;Array.isArray(S)||(S=new Array(y).fill(E));let z=E.map((k,A)=>-k/S[A]);return super.pad_image(u,l,p,{center:!0,constant_values:z,...w})}}class a extends o{}},"./src/models/dpt/image_processing_dpt.js":(d,t,e)=>{e.r(t),e.d(t,{DPTFeatureExtractor:()=>a,DPTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(d,t,e)=>{e.r(t),e.d(t,{EfficientNetImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{constructor(h){super(h),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(u=>u*u))}}},"./src/models/encodec/feature_extraction_encodec.js":(d,t,e)=>{e.r(t),e.d(t,{EncodecFeatureExtractor:()=>a});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js");class a extends r.FeatureExtractor{async _call(u){(0,r.validate_audio_inputs)(u,"EncodecFeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));let l=this.config.feature_size;if(u.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);let p=[1,l,u.length/l];return{input_values:new o.Tensor("float32",u,p)}}}},"./src/models/feature_extractors.js":(d,t,e)=>{e.r(t),e.d(t,{ASTFeatureExtractor:()=>r.ASTFeatureExtractor,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,DacFeatureExtractor:()=>h.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>u.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>k.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,ParakeetFeatureExtractor:()=>p.ParakeetFeatureExtractor,PyAnnoteFeatureExtractor:()=>w.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>f.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>i.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>E.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>S.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>z.WhisperFeatureExtractor});var r=e("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=e("./src/models/encodec/feature_extraction_encodec.js"),a=e("./src/models/clap/feature_extraction_clap.js"),h=e("./src/models/dac/feature_extraction_dac.js"),u=e("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=e("./src/models/moonshine/feature_extraction_moonshine.js"),p=e("./src/models/parakeet/feature_extraction_parakeet.js"),w=e("./src/models/pyannote/feature_extraction_pyannote.js"),f=e("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),i=e("./src/models/snac/feature_extraction_snac.js"),y=e("./src/models/speecht5/feature_extraction_speecht5.js"),E=e("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),S=e("./src/models/wespeaker/feature_extraction_wespeaker.js"),z=e("./src/models/whisper/feature_extraction_whisper.js"),k=e("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(d,t,e)=>{e.r(t),e.d(t,{Florence2Processor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");class h extends r.Processor{constructor(l,p,w){super(l,p,w);let{tasks_answer_post_processing_type:f,task_prompts_without_inputs:i,task_prompts_with_input:y}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(f??{})),this.task_prompts_without_inputs=new Map(Object.entries(i??{})),this.task_prompts_with_input=new Map(Object.entries(y??{})),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(l){typeof l=="string"&&(l=[l]);let p=[];for(let w of l)if(this.task_prompts_without_inputs.has(w))p.push(this.task_prompts_without_inputs.get(w));else{for(let[f,i]of this.task_prompts_with_input)if(w.includes(f)){p.push(i.replaceAll("{input}",w).replaceAll(f,""));break}p.length!==l.length&&p.push(w)}return p}post_process_generation(l,p,w){let f=this.tasks_answer_post_processing_type.get(p)??"pure_text";l=l.replaceAll("<s>","").replaceAll("</s>","");let i;switch(f){case"pure_text":i=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let y=f==="ocr"?"quad_boxes":"bboxes",E=l.matchAll(this.regexes[y]),S=[],z=[];for(let[k,A,...N]of E)S.push(A?A.trim():S.at(-1)??""),z.push(N.map((x,P)=>(Number(x)+.5)/this.size_per_bin*w[P%2]));i={labels:S,[y]:z};break;default:throw new Error(`Task "${p}" (of type "${f}") not yet implemented.`)}return{[p]:i}}async _call(l,p=null,w={}){if(!l&&!p)throw new Error("Either text or images must be provided");let f=await this.image_processor(l,w),i=p?this.tokenizer(this.construct_prompts(p),w):{};return{...f,...i}}}v(h,"tokenizer_class",a.AutoTokenizer),v(h,"image_processor_class",o.AutoImageProcessor)},"./src/models/gemma3n/feature_extraction_gemma3n.js":(d,t,e)=>{e.r(t),e.d(t,{Gemma3nAudioFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");class h extends r.FeatureExtractor{constructor(l){super(l);let{fft_length:p,feature_size:w,min_frequency:f,max_frequency:i,sampling_rate:y,frame_length:E}=this.config,S=(0,a.mel_filter_bank)(Math.floor(1+p/2),w,f,i,y,null,"htk",!1);this.mel_filters=S,this.window=(0,a.window_function)(E,"hann")}async _extract_fbank_features(l,p){return(0,a.spectrogram)(l,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(l,{max_length:p=48e4,truncation:w=!0,padding:f=!0,pad_to_multiple_of:i=128}={}){if((0,r.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),w&&l.length>p&&(l=l.slice(0,p)),f&&l.length%i!==0){let S=i-l.length%i,z=new Float64Array(l.length+S);z.set(l),this.config.padding_value!==0&&z.fill(this.config.padding_value,l.length),l=z}let y=await this._extract_fbank_features(l,this.config.max_length),E=(0,o.full)([1,y.dims[0]],!0);return{input_features:y.unsqueeze_(0),input_features_mask:E}}}},"./src/models/gemma3n/processing_gemma3n.js":(d,t,e)=>{e.r(t),e.d(t,{Gemma3nProcessor:()=>p});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/models/auto/feature_extraction_auto.js"),h=e("./src/tokenizers.js"),u=e("./src/utils/image.js"),l=e("./src/utils/audio.js");class p extends r.Processor{constructor(f,i,y){super(f,i,y),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:E,boa_token:S,audio_token:z,eoa_token:k,image_token_id:A,boi_token:N,image_token:x,eoi_token:P}=this.tokenizer.config;this.audio_token_id=E,this.boa_token=S,this.audio_token=z;let D=z.repeat(this.audio_seq_length);this.full_audio_sequence=`
12
-
13
- ${S}${D}${k}
14
-
15
- `,this.image_token_id=A,this.boi_token=N,this.image_token=x;let _=x.repeat(this.image_seq_length);this.full_image_sequence=`
16
-
17
- ${N}${_}${P}
18
-
19
- `}async _call(f,i=null,y=null,E={}){typeof f=="string"&&(f=[f]);let S;y&&(S=await this.feature_extractor(y,E),f=f.map(A=>A.replaceAll(this.audio_token,this.full_audio_sequence)));let z;return i&&(z=await this.image_processor(i,E),f=f.map(A=>A.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(f,E),...z,...S}}}v(p,"image_processor_class",o.AutoImageProcessor),v(p,"feature_extractor_class",a.AutoFeatureExtractor),v(p,"tokenizer_class",h.AutoTokenizer),v(p,"uses_processor_config",!0),v(p,"uses_chat_template_file",!0)},"./src/models/glpn/image_processing_glpn.js":(d,t,e)=>{e.r(t),e.d(t,{GLPNFeatureExtractor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(d,t,e)=>{e.r(t),e.d(t,{GroundingDinoImageProcessor:()=>a});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");class a extends r.ImageProcessor{async _call(u){let l=await super._call(u),p=l.pixel_values.dims,w=(0,o.ones)([p[0],p[2],p[3]]);return{...l,pixel_mask:w}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(d,t,e)=>{e.r(t),e.d(t,{GroundingDinoProcessor:()=>l});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/base/image_processors_utils.js");function u(p,w){let i=p.dims.at(-1)-1,y=p.tolist();y.fill(!1,0,1),y.fill(!1,i);let E=w.tolist();return y.map((S,z)=>S?z:null).filter(S=>S!==null).map(S=>E[S])}class l extends r.Processor{async _call(w,f,i={}){let y=w?await this.image_processor(w,i):{};return{...f?this.tokenizer(f,i):{},...y}}post_process_grounded_object_detection(w,f,{box_threshold:i=.25,text_threshold:y=.25,target_sizes:E=null}={}){let{logits:S,pred_boxes:z}=w,k=S.dims[0];if(E!==null&&E.length!==k)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let A=S.dims.at(1),N=S.sigmoid(),x=N.max(-1).tolist(),P=z.tolist().map(_=>_.map(M=>(0,h.center_to_corners_format)(M))),D=[];for(let _=0;_<k;++_){let M=E!==null?E[_]:null;M!==null&&(P[_]=P[_].map(B=>B.map((Q,$)=>Q*M[($+1)%2])));let I=x[_],O=[],G=[],U=[];for(let B=0;B<A;++B){let Q=I[B];if(Q<=i)continue;let $=P[_][B],Y=N[_][B];O.push(Q),U.push($);let se=u(Y.gt(y),f[_]);G.push(se)}D.push({scores:O,boxes:U,labels:this.batch_decode(G)})}return D}}v(l,"tokenizer_class",a.AutoTokenizer),v(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/idefics3/image_processing_idefics3.js":(d,t,e)=>{e.r(t),e.d(t,{Idefics3ImageProcessor:()=>a});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");class a extends r.ImageProcessor{constructor(u){super(u),this.do_image_splitting=u.do_image_splitting??!0,this.max_image_size=u.max_image_size}get_resize_for_vision_encoder(u,l){let[p,w]=u.dims.slice(-2),f=w/p;return w>=p?(w=Math.ceil(w/l)*l,p=Math.floor(w/f),p=Math.ceil(p/l)*l):(p=Math.ceil(p/l)*l,w=Math.floor(p*f),w=Math.ceil(w/l)*l),{height:p,width:w}}async _call(u,{do_image_splitting:l=null,return_row_col_info:p=!1}={}){let w;if(!Array.isArray(u))w=[[u]];else{if(u.length===0||!u[0])throw new Error("No images provided.");Array.isArray(u[0])?w=u:w=[u]}let f=[],i=[],y=[],E=[],S=[];for(let _ of w){let M=await Promise.all(_.map(G=>this.preprocess(G)));E.push(...M.map(G=>G.original_size)),S.push(...M.map(G=>G.reshaped_input_size)),M.forEach(G=>G.pixel_values.unsqueeze_(0));let{longest_edge:I}=this.max_image_size,O;if(l??this.do_image_splitting){let G=new Array(M.length),U=new Array(M.length);O=await Promise.all(M.map(async(B,Q)=>{let $=this.get_resize_for_vision_encoder(B.pixel_values,I),Y=await(0,o.interpolate_4d)(B.pixel_values,{size:[$.height,$.width]}),{frames:se,num_splits_h:oe,num_splits_w:ue}=await this.split_image(Y,this.max_image_size);return G[Q]=oe,U[Q]=ue,(0,o.cat)(se,0)})),i.push(G),y.push(U)}else{let G=[I,I];O=await Promise.all(M.map(U=>(0,o.interpolate_4d)(U.pixel_values,{size:G}))),i.push(new Array(M.length).fill(0)),y.push(new Array(M.length).fill(0))}f.push((0,o.cat)(O,0))}let z=f.length,[k,A,N,x]=f[0].dims,P,D;if(z===1)P=f[0].unsqueeze_(0),D=(0,o.full)([z,k,N,x],!0);else{let _=Math.max(...f.map(O=>O.dims.at(0)));D=(0,o.full)([z,_,N,x],!0);let M=D.data,I=_*N*x;for(let O=0;O<z;++O){let G=f[O].dims[0];if(G<_){f[O]=(0,o.cat)([f[O],(0,o.full)([_-G,A,N,x],0)],0);let U=O*I+G*N*x,B=(O+1)*I;M.fill(!1,U,B)}}P=(0,o.stack)(f,0)}return{pixel_values:P,pixel_attention_mask:D,original_sizes:E,reshaped_input_sizes:S,...p?{rows:i,cols:y}:{}}}async split_image(u,{longest_edge:l}){let p=l,w=l,f=[],[i,y]=u.dims.slice(-2),E=0,S=0;if(i>p||y>w){E=Math.ceil(i/p),S=Math.ceil(y/w);let z=Math.ceil(i/E),k=Math.ceil(y/S);for(let x=0;x<E;++x)for(let P=0;P<S;++P){let D,_,M,I;x===E-1?(_=i-z,I=i):(_=x*z,I=(x+1)*z),P===S-1?(D=y-k,M=y):(D=P*k,M=(P+1)*k);let O=[_,D],G=[I,M],U=await(0,o.slice)(u,O,G,[2,3]);f.push(U)}let A=p,N=w;(i!==A||y!==N)&&(u=await(0,o.interpolate_4d)(u,{size:[A,N]}))}return f.push(u),{frames:f,num_splits_h:E,num_splits_w:S}}}},"./src/models/idefics3/processing_idefics3.js":(d,t,e)=>{e.r(t),e.d(t,{Idefics3Processor:()=>f});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/utils/image.js"),u=e("./src/utils/core.js");function l(i,y,E,S,z,k){let A="";for(let N=0;N<y;++N){for(let x=0;x<E;++x)A+=S+`<row_${N+1}_col_${x+1}>`+z.repeat(i);A+=`
20
- `}return A+=`
21
- ${S}${k}`+z.repeat(i)+`${S}`,A}function p(i,y,E,S){return`${y}${S}`+E.repeat(i)+`${y}`}function w(i,y,E,S,z,k){return i===0&&y===0?p(E,S,z,k):l(E,i,y,S,z,k)}class f extends r.Processor{constructor(){super(...arguments);v(this,"fake_image_token","<fake_token_around_image>");v(this,"image_token","<image>");v(this,"global_img_token","<global-img>")}async _call(E,S=null,z={}){z.return_row_col_info??(z.return_row_col_info=!0);let k;S&&(k=await this.image_processor(S,z)),Array.isArray(E)||(E=[E]);let A=k.rows??[new Array(E.length).fill(0)],N=k.cols??[new Array(E.length).fill(0)],x=this.config.image_seq_len,P=[],D=[];for(let M=0;M<E.length;++M){let I=E[M],O=A[M],G=N[M];P.push((0,u.count)(I,this.image_token));let U=O.map(($,Y)=>w($,G[Y],x,this.fake_image_token,this.image_token,this.global_img_token)),B=I.split(this.image_token);if(B.length===0)throw new Error("The image token should be present in the text.");let Q=B[0];for(let $=0;$<U.length;++$)Q+=U[$]+B[$+1];D.push(Q)}return{...this.tokenizer(D),...k}}}v(f,"image_processor_class",o.AutoImageProcessor),v(f,"tokenizer_class",a.AutoTokenizer),v(f,"uses_processor_config",!0)},"./src/models/image_processors.js":(d,t,e)=>{e.r(t),e.d(t,{BeitFeatureExtractor:()=>r.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>h.CLIPFeatureExtractor,CLIPImageProcessor:()=>h.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>a.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>u.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>u.ConvNextImageProcessor,DINOv3ViTImageProcessor:()=>w.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>i.DPTFeatureExtractor,DPTImageProcessor:()=>i.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>p.DetrFeatureExtractor,DetrImageProcessor:()=>p.DetrImageProcessor,DonutFeatureExtractor:()=>f.DonutFeatureExtractor,DonutImageProcessor:()=>f.DonutImageProcessor,EfficientNetImageProcessor:()=>y.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>E.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>S.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>z.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>A.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>N.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>x.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>P.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>P.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>D.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>D.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>M.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>M.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>I.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>I.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,NougatImageProcessor:()=>G.NougatImageProcessor,OwlViTFeatureExtractor:()=>B.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>B.OwlViTImageProcessor,Owlv2ImageProcessor:()=>U.Owlv2ImageProcessor,Phi3VImageProcessor:()=>Q.Phi3VImageProcessor,PixtralImageProcessor:()=>$.PixtralImageProcessor,PvtImageProcessor:()=>Y.PvtImageProcessor,Qwen2VLImageProcessor:()=>se.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>oe.RTDetrImageProcessor,Sam2ImageProcessor:()=>be.Sam2ImageProcessor,Sam3ImageProcessor:()=>pe.Sam3ImageProcessor,SamImageProcessor:()=>ue.SamImageProcessor,SegformerFeatureExtractor:()=>J.SegformerFeatureExtractor,SegformerImageProcessor:()=>J.SegformerImageProcessor,SiglipImageProcessor:()=>F.SiglipImageProcessor,SmolVLMImageProcessor:()=>K.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>Z.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>ie.ViTFeatureExtractor,ViTImageProcessor:()=>ie.ViTImageProcessor,VitMatteImageProcessor:()=>xe.VitMatteImageProcessor,VitPoseImageProcessor:()=>ye.VitPoseImageProcessor,YolosFeatureExtractor:()=>Oe.YolosFeatureExtractor,YolosImageProcessor:()=>Oe.YolosImageProcessor});var r=e("./src/models/beit/image_processing_beit.js"),o=e("./src/models/bit/image_processing_bit.js"),a=e("./src/models/chinese_clip/image_processing_chinese_clip.js"),h=e("./src/models/clip/image_processing_clip.js"),u=e("./src/models/convnext/image_processing_convnext.js"),l=e("./src/models/deit/image_processing_deit.js"),p=e("./src/models/detr/image_processing_detr.js"),w=e("./src/models/dinov3_vit/image_processing_dinov3_vit.js"),f=e("./src/models/donut/image_processing_donut.js"),i=e("./src/models/dpt/image_processing_dpt.js"),y=e("./src/models/efficientnet/image_processing_efficientnet.js"),E=e("./src/models/glpn/image_processing_glpn.js"),S=e("./src/models/grounding_dino/image_processing_grounding_dino.js"),z=e("./src/models/idefics3/image_processing_idefics3.js"),k=e("./src/models/janus/image_processing_janus.js"),A=e("./src/models/jina_clip/image_processing_jina_clip.js"),N=e("./src/models/llava_onevision/image_processing_llava_onevision.js"),x=e("./src/models/mask2former/image_processing_mask2former.js"),P=e("./src/models/maskformer/image_processing_maskformer.js"),D=e("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),_=e("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),M=e("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),I=e("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),O=e("./src/models/mobilevit/image_processing_mobilevit.js"),G=e("./src/models/nougat/image_processing_nougat.js"),U=e("./src/models/owlv2/image_processing_owlv2.js"),B=e("./src/models/owlvit/image_processing_owlvit.js"),Q=e("./src/models/phi3_v/image_processing_phi3_v.js"),$=e("./src/models/pixtral/image_processing_pixtral.js"),Y=e("./src/models/pvt/image_processing_pvt.js"),se=e("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),oe=e("./src/models/rt_detr/image_processing_rt_detr.js"),ue=e("./src/models/sam/image_processing_sam.js"),be=e("./src/models/sam2/image_processing_sam2.js"),pe=e("./src/models/sam3/image_processing_sam3.js"),J=e("./src/models/segformer/image_processing_segformer.js"),F=e("./src/models/siglip/image_processing_siglip.js"),K=e("./src/models/smolvlm/image_processing_smolvlm.js"),Z=e("./src/models/swin2sr/image_processing_swin2sr.js"),ie=e("./src/models/vit/image_processing_vit.js"),xe=e("./src/models/vitmatte/image_processing_vitmatte.js"),ye=e("./src/models/vitpose/image_processing_vitpose.js"),Oe=e("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(d,t,e)=>{e.r(t),e.d(t,{VLMImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{constructor(h){super({do_pad:!0,pad_size:{width:h.image_size,height:h.image_size},...h}),this.constant_values=this.config.background_color.map(u=>u*this.rescale_factor)}pad_image(h,u,l,p){return super.pad_image(h,u,l,{constant_values:this.constant_values,center:!0,...p})}}},"./src/models/janus/processing_janus.js":(d,t,e)=>{e.r(t),e.d(t,{VLChatProcessor:()=>p});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/utils/core.js"),u=e("./src/utils/tensor.js"),l=e("./src/utils/image.js");class p extends r.Processor{constructor(f,i,y){super(f,i,y),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(f,{images:i=null,chat_template:y="default"}={}){i?Array.isArray(i)||(i=[i]):i=await Promise.all(f.filter(O=>O.images).flatMap(O=>O.images).map(O=>l.RawImage.read(O)));let E=this.tokenizer,S=E.apply_chat_template(f,{tokenize:!1,add_generation_prompt:!0,chat_template:y}),z=O=>E.encode(O,{add_special_tokens:!1}),k=S.split(this.image_tag),A=k.length-1;if(i.length!==A)throw new Error(`Number of images provided (${i.length}) does not match number of "${this.image_tag}" image tags (${A})`);let[N,x,P]=E.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),D=z(k[0]),_=new Array(D.length).fill(!1);for(let O=1;O<k.length;++O){let G=new Array(this.num_image_tokens).fill(N),U=z(k[O]);D=(0,h.mergeArrays)(D,[x],G,[P],U);let B=new Array(this.num_image_tokens).fill(!0);_=(0,h.mergeArrays)(_,[!1],B,[!1],new Array(U.length).fill(!1))}let M=[1,D.length],I={input_ids:new u.Tensor("int64",D,M),attention_mask:new u.Tensor("int64",new Array(D.length).fill(1),M),images_seq_mask:new u.Tensor("bool",_,M),images_emb_mask:new u.Tensor("bool",new Array(A*this.num_image_tokens).fill(!0),[1,A,this.num_image_tokens])};if(i&&i.length>0){let O=await this.image_processor(i);return O.pixel_values.unsqueeze_(0),{...I,...O}}return I}}v(p,"image_processor_class",o.AutoImageProcessor),v(p,"tokenizer_class",a.AutoTokenizer),v(p,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(d,t,e)=>{e.r(t),e.d(t,{JinaCLIPImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{constructor(h){let{resize_mode:u,fill_color:l,interpolation:p,size:w,...f}=h,i=u==="squash"?{width:w,height:w}:u==="shortest"?{shortest_edge:w}:{longest_edge:w},y=p==="bicubic"?3:2;super({...f,size:i,resample:y,do_center_crop:!0,crop_size:w,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(d,t,e)=>{e.r(t),e.d(t,{JinaCLIPProcessor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");class h extends r.Processor{async _call(l=null,p=null,w={}){if(!l&&!p)throw new Error("Either text or images must be provided");let f=l?this.tokenizer(l,w):{},i=p?await this.image_processor(p,w):{};return{...f,...i}}}v(h,"tokenizer_class",a.AutoTokenizer),v(h,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava/processing_llava.js":(d,t,e)=>{e.r(t),e.d(t,{LlavaProcessor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");class h extends r.Processor{async _call(l,p=null,w={}){let f=await this.image_processor(l,w);if(p){let[y,E]=f.pixel_values.dims.slice(-2),{image_token:S,patch_size:z,num_additional_image_tokens:k}=this.config,A=Math.floor(y/z)*Math.floor(E/z)+k;p=structuredClone(p),Array.isArray(p)||(p=[p]);for(let N=0;N<p.length;++N)p[N]=p[N].replace(S,S.repeat(A))}let i=p?this.tokenizer(p,w):{};return{...f,...i}}}v(h,"tokenizer_class",a.AutoTokenizer),v(h,"image_processor_class",o.AutoImageProcessor),v(h,"uses_processor_config",!0)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(d,t,e)=>{e.r(t),e.d(t,{LlavaOnevisionImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(d,t,e)=>{e.r(t),e.d(t,{Mask2FormerImageProcessor:()=>o});var r=e("./src/models/maskformer/image_processing_maskformer.js");class o extends r.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(d,t,e)=>{e.r(t),e.d(t,{MaskFormerFeatureExtractor:()=>a,MaskFormerImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_panoptic_segmentation(...u){return(0,r.post_process_panoptic_segmentation)(...u)}post_process_instance_segmentation(...u){return(0,r.post_process_instance_segmentation)(...u)}}class a extends o{}},"./src/models/mgp_str/processing_mgp_str.js":(d,t,e)=>{e.r(t),e.d(t,{MgpstrProcessor:()=>l});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/utils/maths.js");let u={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends r.Processor{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(w,f){if(!u.hasOwnProperty(f))throw new Error(`Format ${f} is not supported.`);let[i,y]=u[f],E=this[i].bind(this),[S,z]=w.dims,k=[],A=[],N=w.tolist();for(let P=0;P<S;++P){let D=N[P],_=[],M=[];for(let O=1;O<z;++O){let[G,U]=(0,h.max)((0,h.softmax)(D[O]));if(M.push(G),U==y)break;_.push(U)}let I=M.length>0?M.reduce((O,G)=>O*G,1):0;A.push(_),k.push(I)}return[E(A),k]}char_decode(w){return this.char_tokenizer.batch_decode(w).map(f=>f.replaceAll(" ",""))}bpe_decode(w){return this.bpe_tokenizer.batch_decode(w)}wp_decode(w){return this.wp_tokenizer.batch_decode(w).map(f=>f.replaceAll(" ",""))}batch_decode([w,f,i]){let[y,E]=this._decode_helper(w,"char"),[S,z]=this._decode_helper(f,"bpe"),[k,A]=this._decode_helper(i,"wp"),N=[],x=[];for(let P=0;P<y.length;++P){let[D,_]=(0,h.max)([E[P],z[P],A[P]]);N.push([y[P],S[P],k[P]][_]),x.push(D)}return{generated_text:N,scores:x,char_preds:y,bpe_preds:S,wp_preds:k}}static async from_pretrained(...w){let f=await super.from_pretrained(...w),i=await a.AutoTokenizer.from_pretrained("Xenova/gpt2"),y=await a.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return f.components={image_processor:f.image_processor,char_tokenizer:f.tokenizer,bpe_tokenizer:i,wp_tokenizer:y},f}async _call(w,f=null){let i=await this.image_processor(w);return f&&(i.labels=this.tokenizer(f).input_ids),i}}v(l,"tokenizer_class",a.AutoTokenizer),v(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(d,t,e)=>{e.r(t),e.d(t,{MobileNetV1FeatureExtractor:()=>a,MobileNetV1ImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(d,t,e)=>{e.r(t),e.d(t,{MobileNetV2FeatureExtractor:()=>a,MobileNetV2ImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(d,t,e)=>{e.r(t),e.d(t,{MobileNetV3FeatureExtractor:()=>a,MobileNetV3ImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(d,t,e)=>{e.r(t),e.d(t,{MobileNetV4FeatureExtractor:()=>a,MobileNetV4ImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(d,t,e)=>{e.r(t),e.d(t,{MobileViTFeatureExtractor:()=>a,MobileViTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/moonshine/feature_extraction_moonshine.js":(d,t,e)=>{e.r(t),e.d(t,{MoonshineFeatureExtractor:()=>a});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js");class a extends r.FeatureExtractor{async _call(u){(0,r.validate_audio_inputs)(u,"MoonshineFeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));let l=[1,u.length];return{input_values:new o.Tensor("float32",u,l)}}}},"./src/models/moonshine/processing_moonshine.js":(d,t,e)=>{e.r(t),e.d(t,{MoonshineProcessor:()=>h});var r=e("./src/models/auto/feature_extraction_auto.js"),o=e("./src/tokenizers.js"),a=e("./src/base/processing_utils.js");class h extends a.Processor{async _call(l){return await this.feature_extractor(l)}}v(h,"tokenizer_class",o.AutoTokenizer),v(h,"feature_extractor_class",r.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(d,t,e)=>{e.r(t),e.d(t,{NougatImageProcessor:()=>o});var r=e("./src/models/donut/image_processing_donut.js");class o extends r.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(d,t,e)=>{e.r(t),e.d(t,{Owlv2ImageProcessor:()=>o});var r=e("./src/models/owlvit/image_processing_owlvit.js");class o extends r.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(d,t,e)=>{e.r(t),e.d(t,{OwlViTFeatureExtractor:()=>a,OwlViTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_object_detection(...u){return(0,r.post_process_object_detection)(...u)}}class a extends o{}},"./src/models/owlvit/processing_owlvit.js":(d,t,e)=>{e.r(t),e.d(t,{OwlViTProcessor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");class h extends r.Processor{}v(h,"tokenizer_class",a.AutoTokenizer),v(h,"image_processor_class",o.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(d,t,e)=>{e.r(t),e.d(t,{PaliGemmaProcessor:()=>l});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");let h="<image>";function u(p,w,f,i,y){return`${i.repeat(f*y)}${w}${p}
22
- `}class l extends r.Processor{async _call(w,f=null,i={}){f||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),f=""),Array.isArray(w)||(w=[w]),Array.isArray(f)||(f=[f]);let y=this.tokenizer.bos_token,E=this.image_processor.config.image_seq_length,S;f.some(A=>A.includes(h))?S=f.map(A=>{let N=A.replaceAll(h,h.repeat(E)),x=N.lastIndexOf(h),P=x===-1?0:x+h.length;return N.slice(0,P)+y+N.slice(P)+`
23
- `}):(console.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."),S=f.map(A=>u(A,y,E,h,w.length)));let z=this.tokenizer(S,i);return{...await this.image_processor(w,i),...z}}}v(l,"tokenizer_class",a.AutoTokenizer),v(l,"image_processor_class",o.AutoImageProcessor),v(l,"uses_processor_config",!1)},"./src/models/parakeet/feature_extraction_parakeet.js":(d,t,e)=>{e.r(t),e.d(t,{ParakeetFeatureExtractor:()=>u});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");let h=1e-5;class u extends r.FeatureExtractor{constructor(p){var i;super(p),(i=this.config).mel_filters??(i.mel_filters=(0,a.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));let w=(0,a.window_function)(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let f=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(w,f)}async _extract_fbank_features(p){let w=this.config.preemphasis;p=new Float64Array(p);for(let i=p.length-1;i>=1;--i)p[i]-=w*p[i-1];return await(0,a.spectrogram)(p,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(p){(0,r.validate_audio_inputs)(p,"ParakeetFeatureExtractor");let w=await this._extract_fbank_features(p),f=Math.floor((p.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),i=w.data;i.fill(0,f*w.dims[1]);let[y,E]=w.dims,S=new Float64Array(E),z=new Float64Array(E);for(let N=0;N<f;++N){let x=N*E;for(let P=0;P<E;++P){let D=i[x+P];S[P]+=D,z[P]+=D*D}}let k=f>1?f-1:1;for(let N=0;N<E;++N){let x=S[N]/f,P=(z[N]-f*x*x)/k,_=1/(Math.sqrt(P)+h);for(let M=0;M<f;++M){let I=M*E+N;i[I]=(i[I]-x)*_}}let A=new BigInt64Array(y);return A.fill(1n,0,f),{input_features:w.unsqueeze_(0),attention_mask:new o.Tensor("int64",A,[1,y])}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(d,t,e)=>{e.r(t),e.d(t,{Phi3VImageProcessor:()=>w});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");let a=336,h=[2,3],{ceil:u,floor:l,sqrt:p}=Math;class w extends r.ImageProcessor{constructor(i){super({...i,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=i.num_crops}calc_num_image_tokens_from_image_size(i,y){let{num_img_tokens:E}=this.config;return l((l(y/a)*l(i/a)+1)*E+1+(l(y/a)+1)*p(E))}get_resize_output_image_size(i,y){let E=this._num_crops,[S,z]=i.size,k=S/z,A=1;for(;A*Math.ceil(A/k)<=E;)A+=1;A-=1;let N=Math.floor(A*336),x=Math.floor(N/k);return[N,x]}pad_image(i,y,E,S={}){let[z,k]=y,A=a*u(z/a),N=a*u(k/a),x=[1,1,1].map((P,D)=>(P-this.image_mean[D])/this.image_std[D]);return super.pad_image(i,y,{width:N,height:A},{center:!0,constant_values:x,...S})}async _call(i,{num_crops:y=null}={}){if(this._num_crops=y??(y=this.config.num_crops),y<4||p(y)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(i)||(i=[i]);let E=i.length,S=await Promise.all(i.map(_=>this.preprocess(_))),z=S.map(_=>_.original_size),k=S.map(_=>_.reshaped_input_size),A=[];for(let{pixel_values:_}of S){_.unsqueeze_(0);let[M,I]=_.dims.slice(-2),O=await(0,o.interpolate_4d)(_,{size:[a,a],mode:"bicubic"});if(y>0){let G=[],U=p(y),B=l(I/U),Q=l(M/U);for(let Y=0;Y<U;++Y)for(let se=0;se<U;++se){let oe,ue,be,pe;Y===U-1?(ue=M-Q,pe=M):(ue=Y*Q,pe=(Y+1)*Q),se===U-1?(oe=I-B,be=I):(oe=se*B,be=(se+1)*B);let J=[ue,oe],F=[pe,be],K=await(0,o.slice)(_,J,F,h);G.push(K)}let $=await(0,o.interpolate_4d)((0,o.cat)(G,0),{size:[a,a],mode:"bicubic"});A.push((0,o.cat)([O,$],0))}else A.push(O)}let N=(0,o.stack)(A,0),x=k.map(_=>_.map(M=>a*u(M/a))),P=new o.Tensor("int64",x.flat(),[E,2]),D=x.map(([_,M])=>this.calc_num_image_tokens_from_image_size(M,_));return{pixel_values:N,original_sizes:z,reshaped_input_sizes:k,image_sizes:P,num_img_tokens:D}}}},"./src/models/phi3_v/processing_phi3_v.js":(d,t,e)=>{e.r(t),e.d(t,{Phi3VProcessor:()=>p});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/utils/image.js");let u="<|image|>",l=/<\|image_\d+\|>/g;class p extends r.Processor{async _call(f,i=null,{padding:y=!0,truncation:E=!0,num_crops:S=null}={}){Array.isArray(f)||(f=[f]);let z,k;if(i){k=await this.image_processor(i,{num_crops:S});let{num_img_tokens:A}=k,N=f.map((P,D)=>P.split(l).join(u.repeat(A[D])));z=this.tokenizer(N,{padding:y,truncation:E});let x=this.tokenizer.model.convert_tokens_to_ids([u])[0];z.input_ids.map_(P=>P==x?-P:P)}else z=this.tokenizer(f);return{...z,...k}}}v(p,"image_processor_class",o.AutoImageProcessor),v(p,"tokenizer_class",a.AutoTokenizer)},"./src/models/pixtral/image_processing_pixtral.js":(d,t,e)=>{e.r(t),e.d(t,{PixtralImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{get_resize_output_image_size(h,u){let{longest_edge:l}=u;if(l===void 0)throw new Error("size must contain 'longest_edge'");let[p,w]=h.size,f=Math.max(p,w)/l,i=p,y=w;f>1&&(i=Math.floor(p/f),y=Math.floor(w/f));let{patch_size:E,spatial_merge_size:S}=this.config;if(!S)throw new Error("config must contain 'spatial_merge_size'");let z=E*S,k=Math.floor((i-1)/z)+1,A=Math.floor((y-1)/z)+1;return[k*z,A*z]}}},"./src/models/pixtral/processing_pixtral.js":(d,t,e)=>{e.r(t),e.d(t,{PixtralProcessor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js");class h extends r.Processor{async _call(l,p=null,w={}){let f=await this.image_processor(l,w);if(p){let[y,E]=f.pixel_values.dims.slice(-2),{image_token:S,image_break_token:z,image_end_token:k,patch_size:A,spatial_merge_size:N}=this.config,x=A*N,P=Math.floor(y/x),D=Math.floor(E/x);p=structuredClone(p),Array.isArray(p)||(p=[p]);for(let _=0;_<p.length;++_){let M=S.repeat(D),I=M+z,O=M+k,G=I.repeat(P-1)+O;p[_]=p[_].replace(S,G)}}let i=p?this.tokenizer(p,w):{};return{...f,...i}}}v(h,"tokenizer_class",a.AutoTokenizer),v(h,"image_processor_class",o.AutoImageProcessor),v(h,"uses_processor_config",!0)},"./src/models/processors.js":(d,t,e)=>{e.r(t),e.d(t,{Florence2Processor:()=>r.Florence2Processor,Gemma3nProcessor:()=>o.Gemma3nProcessor,GroundingDinoProcessor:()=>a.GroundingDinoProcessor,Idefics3Processor:()=>h.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>p.LlavaProcessor,MgpstrProcessor:()=>w.MgpstrProcessor,MoonshineProcessor:()=>f.MoonshineProcessor,OwlViTProcessor:()=>i.OwlViTProcessor,PaliGemmaProcessor:()=>y.PaliGemmaProcessor,Phi3VProcessor:()=>E.Phi3VProcessor,PixtralProcessor:()=>S.PixtralProcessor,PyAnnoteProcessor:()=>z.PyAnnoteProcessor,Qwen2VLProcessor:()=>k.Qwen2VLProcessor,Sam2Processor:()=>N.Sam2Processor,Sam2VideoProcessor:()=>N.Sam2VideoProcessor,SamProcessor:()=>A.SamProcessor,SmolVLMProcessor:()=>x.SmolVLMProcessor,SpeechT5Processor:()=>P.SpeechT5Processor,UltravoxProcessor:()=>D.UltravoxProcessor,VLChatProcessor:()=>u.VLChatProcessor,VoxtralProcessor:()=>_.VoxtralProcessor,Wav2Vec2Processor:()=>M.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>I.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>O.WhisperProcessor});var r=e("./src/models/florence2/processing_florence2.js"),o=e("./src/models/gemma3n/processing_gemma3n.js"),a=e("./src/models/grounding_dino/processing_grounding_dino.js"),h=e("./src/models/idefics3/processing_idefics3.js"),u=e("./src/models/janus/processing_janus.js"),l=e("./src/models/jina_clip/processing_jina_clip.js"),p=e("./src/models/llava/processing_llava.js"),w=e("./src/models/mgp_str/processing_mgp_str.js"),f=e("./src/models/moonshine/processing_moonshine.js"),i=e("./src/models/owlvit/processing_owlvit.js"),y=e("./src/models/paligemma/processing_paligemma.js"),E=e("./src/models/phi3_v/processing_phi3_v.js"),S=e("./src/models/pixtral/processing_pixtral.js"),z=e("./src/models/pyannote/processing_pyannote.js"),k=e("./src/models/qwen2_vl/processing_qwen2_vl.js"),A=e("./src/models/sam/processing_sam.js"),N=e("./src/models/sam2/processing_sam2.js"),x=e("./src/models/smolvlm/processing_smolvlm.js"),P=e("./src/models/speecht5/processing_speecht5.js"),D=e("./src/models/ultravox/processing_ultravox.js"),_=e("./src/models/voxtral/processing_voxtral.js"),M=e("./src/models/wav2vec2/processing_wav2vec2.js"),I=e("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),O=e("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(d,t,e)=>{e.r(t),e.d(t,{PvtImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(d,t,e)=>{e.r(t),e.d(t,{PyAnnoteFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/maths.js");class h extends r.FeatureExtractor{async _call(l){(0,r.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));let p=[1,1,l.length];return{input_values:new o.Tensor("float32",l,p)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,p){let w=p/this.samples_to_frames(p)/this.config.sampling_rate,f=[];for(let i of l.tolist()){let y=[],E=-1;for(let S=0;S<i.length;++S){let z=(0,a.softmax)(i[S]),[k,A]=(0,a.max)(z),[N,x]=[S,S+1];A!==E?(E=A,y.push({id:A,start:N,end:x,score:k})):(y.at(-1).end=x,y.at(-1).score+=k)}f.push(y.map(({id:S,start:z,end:k,score:A})=>({id:S,start:z*w,end:k*w,confidence:A/(k-z)})))}return f}}},"./src/models/pyannote/processing_pyannote.js":(d,t,e)=>{e.r(t),e.d(t,{PyAnnoteProcessor:()=>a});var r=e("./src/base/processing_utils.js"),o=e("./src/models/pyannote/feature_extraction_pyannote.js");class a extends r.Processor{async _call(u){return await this.feature_extractor(u)}post_process_speaker_diarization(...u){return this.feature_extractor.post_process_speaker_diarization(...u)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}v(a,"feature_extractor_class",o.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(d,t,e)=>{e.r(t),e.d(t,{Qwen2VLImageProcessor:()=>a});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");class a extends r.ImageProcessor{async _call(u,...l){let{pixel_values:p,original_sizes:w,reshaped_input_sizes:f}=await super._call(u,...l),i=p,{temporal_patch_size:y,merge_size:E,patch_size:S}=this.config;i.dims[0]===1&&(i=(0,o.cat)(Array.from({length:y},()=>i),0));let z=i.dims[0]/y,k=i.dims[1],A=Math.floor(i.dims[2]/S),N=Math.floor(i.dims[3]/S),x=i.view(z,y,k,Math.floor(A/E),E,S,Math.floor(N/E),E,S).permute(0,3,6,4,7,2,1,5,8).view(z*A*N,k*y*S*S),P=new o.Tensor("int64",[z,A,N],[1,3]);return{pixel_values:x,image_grid_thw:P,original_sizes:w,reshaped_input_sizes:f}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(d,t,e)=>{e.r(t),e.d(t,{Qwen2VLProcessor:()=>u});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js"),a=e("./src/tokenizers.js"),h=e("./src/utils/image.js");class u extends r.Processor{async _call(p,w=null,...f){Array.isArray(p)||(p=[p]);let i,y;if(w&&(i=await this.image_processor(w),y=i.image_grid_thw),y){let S=this.image_processor.config.merge_size**2,z=0,k=y.tolist();p=p.map(A=>{for(;A.includes("<|image_pad|>");){let N=Number(k[z++].reduce((x,P)=>x*P,1n));A=A.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(N/S)))}return A.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(p),...i}}}v(u,"image_processor_class",o.AutoImageProcessor),v(u,"tokenizer_class",a.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(d,t,e)=>{e.r(t),e.d(t,{RTDetrImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_object_detection(...h){return(0,r.post_process_object_detection)(...h)}}},"./src/models/sam/image_processing_sam.js":(d,t,e)=>{e.r(t),e.d(t,{SamImageProcessor:()=>h});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/core.js"),a=e("./src/utils/tensor.js");class h extends r.ImageProcessor{reshape_input_points(l,p,w,f=!1){l=structuredClone(l);let i=(0,o.calculateDimensions)(l);if(i.length===3)f||(i=[1,...i]),l=[l];else if(i.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 y=0;y<l.length;++y){let[E,S]=p[y],[z,k]=w[y],A=[k/S,z/E];for(let N=0;N<l[y].length;++N)for(let x=0;x<l[y][N].length;++x)for(let P=0;P<l[y][N][x].length;++P)l[y][N][x][P]*=A[P%2]}return new a.Tensor("float32",Float32Array.from(l.flat(1/0)),i)}add_input_labels(l,p){let w=(0,o.calculateDimensions)(l);if(w.length===2)w=[1,...w],l=[l];else if(w.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(w.some((f,i)=>f!==p.dims[i]))throw Error(`The first ${w.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new a.Tensor("int64",l.flat(1/0).map(BigInt),w)}async _call(l,{input_points:p=null,input_labels:w=null,input_boxes:f=null}={}){let i=await super._call(l);if(p&&(i.input_points=this.reshape_input_points(p,i.original_sizes,i.reshaped_input_sizes)),w){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(w,i.input_points)}return f&&(i.input_boxes=this.reshape_input_points(f,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(l,p,w,{mask_threshold:f=0,binarize:i=!0,pad_size:y=null}={}){let E=[];y=y??this.pad_size??this.size;let S=[y.height,y.width];for(let z=0;z<p.length;++z){let k=p[z],A=w[z],N=await(0,a.interpolate_4d)(l[z],{mode:"bilinear",size:S});if(N=N.slice(null,null,[0,A[0]],[0,A[1]]),N=await(0,a.interpolate_4d)(N,{mode:"bilinear",size:k}),i){let x=N.data,P=new Uint8Array(x.length);for(let D=0;D<x.length;++D)x[D]>f&&(P[D]=1);N=new a.Tensor("bool",P,N.dims)}E.push(N)}return E}generate_crop_boxes(l,p,{crop_n_layers:w=0,overlap_ratio:f=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:y=1}={}){}}},"./src/models/sam/processing_sam.js":(d,t,e)=>{e.r(t),e.d(t,{SamProcessor:()=>a});var r=e("./src/base/processing_utils.js"),o=e("./src/models/auto/image_processing_auto.js");class a extends r.Processor{async _call(...u){return await this.image_processor(...u)}post_process_masks(...u){return this.image_processor.post_process_masks(...u)}reshape_input_points(...u){return this.image_processor.reshape_input_points(...u)}}v(a,"image_processor_class",o.AutoImageProcessor)},"./src/models/sam2/image_processing_sam2.js":(d,t,e)=>{e.r(t),e.d(t,{Sam2ImageProcessor:()=>r.SamImageProcessor});var r=e("./src/models/sam/image_processing_sam.js")},"./src/models/sam2/processing_sam2.js":(d,t,e)=>{e.r(t),e.d(t,{Sam2Processor:()=>o,Sam2VideoProcessor:()=>a});var r=e("./src/models/sam/processing_sam.js");class o extends r.SamProcessor{}class a extends o{}},"./src/models/sam3/image_processing_sam3.js":(d,t,e)=>{e.r(t),e.d(t,{Sam3ImageProcessor:()=>r.Sam2ImageProcessor});var r=e("./src/models/sam2/image_processing_sam2.js")},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(d,t,e)=>{e.r(t),e.d(t,{SeamlessM4TFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");class h extends r.FeatureExtractor{constructor(l){super(l);let p=this.config.sampling_rate,w=(0,a.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(p/2),p,null,"kaldi",!0);this.mel_filters=w,this.window=(0,a.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,p){return l=l.map(w=>w*32768),(0,a.spectrogram)(l,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:p,transpose:!0})}async _call(l,{padding:p=!0,pad_to_multiple_of:w=2,do_normalize_per_mel_bins:f=!0,return_attention_mask:i=!0}={}){(0,r.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let y=await this._extract_fbank_features(l,this.config.max_length);if(f){let[P,D]=y.dims,_=y.data;for(let M=0;M<D;++M){let I=0;for(let B=0;B<P;++B)I+=_[B*D+M];let O=I/P,G=0;for(let B=0;B<P;++B)G+=(_[B*D+M]-O)**2;G/=P-1;let U=Math.sqrt(G+1e-7);for(let B=0;B<P;++B){let Q=B*D+M;_[Q]=(_[Q]-O)/U}}}let E;if(p){let[P,D]=y.dims,_=y.data,M=P%w;if(M>0){let I=new Float32Array(D*(P+M));I.set(_),I.fill(this.config.padding_value,_.length);let O=P+M;y=new o.Tensor(y.type,I,[O,D]),i&&(E=new o.Tensor("int64",new BigInt64Array(O),[1,O]),E.data.fill(1n,0,P))}}let[S,z]=y.dims,k=this.config.stride;if(S%k!==0)throw new Error(`The number of frames (${S}) must be a multiple of the stride (${k}).`);let N=y.view(1,Math.floor(S/k),z*k),x={input_features:N};if(i){let P=N.dims[1],D=new BigInt64Array(P);if(E){let _=E.data;for(let M=1,I=0;M<S;M+=k,++I)D[I]=_[M]}else D.fill(1n);x.attention_mask=new o.Tensor("int64",D,[1,P])}return x}}},"./src/models/segformer/image_processing_segformer.js":(d,t,e)=>{e.r(t),e.d(t,{SegformerFeatureExtractor:()=>a,SegformerImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_semantic_segmentation(...u){return(0,r.post_process_semantic_segmentation)(...u)}}class a extends o{}},"./src/models/siglip/image_processing_siglip.js":(d,t,e)=>{e.r(t),e.d(t,{SiglipImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(d,t,e)=>{e.r(t),e.d(t,{SmolVLMImageProcessor:()=>r.Idefics3ImageProcessor});var r=e("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(d,t,e)=>{e.r(t),e.d(t,{SmolVLMProcessor:()=>r.Idefics3Processor});var r=e("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(d,t,e)=>{e.r(t),e.d(t,{SnacFeatureExtractor:()=>o});var r=e("./src/models/dac/feature_extraction_dac.js");class o extends r.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(d,t,e)=>{e.r(t),e.d(t,{SpeechT5FeatureExtractor:()=>o});var r=e("./src/base/feature_extraction_utils.js");class o extends r.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(d,t,e)=>{e.r(t),e.d(t,{SpeechT5Processor:()=>h});var r=e("./src/base/processing_utils.js"),o=e("./src/tokenizers.js"),a=e("./src/models/auto/feature_extraction_auto.js");class h extends r.Processor{async _call(l){return await this.feature_extractor(l)}}v(h,"tokenizer_class",o.AutoTokenizer),v(h,"feature_extractor_class",a.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(d,t,e)=>{e.r(t),e.d(t,{Swin2SRImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{pad_image(h,u,l,p={}){let[w,f,i]=u;return super.pad_image(h,u,{width:f+(l-f%l)%l,height:w+(l-w%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...p})}}},"./src/models/ultravox/processing_ultravox.js":(d,t,e)=>{e.r(t),e.d(t,{UltravoxProcessor:()=>h});var r=e("./src/models/auto/feature_extraction_auto.js"),o=e("./src/tokenizers.js"),a=e("./src/base/processing_utils.js");class h extends a.Processor{async _call(l,p=null,w={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let f={};if(p){let y=p.length,{input_features:E}=await this.feature_extractor(p,{...w,max_length:y}),S=Math.round(y/this.config.encoder_ds_factor+1e-4),z=1+Math.ceil(S/this.config.stack_factor);f.audio_token_len=[z],f.audio_values=E;let k=this.config.audio_placeholder;if(!l.includes(k))throw new Error(`The input text does not contain the image token ${k}.`);l=l.replaceAll(k,k.repeat(z))}return{...this.tokenizer(l,{add_special_tokens:!1,...w}),...f}}}v(h,"tokenizer_class",o.AutoTokenizer),v(h,"feature_extractor_class",r.AutoFeatureExtractor),v(h,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(d,t,e)=>{e.r(t),e.d(t,{ViTFeatureExtractor:()=>a,ViTImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{}class a extends o{}},"./src/models/vitmatte/image_processing_vitmatte.js":(d,t,e)=>{e.r(t),e.d(t,{VitMatteImageProcessor:()=>a});var r=e("./src/base/image_processors_utils.js"),o=e("./src/utils/tensor.js");class a extends r.ImageProcessor{async _call(u,l){Array.isArray(u)||(u=[u]),Array.isArray(l)||(l=[l]);let p=await Promise.all(u.map(i=>this.preprocess(i))),w=await Promise.all(l.map(i=>this.preprocess(i,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(p.map((i,y)=>(0,o.cat)([i.pixel_values,w[y].pixel_values],0)),0),original_sizes:p.map(i=>i.original_size),reshaped_input_sizes:p.map(i=>i.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(d,t,e)=>{e.r(t),e.d(t,{VitPoseImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_pose_estimation(h,u,{threshold:l=null}={}){let p=h.tolist(),[w,f,i,y]=h.dims,E=[];for(let S=0;S<w;++S){let z=p[S],k=u[S],A=[];for(let N=0;N<k.length;++N){let x=k[N],P=[],D=[],_=[],M=x.at(-2)/y,I=x.at(-1)/i;for(let O=0;O<z.length;++O){let[G,U]=[0,0],B=0,Q=-1/0,$=z[O];for(let se=0;se<$.length;++se){let oe=$[se];for(let ue=0;ue<oe.length;++ue){let be=oe[ue];B+=be,Q=Math.max(Q,be),G+=(ue+.5)*be,U+=se*be}}if(l!=null&&Q<l)continue;let Y=[M*G/B,I*U/B];P.push(Y),_.push(O),D.push(Q)}A.push({bbox:x,scores:D,labels:_,keypoints:P})}E.push(A)}return E}}},"./src/models/voxtral/processing_voxtral.js":(d,t,e)=>{e.r(t),e.d(t,{VoxtralProcessor:()=>f});var r=e("./src/models/auto/feature_extraction_auto.js"),o=e("./src/tokenizers.js"),a=e("./src/base/processing_utils.js"),h=e("./src/utils/tensor.js");let u="[AUDIO]",l="[BEGIN_AUDIO]",p=375;function w(i,y){let E=[];for(let S=0;S<i.length;S+=y)E.push(i.subarray(S,Math.min(S+y,i.length)));return E}class f extends a.Processor{async _call(y,E=null,S={}){if(Array.isArray(y))throw new Error("Batched inputs are not supported yet.");let z={};if(E){if(!y.includes(u))throw new Error(`The input text does not contain the audio token ${u}.`);Array.isArray(E)||(E=[E]);let A=y.split(u),N=A.length-1;if(N!==E.length)throw new Error(`The number of audio inputs (${E.length}) does not match the number of audio tokens in the text (${N}).`);let x=this.feature_extractor.config.n_samples,P=E.map(O=>w(O,x)),D=P.map(O=>O.length),_=P.flat(),M=(await Promise.all(_.map(O=>this.feature_extractor(O,S)))).map(O=>O.input_features);z.audio_values=M.length>1?(0,h.cat)(M,0):M[0];let I=A[0];for(let O=0;O<D.length;++O){I+=l;for(let G=0;G<D[O];++G)I+=u.repeat(p);I+=A[O+1]}y=I}return{...this.tokenizer(y,{add_special_tokens:!1,...S}),...z}}}v(f,"tokenizer_class",o.AutoTokenizer),v(f,"feature_extractor_class",r.AutoFeatureExtractor),v(f,"uses_processor_config",!1)},"./src/models/wav2vec2/feature_extraction_wav2vec2.js":(d,t,e)=>{e.r(t),e.d(t,{Wav2Vec2FeatureExtractor:()=>a});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js");class a extends r.FeatureExtractor{_zero_mean_unit_var_norm(u){let p=u.reduce((f,i)=>f+i,0)/u.length,w=u.reduce((f,i)=>f+(i-p)**2,0)/u.length;return u.map(f=>(f-p)/Math.sqrt(w+1e-7))}async _call(u){(0,r.validate_audio_inputs)(u,"Wav2Vec2FeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));let l=u;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));let p=[1,l.length];return{input_values:new o.Tensor("float32",l,p),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),p)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(d,t,e)=>{e.r(t),e.d(t,{Wav2Vec2Processor:()=>h});var r=e("./src/tokenizers.js"),o=e("./src/models/auto/feature_extraction_auto.js"),a=e("./src/base/processing_utils.js");class h extends a.Processor{async _call(l){return await this.feature_extractor(l)}}v(h,"tokenizer_class",r.AutoTokenizer),v(h,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(d,t,e)=>{e.r(t),e.d(t,{Wav2Vec2ProcessorWithLM:()=>h});var r=e("./src/tokenizers.js"),o=e("./src/models/auto/feature_extraction_auto.js"),a=e("./src/base/processing_utils.js");class h extends a.Processor{async _call(l){return await this.feature_extractor(l)}}v(h,"tokenizer_class",r.AutoTokenizer),v(h,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(d,t,e)=>{e.r(t),e.d(t,{WeSpeakerFeatureExtractor:()=>h});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js");class h extends r.FeatureExtractor{constructor(l){super(l);let p=this.config.sampling_rate,w=(0,a.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(p/2),p,null,"kaldi",!0);this.mel_filters=w,this.window=(0,a.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(l){return l=l.map(p=>p*32768),(0,a.spectrogram)(l,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(l){(0,r.validate_audio_inputs)(l,"WeSpeakerFeatureExtractor");let p=(await this._extract_fbank_features(l)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let w=p.mean(1).data,f=p.data,[i,y,E]=p.dims;for(let S=0;S<i;++S){let z=S*y*E,k=S*E;for(let A=0;A<y;++A){let N=z+A*E;for(let x=0;x<E;++x)f[N+x]-=w[k+x]}}}return{input_features:p}}}},"./src/models/whisper/common_whisper.js":(d,t,e)=>{e.r(t),e.d(t,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>a,whisper_language_to_code:()=>h});let r=[["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"]],o=new Map(r),a=new Map([...r.map(([u,l])=>[l,u]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function h(u){u=u.toLowerCase();let l=a.get(u);if(l===void 0){let p=u.match(/^<\|([a-z]{2})\|>$/);if(p&&(u=p[1]),o.has(u))l=u;else{let f=u.length===2?o.keys():o.values();throw new Error(`Language "${u}" is not supported. Must be one of: ${JSON.stringify(Array.from(f))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(d,t,e)=>{e.r(t),e.d(t,{WhisperFeatureExtractor:()=>u});var r=e("./src/base/feature_extraction_utils.js"),o=e("./src/utils/tensor.js"),a=e("./src/utils/audio.js"),h=e("./src/utils/maths.js");class u extends r.FeatureExtractor{constructor(p){var w;super(p),(w=this.config).mel_filters??(w.mel_filters=(0,a.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,a.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(p){let w=await(0,a.spectrogram)(p,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(p.length/this.config.hop_length),this.config.nb_max_frames)}),f=w.data,i=(0,h.max)(f)[0];for(let y=0;y<f.length;++y)f[y]=(Math.max(f[y],i-8)+4)/4;return w}async _call(p,{max_length:w=null}={}){(0,r.validate_audio_inputs)(p,"WhisperFeatureExtractor");let f,i=w??this.config.n_samples;return p.length>i?(p.length>this.config.n_samples&&console.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`."),f=p.slice(0,i)):(f=new Float32Array(i),f.set(p)),{input_features:(await this._extract_fbank_features(f)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(d,t,e)=>{e.r(t),e.d(t,{WhisperGenerationConfig:()=>o});var r=e("./src/generation/configuration_utils.js");class o extends r.GenerationConfig{constructor(){super(...arguments);v(this,"return_timestamps",null);v(this,"return_token_timestamps",null);v(this,"num_frames",null);v(this,"alignment_heads",null);v(this,"task",null);v(this,"language",null);v(this,"no_timestamps_token_id",null);v(this,"prompt_ids",null);v(this,"is_multilingual",null);v(this,"lang_to_id",null);v(this,"task_to_id",null);v(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(d,t,e)=>{e.r(t),e.d(t,{WhisperProcessor:()=>h});var r=e("./src/models/auto/feature_extraction_auto.js"),o=e("./src/tokenizers.js"),a=e("./src/base/processing_utils.js");class h extends a.Processor{async _call(l){return await this.feature_extractor(l)}}v(h,"tokenizer_class",o.AutoTokenizer),v(h,"feature_extractor_class",r.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(d,t,e)=>{e.r(t),e.d(t,{YolosFeatureExtractor:()=>a,YolosImageProcessor:()=>o});var r=e("./src/base/image_processors_utils.js");class o extends r.ImageProcessor{post_process_object_detection(...u){return(0,r.post_process_object_detection)(...u)}}class a extends o{}},"./src/ops/registry.js":(d,t,e)=>{e.r(t),e.d(t,{TensorOpRegistry:()=>h});var r=e("./src/backends/onnx.js"),o=e("./src/utils/tensor.js");let a=async(u,l,p)=>{let w=await(0,r.createInferenceSession)(new Uint8Array(u),l);return async f=>{let i=(0,r.isONNXProxy)(),y=Object.fromEntries(Object.entries(f).map(([S,z])=>[S,(i?z.clone():z).ort_tensor])),E=await(0,r.runInferenceSession)(w,y);return Array.isArray(p)?p.map(S=>new o.Tensor(E[S])):new o.Tensor(E[p])}};class h{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([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=a([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=a([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=a([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=a([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=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([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=a([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}}v(h,"session_options",{})},"./src/pipelines.js":(d,t,e)=>{e.r(t),e.d(t,{AudioClassificationPipeline:()=>B,AutomaticSpeechRecognitionPipeline:()=>$,BackgroundRemovalPipeline:()=>ue,DepthEstimationPipeline:()=>ie,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>G,FillMaskPipeline:()=>x,ImageClassificationPipeline:()=>se,ImageFeatureExtractionPipeline:()=>U,ImageSegmentationPipeline:()=>oe,ImageToImagePipeline:()=>Z,ImageToTextPipeline:()=>Y,ObjectDetectionPipeline:()=>pe,Pipeline:()=>z,QuestionAnsweringPipeline:()=>N,SummarizationPipeline:()=>D,Text2TextGenerationPipeline:()=>P,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>I,TextToAudioPipeline:()=>K,TokenClassificationPipeline:()=>A,TranslationPipeline:()=>_,ZeroShotAudioClassificationPipeline:()=>Q,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>be,ZeroShotObjectDetectionPipeline:()=>J,pipeline:()=>Oe});var r=e("./src/tokenizers.js"),o=e("./src/models.js"),a=e("./src/models/auto/processing_auto.js"),h=e("./src/base/processing_utils.js"),u=e("./src/utils/generic.js"),l=e("./src/utils/core.js"),p=e("./src/utils/maths.js"),w=e("./src/utils/audio.js"),f=e("./src/utils/tensor.js"),i=e("./src/utils/image.js");async function y(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(T=>i.RawImage.read(T)))}async function E(we,T){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(X=>typeof X=="string"||X instanceof URL?(0,w.read_audio)(X,T):X instanceof Float64Array?new Float32Array(X):X))}function S(we,T){T&&(we=we.map(ge=>ge|0));let[X,de,he,Te]=we;return{xmin:X,ymin:de,xmax:he,ymax:Te}}class z extends u.Callable{constructor({task:T,model:X,tokenizer:de=null,processor:he=null}){super(),this.task=T,this.model=X,this.tokenizer=de,this.processor=he}async dispose(){await this.model.dispose()}}class k extends z{constructor(T){super(T)}async _call(T,{top_k:X=1}={}){let de=this.tokenizer(T,{padding:!0,truncation:!0}),he=await this.model(de),Te=this.model.config.problem_type==="multi_label_classification"?ve=>ve.sigmoid():ve=>new f.Tensor("float32",(0,p.softmax)(ve.data),ve.dims),ge=this.model.config.id2label,le=[];for(let ve of he.logits){let ce=Te(ve),Me=await(0,f.topk)(ce,X),Re=Me[0].tolist(),Ie=Me[1].tolist().map((Fe,Je)=>({label:ge?ge[Fe]:`LABEL_${Fe}`,score:Re[Je]}));X===1?le.push(...Ie):le.push(Ie)}return Array.isArray(T)||X===1?le:le[0]}}class A extends z{constructor(T){super(T)}async _call(T,{ignore_labels:X=["O"]}={}){let de=Array.isArray(T),he=this.tokenizer(de?T:[T],{padding:!0,truncation:!0}),ge=(await this.model(he)).logits,le=this.model.config.id2label,ve=[];for(let ce=0;ce<ge.dims[0];++ce){let Me=he.input_ids[ce],Re=ge[ce],Ce=[];for(let Ie=0;Ie<Re.dims[0];++Ie){let Fe=Re[Ie],Je=(0,p.max)(Fe.data)[1],Ve=le?le[Je]:`LABEL_${Je}`;if(X.includes(Ve))continue;let ze=this.tokenizer.decode([Me[Ie].item()],{skip_special_tokens:!0});if(ze==="")continue;let Ae=(0,p.softmax)(Fe.data);Ce.push({entity:Ve,score:Ae[Je],index:Ie,word:ze})}ve.push(Ce)}return de?ve:ve[0]}}class N extends z{constructor(T){super(T)}async _call(T,X,{top_k:de=1}={}){let he=this.tokenizer(T,{text_pair:X,padding:!0,truncation:!0}),{start_logits:Te,end_logits:ge}=await this.model(he),le=he.input_ids.tolist(),ve=he.attention_mask.tolist(),ce=this.tokenizer.all_special_ids,Me=[];for(let Re=0;Re<Te.dims[0];++Re){let Ce=le[Re],Ie=Ce.findIndex(Ue=>Ue==this.tokenizer.sep_token_id),Fe=ve[Re].map((Ue,lt)=>Ue==1&&(lt===0||lt>Ie&&ce.findIndex(mt=>mt==Ce[lt])===-1)),Je=Te[Re].tolist(),Ve=ge[Re].tolist();for(let Ue=1;Ue<Je.length;++Ue)(ve[Re]==0||Ue<=Ie||ce.findIndex(lt=>lt==Ce[Ue])!==-1)&&(Je[Ue]=-1/0,Ve[Ue]=-1/0);let ze=(0,p.softmax)(Je).map((Ue,lt)=>[Ue,lt]),Ae=(0,p.softmax)(Ve).map((Ue,lt)=>[Ue,lt]);ze[0][0]=0,Ae[0][0]=0;let et=(0,l.product)(ze,Ae).filter(Ue=>Ue[0][1]<=Ue[1][1]).map(Ue=>[Ue[0][1],Ue[1][1],Ue[0][0]*Ue[1][0]]).sort((Ue,lt)=>lt[2]-Ue[2]);for(let Ue=0;Ue<Math.min(et.length,de);++Ue){let[lt,mt,bt]=et[Ue],Vt=Ce.slice(lt,mt+1),vt=this.tokenizer.decode(Vt,{skip_special_tokens:!0});Me.push({answer:vt,score:bt})}}return de===1?Me[0]:Me}}class x extends z{constructor(T){super(T)}async _call(T,{top_k:X=5}={}){let de=this.tokenizer(T,{padding:!0,truncation:!0}),{logits:he}=await this.model(de),Te=[],ge=de.input_ids.tolist();for(let le=0;le<ge.length;++le){let ve=ge[le],ce=ve.findIndex(Fe=>Fe==this.tokenizer.mask_token_id);if(ce===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);let Me=he[le][ce],Re=await(0,f.topk)(new f.Tensor("float32",(0,p.softmax)(Me.data),Me.dims),X),Ce=Re[0].tolist(),Ie=Re[1].tolist();Te.push(Ie.map((Fe,Je)=>{let Ve=ve.slice();return Ve[ce]=Fe,{score:Ce[Je],token:Number(Fe),token_str:this.tokenizer.decode([Fe]),sequence:this.tokenizer.decode(Ve,{skip_special_tokens:!0})}}))}return Array.isArray(T)?Te:Te[0]}}class P extends z{constructor(X){super(X);v(this,"_key","generated_text")}async _call(X,de={}){Array.isArray(X)||(X=[X]),this.model.config.prefix&&(X=X.map(ce=>this.model.config.prefix+ce));let he=this.model.config.task_specific_params;he&&he[this.task]&&he[this.task].prefix&&(X=X.map(ce=>he[this.task].prefix+ce));let Te=this.tokenizer,ge={padding:!0,truncation:!0},le;this instanceof _&&"_build_translation_inputs"in Te?le=Te._build_translation_inputs(X,ge,de):le=Te(X,ge);let ve=await this.model.generate({...le,...de});return Te.batch_decode(ve,{skip_special_tokens:!0}).map(ce=>({[this._key]:ce}))}}class D extends P{constructor(X){super(X);v(this,"_key","summary_text")}}class _ extends P{constructor(X){super(X);v(this,"_key","translation_text")}}function M(we){return Array.isArray(we)&&we.every(T=>"role"in T&&"content"in T)}class I extends z{constructor(T){super(T)}async _call(T,X={}){let de=!1,he=!1,Te=X.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,ge;if(typeof T=="string")ge=T=[T];else if(Array.isArray(T)&&T.every(Ie=>typeof Ie=="string"))de=!0,ge=T;else{if(M(T))T=[T];else if(Array.isArray(T)&&T.every(M))de=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");he=!0,ge=T.map(Ie=>this.tokenizer.apply_chat_template(Ie,{tokenize:!1,add_generation_prompt:!0})),Te=!1}let le=he?!1:X.return_full_text??!0;this.tokenizer.padding_side="left";let ve=this.tokenizer(ge,{add_special_tokens:Te,padding:!0,truncation:!0}),ce=await this.model.generate({...ve,...X}),Me=this.tokenizer.batch_decode(ce,{skip_special_tokens:!0}),Re;!le&&ve.input_ids.dims.at(-1)>0&&(Re=this.tokenizer.batch_decode(ve.input_ids,{skip_special_tokens:!0}).map(Ie=>Ie.length));let Ce=Array.from({length:T.length},Ie=>[]);for(let Ie=0;Ie<Me.length;++Ie){let Fe=Math.floor(Ie/ce.dims[0]*T.length);Re&&(Me[Ie]=Me[Ie].slice(Re[Fe])),Ce[Fe].push({generated_text:he?[...T[Fe],{role:"assistant",content:Me[Ie]}]:Me[Ie]})}return!de&&Ce.length===1?Ce[0]:Ce}}class O extends z{constructor(T){super(T),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([X,de])=>[X.toLowerCase(),de])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.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&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(T,X,{hypothesis_template:de="This example is {}.",multi_label:he=!1}={}){let Te=Array.isArray(T);Te||(T=[T]),Array.isArray(X)||(X=[X]);let ge=X.map(ce=>de.replace("{}",ce)),le=he||X.length===1,ve=[];for(let ce of T){let Me=[];for(let Ie of ge){let Fe=this.tokenizer(ce,{text_pair:Ie,padding:!0,truncation:!0}),Je=await this.model(Fe);le?Me.push([Je.logits.data[this.contradiction_id],Je.logits.data[this.entailment_id]]):Me.push(Je.logits.data[this.entailment_id])}let Ce=(le?Me.map(Ie=>(0,p.softmax)(Ie)[1]):(0,p.softmax)(Me)).map((Ie,Fe)=>[Ie,Fe]).sort((Ie,Fe)=>Fe[0]-Ie[0]);ve.push({sequence:ce,labels:Ce.map(Ie=>X[Ie[1]]),scores:Ce.map(Ie=>Ie[0])})}return Te?ve:ve[0]}}class G extends z{constructor(T){super(T)}async _call(T,{pooling:X="none",normalize:de=!1,quantize:he=!1,precision:Te="binary"}={}){let ge=this.tokenizer(T,{padding:!0,truncation:!0}),le=await this.model(ge),ve=le.last_hidden_state??le.logits??le.token_embeddings;switch(X){case"none":break;case"mean":ve=(0,f.mean_pooling)(ve,ge.attention_mask);break;case"first_token":case"cls":ve=ve.slice(null,0);break;case"last_token":case"eos":ve=ve.slice(null,-1);break;default:throw Error(`Pooling method '${X}' not supported.`)}return de&&(ve=ve.normalize(2,-1)),he&&(ve=(0,f.quantize_embeddings)(ve,Te)),ve}}class U extends z{constructor(T){super(T)}async _call(T,{pool:X=null}={}){let de=await y(T),{pixel_values:he}=await this.processor(de),Te=await this.model({pixel_values:he}),ge;if(X){if(!("pooler_output"in Te))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");ge=Te.pooler_output}else ge=Te.last_hidden_state??Te.logits??Te.image_embeds;return ge}}class B extends z{constructor(T){super(T)}async _call(T,{top_k:X=5}={}){let de=this.processor.feature_extractor.config.sampling_rate,he=await E(T,de),Te=this.model.config.id2label,ge=[];for(let le of he){let ve=await this.processor(le),Me=(await this.model(ve)).logits[0],Re=await(0,f.topk)(new f.Tensor("float32",(0,p.softmax)(Me.data),Me.dims),X),Ce=Re[0].tolist(),Fe=Re[1].tolist().map((Je,Ve)=>({label:Te?Te[Je]:`LABEL_${Je}`,score:Ce[Ve]}));ge.push(Fe)}return Array.isArray(T)?ge:ge[0]}}class Q extends z{constructor(T){super(T)}async _call(T,X,{hypothesis_template:de="This is a sound of {}."}={}){let he=!Array.isArray(T);he&&(T=[T]);let Te=X.map(Me=>de.replace("{}",Me)),ge=this.tokenizer(Te,{padding:!0,truncation:!0}),le=this.processor.feature_extractor.config.sampling_rate,ve=await E(T,le),ce=[];for(let Me of ve){let Re=await this.processor(Me),Ce=await this.model({...ge,...Re}),Ie=(0,p.softmax)(Ce.logits_per_audio.data);ce.push([...Ie].map((Fe,Je)=>({score:Fe,label:X[Je]})))}return he?ce[0]:ce}}class $ extends z{constructor(T){super(T)}async _call(T,X={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(T,X);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(T,X);case"moonshine":return this._call_moonshine(T,X);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(T,X){X.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),X.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let de=!Array.isArray(T);de&&(T=[T]);let he=this.processor.feature_extractor.config.sampling_rate,Te=await E(T,he),ge=[];for(let le of Te){let ve=await this.processor(le),Me=(await this.model(ve)).logits[0],Re=[];for(let Ie of Me)Re.push((0,p.max)(Ie.data)[1]);let Ce=this.tokenizer.decode(Re,{skip_special_tokens:!0}).trim();ge.push({text:Ce})}return de?ge[0]:ge}async _call_whisper(T,X){let de=X.return_timestamps??!1,he=X.chunk_length_s??0,Te=X.force_full_sequences??!1,ge=X.stride_length_s??null,le={...X};de==="word"&&(le.return_token_timestamps=!0,le.return_timestamps=!1);let ve=!Array.isArray(T);ve&&(T=[T]);let ce=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Me=this.processor.feature_extractor.config.hop_length,Re=this.processor.feature_extractor.config.sampling_rate,Ce=await E(T,Re),Ie=[];for(let Fe of Ce){let Je=[];if(he>0){if(ge===null)ge=he/6;else if(he<=ge)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let Ae=Re*he,et=Re*ge,Ue=Ae-2*et,lt=0;for(;;){let mt=lt+Ae,bt=Fe.subarray(lt,mt),Vt=await this.processor(bt),vt=lt===0,Ht=mt>=Fe.length;if(Je.push({stride:[bt.length,vt?0:et,Ht?0:et],input_features:Vt.input_features,is_last:Ht}),Ht)break;lt+=Ue}}else Je=[{stride:[Fe.length,0,0],input_features:(await this.processor(Fe)).input_features,is_last:!0}];for(let Ae of Je){le.num_frames=Math.floor(Ae.stride[0]/Me);let et=await this.model.generate({inputs:Ae.input_features,...le});de==="word"?(Ae.tokens=et.sequences.tolist()[0],Ae.token_timestamps=et.token_timestamps.tolist()[0].map(Ue=>(0,p.round)(Ue,2))):Ae.tokens=et[0].tolist(),Ae.stride=Ae.stride.map(Ue=>Ue/Re)}let[Ve,ze]=this.tokenizer._decode_asr(Je,{time_precision:ce,return_timestamps:de,force_full_sequences:Te});Ie.push({text:Ve,...ze})}return ve?Ie[0]:Ie}async _call_moonshine(T,X){let de=!Array.isArray(T);de&&(T=[T]);let he=this.processor.feature_extractor.config.sampling_rate,Te=await E(T,he),ge=[];for(let le of Te){let ve=await this.processor(le),ce=Math.floor(le.length/he)*6,Me=await this.model.generate({max_new_tokens:ce,...X,...ve}),Re=this.processor.batch_decode(Me,{skip_special_tokens:!0})[0];ge.push({text:Re})}return de?ge[0]:ge}}class Y extends z{constructor(T){super(T)}async _call(T,X={}){let de=Array.isArray(T),he=await y(T),{pixel_values:Te}=await this.processor(he),ge=[];for(let le of Te){le.dims=[1,...le.dims];let ve=await this.model.generate({inputs:le,...X}),ce=this.tokenizer.batch_decode(ve,{skip_special_tokens:!0}).map(Me=>({generated_text:Me.trim()}));ge.push(ce)}return de?ge:ge[0]}}class se extends z{constructor(T){super(T)}async _call(T,{top_k:X=5}={}){let de=await y(T),{pixel_values:he}=await this.processor(de),Te=await this.model({pixel_values:he}),ge=this.model.config.id2label,le=[];for(let ve of Te.logits){let ce=await(0,f.topk)(new f.Tensor("float32",(0,p.softmax)(ve.data),ve.dims),X),Me=ce[0].tolist(),Ce=ce[1].tolist().map((Ie,Fe)=>({label:ge?ge[Ie]:`LABEL_${Ie}`,score:Me[Fe]}));le.push(Ce)}return Array.isArray(T)?le:le[0]}}class oe extends z{constructor(T){super(T),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(T,{threshold:X=.5,mask_threshold:de=.5,overlap_mask_area_threshold:he=.8,label_ids_to_fuse:Te=null,target_sizes:ge=null,subtask:le=null}={}){if(Array.isArray(T)&&T.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let ce=await y(T),Me=ce.map(Ae=>[Ae.height,Ae.width]),Re=await this.processor(ce),{inputNames:Ce,outputNames:Ie}=this.model.sessions.model;if(!Ce.includes("pixel_values")){if(Ce.length!==1)throw Error(`Expected a single input name, but got ${Ce.length} inputs: ${Ce}.`);let Ae=Ce[0];if(Ae in Re)throw Error(`Input name ${Ae} already exists in the inputs.`);Re[Ae]=Re.pixel_values}let Fe=await this.model(Re),Je=null;if(le!==null)Je=this.subtasks_mapping[le];else if(this.processor.image_processor){for(let[Ae,et]of Object.entries(this.subtasks_mapping))if(et in this.processor.image_processor){Je=this.processor.image_processor[et].bind(this.processor.image_processor),le=Ae;break}}let Ve=this.model.config.id2label,ze=[];if(le)if(le==="panoptic"||le==="instance"){let Ae=Je(Fe,X,de,he,Te,ge??Me)[0],et=Ae.segmentation;for(let Ue of Ae.segments_info){let lt=new Uint8ClampedArray(et.data.length);for(let bt=0;bt<et.data.length;++bt)et.data[bt]===Ue.id&&(lt[bt]=255);let mt=new i.RawImage(lt,et.dims[1],et.dims[0],1);ze.push({score:Ue.score,label:Ve[Ue.label_id],mask:mt})}}else if(le==="semantic"){let{segmentation:Ae,labels:et}=Je(Fe,ge??Me)[0];for(let Ue of et){let lt=new Uint8ClampedArray(Ae.data.length);for(let bt=0;bt<Ae.data.length;++bt)Ae.data[bt]===Ue&&(lt[bt]=255);let mt=new i.RawImage(lt,Ae.dims[1],Ae.dims[0],1);ze.push({score:null,label:Ve[Ue],mask:mt})}}else throw Error(`Subtask ${le} not supported.`);else{let et=Fe[Ie[0]];for(let Ue=0;Ue<Me.length;++Ue){let lt=Me[Ue],mt=et[Ue];mt.data.some(Vt=>Vt<-1e-5||Vt>1+1e-5)&&mt.sigmoid_();let bt=await i.RawImage.fromTensor(mt.mul_(255).to("uint8")).resize(lt[1],lt[0]);ze.push({label:null,score:null,mask:bt})}}return ze}}class ue extends oe{constructor(T){super(T)}async _call(T,X={}){if(Array.isArray(T)&&T.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");let he=await y(T),Te=await super._call(T,X);return he.map((le,ve)=>{let ce=le.clone();return ce.putAlpha(Te[ve].mask),ce})}}class be extends z{constructor(T){super(T)}async _call(T,X,{hypothesis_template:de="This is a photo of {}"}={}){let he=Array.isArray(T),Te=await y(T),ge=X.map(Ce=>de.replace("{}",Ce)),le=this.tokenizer(ge,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ve}=await this.processor(Te),ce=await this.model({...le,pixel_values:ve}),Me=this.model.config.model_type==="siglip"?Ce=>Ce.sigmoid().data:Ce=>(0,p.softmax)(Ce.data),Re=[];for(let Ce of ce.logits_per_image){let Fe=[...Me(Ce)].map((Je,Ve)=>({score:Je,label:X[Ve]}));Fe.sort((Je,Ve)=>Ve.score-Je.score),Re.push(Fe)}return he?Re:Re[0]}}class pe extends z{constructor(T){super(T)}async _call(T,{threshold:X=.9,percentage:de=!1}={}){let he=Array.isArray(T);if(he&&T.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let Te=await y(T),ge=de?null:Te.map(Ie=>[Ie.height,Ie.width]),{pixel_values:le,pixel_mask:ve}=await this.processor(Te),ce=await this.model({pixel_values:le,pixel_mask:ve}),Me=this.processor.image_processor.post_process_object_detection(ce,X,ge),Re=this.model.config.id2label,Ce=Me.map(Ie=>Ie.boxes.map((Fe,Je)=>({score:Ie.scores[Je],label:Re[Ie.classes[Je]],box:S(Fe,!de)})));return he?Ce:Ce[0]}}class J extends z{constructor(T){super(T)}async _call(T,X,{threshold:de=.1,top_k:he=null,percentage:Te=!1}={}){let ge=Array.isArray(T),le=await y(T),ve=this.tokenizer(X,{padding:!0,truncation:!0}),ce=await this.processor(le),Me=[];for(let Re=0;Re<le.length;++Re){let Ce=le[Re],Ie=Te?null:[[Ce.height,Ce.width]],Fe=ce.pixel_values[Re].unsqueeze_(0),Je=await this.model({...ve,pixel_values:Fe}),Ve;if("post_process_grounded_object_detection"in this.processor){let ze=this.processor.post_process_grounded_object_detection(Je,ve.input_ids,{box_threshold:de,text_threshold:de,target_sizes:Ie})[0];Ve=ze.boxes.map((Ae,et)=>({score:ze.scores[et],label:ze.labels[et],box:S(Ae,!Te)}))}else{let ze=this.processor.image_processor.post_process_object_detection(Je,de,Ie,!0)[0];Ve=ze.boxes.map((Ae,et)=>({score:ze.scores[et],label:X[ze.classes[et]],box:S(Ae,!Te)}))}Ve.sort((ze,Ae)=>Ae.score-ze.score),he!==null&&(Ve=Ve.slice(0,he)),Me.push(Ve)}return ge?Me:Me[0]}}class F extends z{constructor(T){super(T)}async _call(T,X,de={}){let he=(await y(T))[0],{pixel_values:Te}=await this.processor(he),ge=`<s_docvqa><s_question>${X}</s_question><s_answer>`,le=this.tokenizer(ge,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ve=await this.model.generate({inputs:Te,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:le,...de}),Me=this.tokenizer.batch_decode(ve)[0].match(/<s_answer>(.*?)<\/s_answer>/),Re=null;return Me&&Me.length>=2&&(Re=Me[1].trim()),[{answer:Re}]}}class K extends z{constructor(X){super(X);v(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=X.vocoder??null}async _prepare_speaker_embeddings(X){if((typeof X=="string"||X instanceof URL)&&(X=new Float32Array(await(await fetch(X)).arrayBuffer())),X instanceof Float32Array)X=new f.Tensor("float32",X,[X.length]);else if(!(X instanceof f.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");return X}async _call(X,{speaker_embeddings:de=null,num_inference_steps:he,speed:Te}={}){return this.processor?this._call_text_to_spectrogram(X,{speaker_embeddings:de}):this.model.config.model_type==="supertonic"?this._call_supertonic(X,{speaker_embeddings:de,num_inference_steps:he,speed:Te}):this._call_text_to_waveform(X)}async _call_supertonic(X,{speaker_embeddings:de,num_inference_steps:he,speed:Te}){if(!de)throw new Error("Speaker embeddings must be provided for Supertonic models.");de=await this._prepare_speaker_embeddings(de);let{sampling_rate:ge,style_dim:le}=this.model.config;de=de.view(1,-1,le);let ve=this.tokenizer(X,{padding:!0,truncation:!0}),{waveform:ce}=await this.model.generate_speech({...ve,style:de,num_inference_steps:he,speed:Te});return new w.RawAudio(ce.data,ge)}async _call_text_to_waveform(X){let de=this.tokenizer(X,{padding:!0,truncation:!0}),{waveform:he}=await this.model(de),Te=this.model.config.sampling_rate;return new w.RawAudio(he.data,Te)}async _call_text_to_spectrogram(X,{speaker_embeddings:de}){this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:he}=this.tokenizer(X,{padding:!0,truncation:!0});de=await this._prepare_speaker_embeddings(de),de=de.view(1,-1);let{waveform:Te}=await this.model.generate_speech(he,de,{vocoder:this.vocoder}),ge=this.processor.feature_extractor.config.sampling_rate;return new w.RawAudio(Te.data,ge)}}class Z extends z{constructor(T){super(T)}async _call(T){let X=await y(T),de=await this.processor(X),he=await this.model(de),Te=[];for(let ge of he.reconstruction){let le=ge.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Te.push(i.RawImage.fromTensor(le))}return Te.length>1?Te:Te[0]}}class ie extends z{constructor(T){super(T)}async _call(T){let X=await y(T),de=await this.processor(X),{predicted_depth:he}=await this.model(de),Te=[];for(let ge=0;ge<X.length;++ge){let le=he[ge],[ve,ce]=le.dims.slice(-2),[Me,Re]=X[ge].size,Ce=(await(0,f.interpolate_4d)(le.view(1,1,ve,ce),{size:[Re,Me],mode:"bilinear"})).view(Re,Me),Ie=Ce.min().item(),Fe=Ce.max().item(),Je=Ce.sub(Ie).div_(Fe-Ie).mul_(255).to("uint8").unsqueeze(0),Ve=i.RawImage.fromTensor(Je);Te.push({predicted_depth:Ce,depth:Ve})}return Te.length>1?Te:Te[0]}}let xe=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:A,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:N,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:x,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:D,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:_,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:P,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:I,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:O,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:B,model:o.AutoModelForAudioClassification,processor:a.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:Q,model:o.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:$,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:a.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:K,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[a.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:Y,model:o.AutoModelForVision2Seq,processor:a.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:se,model:o.AutoModelForImageClassification,processor:a.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ue,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:a.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:be,model:o.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:o.AutoModelForObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:J,model:o.AutoModelForZeroShotObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:a.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Z,model:o.AutoModelForImageToImage,processor:a.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ie,model:o.AutoModelForDepthEstimation,processor:a.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:G,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:a.AutoProcessor,pipeline:U,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ye=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Oe(we,T=null,{progress_callback:X=null,config:de=null,cache_dir:he=null,local_files_only:Te=!1,revision:ge="main",device:le=null,dtype:ve=null,subfolder:ce="onnx",use_external_data_format:Me=null,model_file_name:Re=null,session_options:Ce={}}={}){we=ye[we]??we;let Ie=xe[we.split("_",1)[0]];if(!Ie)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(xe)}]`);T||(T=Ie.default.model,console.log(`No model specified. Using default model: "${T}".`));let Fe={progress_callback:X,config:de,cache_dir:he,local_files_only:Te,revision:ge,device:le,dtype:ve,subfolder:ce,use_external_data_format:Me,model_file_name:Re,session_options:Ce},Je=new Map([["tokenizer",Ie.tokenizer],["model",Ie.model],["processor",Ie.processor]]),Ve=await He(Je,T,Fe);Ve.task=we,(0,l.dispatchCallback)(X,{status:"ready",task:we,model:T});let ze=Ie.pipeline;return new ze(Ve)}async function He(we,T,X){let de=Object.create(null),he=[];for(let[Te,ge]of we.entries()){if(!ge)continue;let le;Array.isArray(ge)?le=new Promise(async(ve,ce)=>{let Me;for(let Re of ge){if(Re===null){ve(null);return}try{ve(await Re.from_pretrained(T,X));return}catch(Ce){if(Ce.message?.includes("Unsupported model type"))Me=Ce;else if(Ce.message?.includes("Could not locate file"))Me=Ce;else{ce(Ce);return}}}ce(Me)}):le=ge.from_pretrained(T,X),de[Te]=le,he.push(le)}await Promise.all(he);for(let[Te,ge]of Object.entries(de))de[Te]=await ge;return de}},"./src/tokenizers.js":(d,t,e)=>{e.r(t),e.d(t,{AlbertTokenizer:()=>zr,AutoTokenizer:()=>Is,BartTokenizer:()=>je,BertTokenizer:()=>Ur,BlenderbotSmallTokenizer:()=>De,BlenderbotTokenizer:()=>ke,BloomTokenizer:()=>ft,CLIPTokenizer:()=>Sr,CamembertTokenizer:()=>V,CodeGenTokenizer:()=>Ir,CodeLlamaTokenizer:()=>ar,CohereTokenizer:()=>Lr,ConvBertTokenizer:()=>j,DebertaTokenizer:()=>_t,DebertaV2Tokenizer:()=>Gr,DistilBertTokenizer:()=>R,ElectraTokenizer:()=>me,EsmTokenizer:()=>cr,FalconTokenizer:()=>kr,GPT2Tokenizer:()=>qe,GPTNeoXTokenizer:()=>Fr,GemmaTokenizer:()=>Ar,Grok1Tokenizer:()=>$r,HerbertTokenizer:()=>m,LlamaTokenizer:()=>Ut,M2M100Tokenizer:()=>wr,MBart50Tokenizer:()=>Ge,MBartTokenizer:()=>st,MPNetTokenizer:()=>Cr,MarianTokenizer:()=>Tr,MgpstrTokenizer:()=>Xr,MobileBertTokenizer:()=>Wr,NllbTokenizer:()=>Mr,NougatTokenizer:()=>xt,PreTrainedTokenizer:()=>rt,Qwen2Tokenizer:()=>Kr,RoFormerTokenizer:()=>C,RobertaTokenizer:()=>ct,SiglipTokenizer:()=>Dr,SpeechT5Tokenizer:()=>Qe,SqueezeBertTokenizer:()=>pr,T5Tokenizer:()=>Ke,TokenizerModel:()=>G,VitsTokenizer:()=>Qr,Wav2Vec2CTCTokenizer:()=>ir,WhisperTokenizer:()=>Hr,XLMRobertaTokenizer:()=>Xt,XLMTokenizer:()=>te,is_chinese_char:()=>N});var r=e("./src/utils/generic.js"),o=e("./src/utils/core.js"),a=e("./src/utils/hub.js"),h=e("./src/utils/maths.js"),u=e("./src/utils/tensor.js"),l=e("./src/utils/data-structures.js"),p=e("./node_modules/@huggingface/jinja/dist/index.js"),w=e("./src/models/whisper/common_whisper.js");async function f(re,g){let L=await Promise.all([(0,a.getModelJSON)(re,"tokenizer.json",!0,g),(0,a.getModelJSON)(re,"tokenizer_config.json",!0,g)]);return g.legacy!==null&&(L[1].legacy=g.legacy),L}function i(re,g){let L=[],W=0;for(let q of re.matchAll(g)){let ee=q[0];W<q.index&&L.push(re.slice(W,q.index)),ee.length>0&&L.push(ee),W=q.index+ee.length}return W<re.length&&L.push(re.slice(W)),L}function y(re,g=!0){if(re.Regex!==void 0){let L=re.Regex.replace(/\\([#&~])/g,"$1");for(let[W,q]of I)L=L.replaceAll(W,q);return new RegExp(L,"gu")}else if(re.String!==void 0){let L=(0,o.escapeRegExp)(re.String);return new RegExp(g?L:`(${L})`,"gu")}else return console.warn("Unknown pattern type:",re),null}function E(re){return new Map(Object.entries(re))}function S(re){let g=re.dims;switch(g.length){case 1:return re.tolist();case 2:if(g[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return re.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${g.length}.`)}}function z(re){return re.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")}function k(re){return re.replace(new RegExp("\\p{M}","gu"),"")}function A(re){return k(re.toLowerCase())}function N(re){return re>=19968&&re<=40959||re>=13312&&re<=19903||re>=131072&&re<=173791||re>=173824&&re<=177983||re>=177984&&re<=178207||re>=178208&&re<=183983||re>=63744&&re<=64255||re>=194560&&re<=195103}function x(re,g,L){let W=[],q=0;for(;q<re.length;){if(W.push(re[q]),(g.get(re[q])??L)!==L){++q;continue}for(;++q<re.length&&(g.get(re[q])??L)===L;)g.get(W.at(-1))!==L&&(W[W.length-1]+=re[q])}return W}function P(re){return re.match(/\S+/g)||[]}let D="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",_=new RegExp(`^[${D}]+$`,"gu"),M=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",I=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${M}])]+`,` ?[^\\s${M}]+`]]);class O{constructor(g){this.content=g.content,this.id=g.id,this.single_word=g.single_word??!1,this.lstrip=g.lstrip??!1,this.rstrip=g.rstrip??!1,this.special=g.special??!1,this.normalized=g.normalized??null}}class G extends r.Callable{constructor(g){super(),this.config=g,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}static fromConfig(g,...L){switch(g.type){case"WordPiece":return new U(g);case"Unigram":return new B(g,...L);case"BPE":return new Y(g);default:if(g.vocab)return Array.isArray(g.vocab)?new B(g,...L):Object.hasOwn(g,"continuing_subword_prefix")&&Object.hasOwn(g,"unk_token")?Object.hasOwn(g,"merges")?new Y(g):new U(g):new se(g,...L);throw new Error(`Unknown TokenizerModel type: ${g.type}`)}}_call(g){return g=this.encode(g),this.fuse_unk&&(g=x(g,this.tokens_to_ids,this.unk_token_id)),g}encode(g){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(g){return g.map(L=>this.tokens_to_ids.get(L)??this.unk_token_id)}convert_ids_to_tokens(g){return g.map(L=>this.vocab[L]??this.unk_token)}}class U extends G{constructor(g){super(g),this.tokens_to_ids=E(g.vocab),this.unk_token_id=this.tokens_to_ids.get(g.unk_token),this.unk_token=g.unk_token,this.max_input_chars_per_word=g.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[L,W]of this.tokens_to_ids)this.vocab[W]=L}encode(g){let L=[];for(let W of g){let q=[...W];if(q.length>this.max_input_chars_per_word){L.push(this.unk_token);continue}let ee=!1,fe=0,Le=[];for(;fe<q.length;){let We=q.length,Be=null;for(;fe<We;){let $e=q.slice(fe,We).join("");if(fe>0&&($e=this.config.continuing_subword_prefix+$e),this.tokens_to_ids.has($e)){Be=$e;break}--We}if(Be===null){ee=!0;break}Le.push(Be),fe=We}ee?L.push(this.unk_token):L.push(...Le)}return L}}class B extends G{constructor(g,L){super(g);let W=g.vocab.length;this.vocab=new Array(W),this.scores=new Array(W);for(let q=0;q<W;++q)[this.vocab[q],this.scores[q]]=g.vocab[q];this.unk_token_id=g.unk_id,this.unk_token=this.vocab[g.unk_id],this.tokens_to_ids=new Map(this.vocab.map((q,ee)=>[q,ee])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=L.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,h.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(g){let L=g.chars,W=1,q=0;for(;q<L.length;){let ee=!1,fe=[],Le=L.slice(q).join(""),We=this.trie.commonPrefixSearch(Le);for(let Be of We){fe.push(Be);let $e=this.tokens_to_ids.get(Be),ot=this.scores[$e],Mt=(0,o.len)(Be);g.insert(q,Mt,ot,$e),!ee&&Mt===W&&(ee=!0)}ee||g.insert(q,W,this.unk_score,this.unk_token_id),q+=W}}tokenize(g){let L=new l.TokenLattice(g,this.bos_token_id,this.eos_token_id);return this.populateNodes(L),L.tokens()}encode(g){let L=[];for(let W of g){let q=this.tokenize(W);L.push(...q)}return L}}let Q=(()=>{let re=[...Array.from({length:94},(q,ee)=>ee+33),...Array.from({length:12},(q,ee)=>ee+161),...Array.from({length:82},(q,ee)=>ee+174)],g=re.slice(),L=0;for(let q=0;q<256;++q)re.includes(q)||(re.push(q),g.push(256+L),L+=1);let W=g.map(q=>String.fromCharCode(q));return Object.fromEntries(re.map((q,ee)=>[q,W[ee]]))})(),$=(0,o.reverseDictionary)(Q);class Y extends G{constructor(g){super(g),this.tokens_to_ids=E(g.vocab),this.unk_token_id=this.tokens_to_ids.get(g.unk_token),this.unk_token=g.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[W,q]of this.tokens_to_ids)this.vocab[q]=W;let L=Array.isArray(g.merges[0]);this.merges=L?g.merges:g.merges.map(W=>W.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((W,q)=>[JSON.stringify(W),q])),this.end_of_word_suffix=g.end_of_word_suffix,this.continuing_subword_suffix=g.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 l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(g){if(g.length===0)return[];let L=this.cache.get(g);if(L!==void 0)return L;let W=Array.from(g);this.end_of_word_suffix&&(W[W.length-1]+=this.end_of_word_suffix);let q=[];if(W.length>1){let ee=new l.PriorityQueue((We,Be)=>We.score<Be.score),fe={token:W[0],bias:0,prev:null,next:null},Le=fe;for(let We=1;We<W.length;++We){let Be={bias:We/W.length,token:W[We],prev:Le,next:null};Le.next=Be,this._add_node(ee,Le),Le=Be}for(;!ee.isEmpty();){let We=ee.pop();if(We.deleted||!We.next||We.next.deleted)continue;if(We.deleted=!0,We.next.deleted=!0,We.prev){let $e={...We.prev};We.prev.deleted=!0,We.prev=$e,$e.prev?$e.prev.next=$e:fe=$e}let Be={token:We.token+We.next.token,bias:We.bias,prev:We.prev,next:We.next.next};Be.prev?(Be.prev.next=Be,this._add_node(ee,Be.prev)):fe=Be,Be.next&&(Be.next.prev=Be,this._add_node(ee,Be))}for(let We=fe;We!==null;We=We.next)q.push(We.token)}else q=W;if(this.continuing_subword_suffix)for(let ee=0;ee<q.length-1;++ee)q[ee]+=this.continuing_subword_suffix;return g.length<this.max_length_to_cache&&this.cache.put(g,q),q}_add_node(g,L){let W=this.bpe_ranks.get(JSON.stringify([L.token,L.next.token]));W!==void 0&&(L.score=W+L.bias,g.push(L))}encode(g){let L=[];for(let W of g){if(this.ignore_merges&&this.tokens_to_ids.has(W)){L.push(W);continue}let q=this.bpe(W);for(let ee of q)if(this.tokens_to_ids.has(ee))L.push(ee);else if(this.byte_fallback){let fe=Array.from(this.text_encoder.encode(ee)).map(Le=>`<0x${Le.toString(16).toUpperCase().padStart(2,"0")}>`);fe.every(Le=>this.tokens_to_ids.has(Le))?L.push(...fe):L.push(this.unk_token)}else L.push(this.unk_token)}return L}}class se extends G{constructor(g,L){super(g),this.tokens_to_ids=E(L.target_lang?g.vocab[L.target_lang]:g.vocab),this.bos_token=L.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=L.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=L.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=L.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[W,q]of this.tokens_to_ids)this.vocab[q]=W}encode(g){return g}}class oe extends r.Callable{constructor(g){super(),this.config=g}static fromConfig(g){if(g===null)return null;switch(g.type){case"BertNormalizer":return new He(g);case"Precompiled":return new vt(g);case"Sequence":return new Oe(g);case"Replace":return new ue(g);case"NFC":return new pe(g);case"NFD":return new J(g);case"NFKC":return new F(g);case"NFKD":return new K(g);case"Strip":return new Z(g);case"StripAccents":return new ie(g);case"Lowercase":return new xe(g);case"Prepend":return new ye(g);default:throw new Error(`Unknown Normalizer type: ${g.type}`)}}normalize(g){throw Error("normalize should be implemented in subclass.")}_call(g){return this.normalize(g)}}class ue extends oe{normalize(g){let L=y(this.config.pattern);return L===null?g:g.replaceAll(L,this.config.content)}}class be extends oe{constructor(){super(...arguments);v(this,"form")}normalize(L){return L=L.normalize(this.form),L}}class pe extends be{constructor(){super(...arguments);v(this,"form","NFC")}}class J extends be{constructor(){super(...arguments);v(this,"form","NFD")}}class F extends be{constructor(){super(...arguments);v(this,"form","NFKC")}}class K extends be{constructor(){super(...arguments);v(this,"form","NFKD")}}class Z extends oe{normalize(g){return this.config.strip_left&&this.config.strip_right?g=g.trim():(this.config.strip_left&&(g=g.trimStart()),this.config.strip_right&&(g=g.trimEnd())),g}}class ie extends oe{normalize(g){return g=k(g),g}}class xe extends oe{normalize(g){return g=g.toLowerCase(),g}}class ye extends oe{normalize(g){return g=this.config.prepend+g,g}}class Oe extends oe{constructor(g){super(g),this.normalizers=g.normalizers.map(L=>oe.fromConfig(L))}normalize(g){return this.normalizers.reduce((L,W)=>W.normalize(L),g)}}class He extends oe{_tokenize_chinese_chars(g){let L=[];for(let W=0;W<g.length;++W){let q=g[W],ee=q.charCodeAt(0);N(ee)?(L.push(" "),L.push(q),L.push(" ")):L.push(q)}return L.join("")}stripAccents(g){return g.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control(g){switch(g){case" ":case`
24
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(g)}}_clean_text(g){let L=[];for(let W of g){let q=W.charCodeAt(0);q===0||q===65533||this._is_control(W)||(/^\s$/.test(W)?L.push(" "):L.push(W))}return L.join("")}normalize(g){return this.config.clean_text&&(g=this._clean_text(g)),this.config.handle_chinese_chars&&(g=this._tokenize_chinese_chars(g)),this.config.lowercase?(g=g.toLowerCase(),this.config.strip_accents!==!1&&(g=this.stripAccents(g))):this.config.strip_accents&&(g=this.stripAccents(g)),g}}class we extends r.Callable{static fromConfig(g){if(g===null)return null;switch(g.type){case"BertPreTokenizer":return new T(g);case"Sequence":return new Ht(g);case"Whitespace":return new ls(g);case"WhitespaceSplit":return new cs(g);case"Metaspace":return new bt(g);case"ByteLevel":return new X(g);case"Split":return new de(g);case"Punctuation":return new he(g);case"Digits":return new Te(g);case"Replace":return new ds(g);case"FixedLength":return new St(g);default:throw new Error(`Unknown PreTokenizer type: ${g.type}`)}}pre_tokenize_text(g,L){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(g,L){return(Array.isArray(g)?g.map(W=>this.pre_tokenize_text(W,L)):this.pre_tokenize_text(g,L)).flat()}_call(g,L){return this.pre_tokenize(g,L)}}class T extends we{constructor(g){super(),this.pattern=new RegExp(`[^\\s${D}]+|[${D}]`,"gu")}pre_tokenize_text(g,L){return g.trim().match(this.pattern)||[]}}class X extends we{constructor(g){super(),this.config=g,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Q,this.text_encoder=new TextEncoder}pre_tokenize_text(g,L){return this.add_prefix_space&&!g.startsWith(" ")&&(g=" "+g),(this.use_regex?g.match(this.pattern)||[]:[g]).map(q=>Array.from(this.text_encoder.encode(q),ee=>this.byte_encoder[ee]).join(""))}}class de extends we{constructor(g){super(),this.config=g,this.pattern=y(this.config.pattern,this.config.invert)}pre_tokenize_text(g,L){return this.pattern===null?[]:this.config.invert?g.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?g.split(this.pattern).filter(W=>W):i(g,this.pattern)}}class he extends we{constructor(g){super(),this.config=g,this.pattern=new RegExp(`[^${D}]+|[${D}]+`,"gu")}pre_tokenize_text(g,L){return g.match(this.pattern)||[]}}class Te extends we{constructor(g){super(),this.config=g;let L=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(L,"gu")}pre_tokenize_text(g,L){return g.match(this.pattern)||[]}}class ge extends r.Callable{constructor(g){super(),this.config=g}static fromConfig(g){if(g===null)return null;switch(g.type){case"TemplateProcessing":return new ce(g);case"ByteLevel":return new Me(g);case"RobertaProcessing":return new ve(g);case"BertProcessing":return new le(g);case"Sequence":return new Re(g);default:throw new Error(`Unknown PostProcessor type: ${g.type}`)}}post_process(g,...L){throw Error("post_process should be implemented in subclass.")}_call(g,...L){return this.post_process(g,...L)}}class le extends ge{constructor(g){super(g),this.cls=g.cls[0],this.sep=g.sep[0]}post_process(g,L=null,{add_special_tokens:W=!0}={}){W&&(g=(0,o.mergeArrays)([this.cls],g,[this.sep]));let q=new Array(g.length).fill(0);if(L!==null){let ee=W&&this instanceof ve?[this.sep]:[],fe=W?[this.sep]:[];g=(0,o.mergeArrays)(g,ee,L,fe),q=(0,o.mergeArrays)(q,new Array(L.length+ee.length+fe.length).fill(1))}return{tokens:g,token_type_ids:q}}}class ve extends le{}class ce extends ge{constructor(g){super(g),this.single=g.single,this.pair=g.pair}post_process(g,L=null,{add_special_tokens:W=!0}={}){let q=L===null?this.single:this.pair,ee=[],fe=[];for(let Le of q)"SpecialToken"in Le?W&&(ee.push(Le.SpecialToken.id),fe.push(Le.SpecialToken.type_id)):"Sequence"in Le&&(Le.Sequence.id==="A"?(ee=(0,o.mergeArrays)(ee,g),fe=(0,o.mergeArrays)(fe,new Array(g.length).fill(Le.Sequence.type_id))):Le.Sequence.id==="B"&&(ee=(0,o.mergeArrays)(ee,L),fe=(0,o.mergeArrays)(fe,new Array(L.length).fill(Le.Sequence.type_id))));return{tokens:ee,token_type_ids:fe}}}class Me extends ge{post_process(g,L=null){return L&&(g=(0,o.mergeArrays)(g,L)),{tokens:g}}}class Re extends ge{constructor(g){super(g),this.processors=g.processors.map(L=>ge.fromConfig(L))}post_process(g,L=null,W={}){let q;for(let ee of this.processors)if(ee instanceof Me)g=ee.post_process(g).tokens,L&&(L=ee.post_process(L).tokens);else{let fe=ee.post_process(g,L,W);g=fe.tokens,q=fe.token_type_ids}return{tokens:g,token_type_ids:q}}}class Ce extends r.Callable{constructor(g){super(),this.config=g,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=g.trim_offsets}static fromConfig(g){if(g===null)return null;switch(g.type){case"WordPiece":return new ze(g);case"Metaspace":return new Vt(g);case"ByteLevel":return new Ae(g);case"Replace":return new Ie(g);case"ByteFallback":return new Fe(g);case"Fuse":return new Je(g);case"Strip":return new Ve(g);case"Sequence":return new Ue(g);case"CTC":return new et(g);case"BPEDecoder":return new lt(g);default:throw new Error(`Unknown Decoder type: ${g.type}`)}}_call(g){return this.decode(g)}decode(g){return this.decode_chain(g).join("")}decode_chain(g){throw Error("`decode_chain` should be implemented in subclass.")}}class Ie extends Ce{decode_chain(g){let L=y(this.config.pattern);return L===null?g:g.map(W=>W.replaceAll(L,this.config.content))}}class Fe extends Ce{constructor(g){super(g),this.text_decoder=new TextDecoder}decode_chain(g){let L=[],W=[];for(let q of g){let ee=null;if(q.length===6&&q.startsWith("<0x")&&q.endsWith(">")){let fe=parseInt(q.slice(3,5),16);isNaN(fe)||(ee=fe)}if(ee!==null)W.push(ee);else{if(W.length>0){let fe=this.text_decoder.decode(Uint8Array.from(W));L.push(fe),W=[]}L.push(q)}}if(W.length>0){let q=this.text_decoder.decode(Uint8Array.from(W));L.push(q),W=[]}return L}}class Je extends Ce{decode_chain(g){return[g.join("")]}}class Ve extends Ce{constructor(g){super(g),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(g){return g.map(L=>{let W=0;for(let ee=0;ee<this.start&&L[ee]===this.content;++ee){W=ee+1;continue}let q=L.length;for(let ee=0;ee<this.stop;++ee){let fe=L.length-ee-1;if(L[fe]===this.content){q=fe;continue}else break}return L.slice(W,q)})}}class ze extends Ce{constructor(g){super(g),this.cleanup=g.cleanup}decode_chain(g){return g.map((L,W)=>(W!==0&&(L.startsWith(this.config.prefix)?L=L.replace(this.config.prefix,""):L=" "+L),this.cleanup&&(L=z(L)),L))}}class Ae extends Ce{constructor(g){super(g),this.byte_decoder=$,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(g){let L=g.join(""),W=new Uint8Array([...L].map(ee=>this.byte_decoder[ee]));return this.text_decoder.decode(W)}decode_chain(g){let L=[],W=[];for(let q of g)this.added_tokens.find(ee=>ee.content===q)!==void 0?(W.length>0&&(L.push(this.convert_tokens_to_string(W)),W=[]),L.push(q)):W.push(q);return W.length>0&&L.push(this.convert_tokens_to_string(W)),L}}class et extends Ce{constructor(g){super(g),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(g){if(g.length===0)return"";let L=[g[0]];for(let ee=1;ee<g.length;++ee)g[ee]!==L.at(-1)&&L.push(g[ee]);let q=L.filter(ee=>ee!==this.pad_token).join("");return this.cleanup&&(q=z(q).replaceAll(this.word_delimiter_token," ").trim()),q}decode_chain(g){return[this.convert_tokens_to_string(g)]}}class Ue extends Ce{constructor(g){super(g),this.decoders=g.decoders.map(L=>Ce.fromConfig(L))}decode_chain(g){return this.decoders.reduce((L,W)=>W.decode_chain(L),g)}}class lt extends Ce{constructor(g){super(g),this.suffix=this.config.suffix}decode_chain(g){return g.map((L,W)=>L.replaceAll(this.suffix,W===g.length-1?"":" "))}}class mt extends Ce{decode_chain(g){let L="";for(let W=1;W<g.length;W+=2)L+=g[W];return[L]}}class bt extends we{constructor(g){super(),this.replacement=g.replacement,this.strRep=g.str_rep||this.replacement,this.prepend_scheme=g.prepend_scheme??"always"}pre_tokenize_text(g,{section_index:L=void 0}={}){let W=g.replaceAll(" ",this.strRep);return!W.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&L===0)&&(W=this.strRep+W),[W]}}class Vt extends Ce{constructor(g){super(g),this.replacement=g.replacement}decode_chain(g){let L=[];for(let W=0;W<g.length;++W){let q=g[W].replaceAll(this.replacement," ");W==0&&q.startsWith(" ")&&(q=q.substring(1)),L.push(q)}return L}}class vt extends oe{constructor(g){super(g),this.charsmap=g.precompiled_charsmap}normalize(g){return g=g.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),g=g.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),g.includes("\uFF5E")?g=g.split("\uFF5E").map(W=>W.normalize("NFKC")).join("\uFF5E"):g=g.normalize("NFKC"),g}}class Ht extends we{constructor(g){super(),this.tokenizers=g.pretokenizers.map(L=>we.fromConfig(L))}pre_tokenize_text(g,L){return this.tokenizers.reduce((W,q)=>q.pre_tokenize(W,L),[g])}}class ls extends we{constructor(g){super()}pre_tokenize_text(g,L){return g.match(/\w+|[^\w\s]+/g)||[]}}class cs extends we{constructor(g){super()}pre_tokenize_text(g,L){return P(g)}}class ds extends we{constructor(g){super(),this.config=g,this.pattern=y(this.config.pattern),this.content=this.config.content}pre_tokenize_text(g,L){return this.pattern===null?[g]:[g.replaceAll(this.pattern,this.config.content)]}}class St extends we{constructor(g){super(),this._length=g.length}pre_tokenize_text(g,L){let W=[];for(let q=0;q<g.length;q+=this._length)W.push(g.slice(q,q+this._length));return W}}let er=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function gr(re,g,L,W){for(let q of Object.keys(re)){let ee=g-re[q].length,fe=L(q),Le=new Array(ee).fill(fe);re[q]=W==="right"?(0,o.mergeArrays)(re[q],Le):(0,o.mergeArrays)(Le,re[q])}}function _s(re,g){for(let L of Object.keys(re))re[L].length=g}class rt extends r.Callable{constructor(L,W){super();v(this,"return_token_type_ids",!1);v(this,"padding_side","right");this.config=W,this.normalizer=oe.fromConfig(L.normalizer),this.pre_tokenizer=we.fromConfig(L.pre_tokenizer),this.model=G.fromConfig(L.model,W),this.post_processor=ge.fromConfig(L.post_processor),this.decoder=Ce.fromConfig(L.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(let q of L.added_tokens){let ee=new O(q);this.added_tokens.push(ee),this.model.tokens_to_ids.set(ee.content,ee.id),this.model.vocab[ee.id]=ee.content,ee.special&&(this.special_tokens.push(ee.content),this.all_special_ids.push(ee.id))}if(this.additional_special_tokens=W.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(q=>q.content)),this.added_tokens_map=new Map(this.added_tokens.map(q=>[q.content,q])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=W.model_max_length,this.remove_space=W.remove_space,this.clean_up_tokenization_spaces=W.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=W.do_lowercase_and_remove_accent??!1,W.padding_side&&(this.padding_side=W.padding_side),this.add_bos_token=W.add_bos_token,this.add_eos_token=W.add_eos_token,this.legacy=!1,this.chat_template=W.chat_template??null,Array.isArray(this.chat_template)){let q=Object.create(null);for(let{name:ee,template:fe}of this.chat_template){if(typeof ee!="string"||typeof fe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');q[ee]=fe}this.chat_template=q}this._compiled_template_cache=new Map}getToken(...L){for(let W of L){let q=this.config[W];if(q)if(typeof q=="object"){if(q.__type==="AddedToken")return q.content;throw Error(`Unknown token: ${q}`)}else return q}return null}static async from_pretrained(L,{progress_callback:W=null,config:q=null,cache_dir:ee=null,local_files_only:fe=!1,revision:Le="main",legacy:We=null}={}){let Be=await f(L,{progress_callback:W,config:q,cache_dir:ee,local_files_only:fe,revision:Le,legacy:We});return new this(...Be)}_call(L,{text_pair:W=null,add_special_tokens:q=!0,padding:ee=!1,truncation:fe=null,max_length:Le=null,return_tensor:We=!0,return_token_type_ids:Be=null}={}){let $e=Array.isArray(L),ot;if($e){if(L.length===0)throw Error("text array must be non-empty");if(W!==null){if(Array.isArray(W)){if(L.length!==W.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");ot=L.map((Tt,It)=>this._encode_plus(Tt,{text_pair:W[It],add_special_tokens:q,return_token_type_ids:Be}))}else ot=L.map(Tt=>this._encode_plus(Tt,{add_special_tokens:q,return_token_type_ids:Be}))}else{if(L==null)throw Error("text may not be null or undefined");if(Array.isArray(W))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");ot=[this._encode_plus(L,{text_pair:W,add_special_tokens:q,return_token_type_ids:Be})]}if(Le===null?Le=this.model_max_length:fe===null&&(ee===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),Le=this.model_max_length):ee===!1&&(console.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."),fe=!0)),ee===!0&&(Le=Math.min((0,h.max)(ot.map(Tt=>Tt.input_ids.length))[0],Le??1/0)),Le=Math.min(Le,this.model_max_length??1/0),ee||fe)for(let Tt=0;Tt<ot.length;++Tt)ot[Tt].input_ids.length!==Le&&(ot[Tt].input_ids.length>Le?fe&&_s(ot[Tt],Le):ee&&gr(ot[Tt],Le,It=>It==="input_ids"?this.pad_token_id:0,this.padding_side));let Mt={};if(We){if(!(ee&&fe)&&ot.some(It=>{for(let Pt of Object.keys(It))if(It[Pt].length!==ot[0][Pt]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let Tt=[ot.length,ot[0].input_ids.length];for(let It of Object.keys(ot[0]))Mt[It]=new u.Tensor("int64",BigInt64Array.from(ot.flatMap(Pt=>Pt[It]).map(BigInt)),Tt)}else{for(let Tt of Object.keys(ot[0]))Mt[Tt]=ot.map(It=>It[Tt]);if(!$e)for(let Tt of Object.keys(Mt))Mt[Tt]=Mt[Tt][0]}return Mt}_encode_text(L){if(L===null)return null;let W=this.added_tokens_splitter.split(L);for(let ee=0;ee<W.length;++ee){let fe=this.added_tokens_map.get(W[ee]);fe&&(fe.lstrip&&ee>0&&(W[ee-1]=W[ee-1].trimEnd()),fe.rstrip&&ee<W.length-1&&(W[ee+1]=W[ee+1].trimStart()))}return W.flatMap((ee,fe)=>{if(ee.length===0)return[];if(this.added_tokens_map.has(ee))return[ee];if(this.remove_space===!0&&(ee=ee.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ee=A(ee)),this.normalizer!==null&&(ee=this.normalizer(ee)),ee.length===0)return[];let Le=this.pre_tokenizer!==null?this.pre_tokenizer(ee,{section_index:fe}):[ee];return this.model(Le)})}_encode_plus(L,{text_pair:W=null,add_special_tokens:q=!0,return_token_type_ids:ee=null}={}){let{tokens:fe,token_type_ids:Le}=this._tokenize_helper(L,{pair:W,add_special_tokens:q}),We=this.model.convert_tokens_to_ids(fe),Be={input_ids:We,attention_mask:new Array(We.length).fill(1)};return(ee??this.return_token_type_ids)&&Le&&(Be.token_type_ids=Le),Be}_tokenize_helper(L,{pair:W=null,add_special_tokens:q=!1}={}){let ee=this._encode_text(L),fe=this._encode_text(W);return this.post_processor?this.post_processor(ee,fe,{add_special_tokens:q}):{tokens:(0,o.mergeArrays)(ee??[],fe??[])}}tokenize(L,{pair:W=null,add_special_tokens:q=!1}={}){return this._tokenize_helper(L,{pair:W,add_special_tokens:q}).tokens}encode(L,{text_pair:W=null,add_special_tokens:q=!0,return_token_type_ids:ee=null}={}){return this._encode_plus(L,{text_pair:W,add_special_tokens:q,return_token_type_ids:ee}).input_ids}batch_decode(L,W={}){return L instanceof u.Tensor&&(L=L.tolist()),L.map(q=>this.decode(q,W))}decode(L,W={}){if(L instanceof u.Tensor&&(L=S(L)),!Array.isArray(L)||L.length===0||!(0,o.isIntegralNumber)(L[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(L,W)}decode_single(L,{skip_special_tokens:W=!1,clean_up_tokenization_spaces:q=null}){let ee=this.model.convert_ids_to_tokens(L);W&&(ee=ee.filter(Le=>!this.special_tokens.includes(Le)));let fe=this.decoder?this.decoder(ee):ee.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(fe=fe.replaceAll(this.decoder.end_of_word_suffix," "),W&&(fe=fe.trim())),(q??this.clean_up_tokenization_spaces)&&(fe=z(fe)),fe}get_chat_template({chat_template:L=null,tools:W=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let q=this.chat_template;if(L!==null&&Object.hasOwn(q,L))L=q[L];else if(L===null)if(W!==null&&"tool_use"in q)L=q.tool_use;else if("default"in q)L=q.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(q).sort()}.`)}else if(L===null)if(this.chat_template)L=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 L}apply_chat_template(L,{tools:W=null,documents:q=null,chat_template:ee=null,add_generation_prompt:fe=!1,tokenize:Le=!0,padding:We=!1,truncation:Be=!1,max_length:$e=null,return_tensor:ot=!0,return_dict:Mt=!1,tokenizer_kwargs:Tt={},...It}={}){if(ee=this.get_chat_template({chat_template:ee,tools:W}),typeof ee!="string")throw Error(`chat_template must be a string, but got ${typeof ee}`);let Pt=this._compiled_template_cache.get(ee);Pt===void 0&&(Pt=new p.Template(ee),this._compiled_template_cache.set(ee,Pt));let tr=Object.create(null);for(let lr of er){let vr=this.getToken(lr);vr&&(tr[lr]=vr)}let rr=Pt.render({messages:L,add_generation_prompt:fe,tools:W,documents:q,...tr,...It});if(Le){let lr=this._call(rr,{add_special_tokens:!1,padding:We,truncation:Be,max_length:$e,return_tensor:ot,...Tt});return Mt?lr:lr.input_ids}return rr}}class Ur extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class zr extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class Wr extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class pr extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class _t extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class Gr extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class m extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class j extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class C extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class R extends rt{}class V extends rt{}class te extends rt{constructor(L,W){super(L,W);v(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class me extends rt{constructor(){super(...arguments);v(this,"return_token_type_ids",!0)}}class Ke extends rt{}class qe extends rt{}class je extends rt{}class st extends rt{constructor(g,L){super(g,L),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(W=>this.languageRegex.test(W)),this.lang_to_token=W=>W}_build_translation_inputs(g,L,W){return mr(this,g,L,W)}}class Ge extends st{}class ct extends rt{}class ft extends rt{}let Qt="\u2581";class Ut extends rt{constructor(L,W){super(L,W);v(this,"padding_side","left");this.legacy=W.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new bt({replacement:Qt,prepend_scheme:"first"}))}_encode_text(L){if(L===null)return null;if(this.legacy||L.length===0)return super._encode_text(L);let W=super._encode_text(Qt+L.replaceAll(Qt," "));return W.length>1&&W[0]===Qt&&this.special_tokens.includes(W[1])&&(W=W.slice(1)),W}}class ar extends rt{}class Xt extends rt{}class Cr extends rt{}class kr extends rt{}class Fr extends rt{}class cr extends rt{}class Kr extends rt{}class Ar extends rt{}class $r extends rt{}function mr(re,g,L,W){if(!("language_codes"in re)||!Array.isArray(re.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in re)||!(re.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in re)||typeof re.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let q=W.src_lang,ee=W.tgt_lang;if(!re.language_codes.includes(ee))throw new Error(`Target language code "${ee}" is not valid. Must be one of: {${re.language_codes.join(", ")}}`);if(q!==void 0){if(!re.language_codes.includes(q))throw new Error(`Source language code "${q}" is not valid. Must be one of: {${re.language_codes.join(", ")}}`);for(let fe of re.post_processor.config.single)if("SpecialToken"in fe&&re.languageRegex.test(fe.SpecialToken.id)){fe.SpecialToken.id=re.lang_to_token(q);break}}return W.forced_bos_token_id=re.model.convert_tokens_to_ids([re.lang_to_token(ee)])[0],re._call(g,L)}class Mr extends rt{constructor(g,L){super(g,L),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(W=>this.languageRegex.test(W)),this.lang_to_token=W=>W}_build_translation_inputs(g,L,W){return mr(this,g,L,W)}}class wr extends rt{constructor(g,L){super(g,L),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(W=>this.languageRegex.test(W)).map(W=>W.slice(2,-2)),this.lang_to_token=W=>`__${W}__`}_build_translation_inputs(g,L,W){return mr(this,g,L,W)}}class Hr extends rt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(g,{return_timestamps:L=!1,return_language:W=!1,time_precision:q=null,force_full_sequences:ee=!0}={}){if(q===null)throw Error("Must specify time_precision");let fe=null,Le=L==="word";function We(){return{language:fe,timestamp:[null,null],text:""}}let Be=[],$e=We(),ot=0,Mt=this.timestamp_begin,It=Mt+1500,Pt=[],tr=[],rr=!1,lr=null,vr=new Set(this.all_special_ids);for(let At of g){let Kt=At.tokens,qt=Le?At.token_timestamps:null,Pr=null,yr=Mt;if("stride"in At){let[zt,Dt,Rt]=At.stride;if(ot-=Dt,lr=zt-Rt,Dt&&(yr=Dt/q+Mt),Rt)for(let Lt=Kt.length-1;Lt>=0;--Lt){let dr=Number(Kt[Lt]);if(dr>=Mt){if(Pr!==null&&(dr-Mt)*q<lr)break;Pr=dr}}}let sr=[],br=[];for(let zt=0;zt<Kt.length;++zt){let Dt=Number(Kt[zt]);if(vr.has(Dt)){let Rt=this.decode([Dt]),Lt=w.WHISPER_LANGUAGE_MAPPING.get(Rt.slice(2,-2));if(Lt!==void 0){if(fe!==null&&Lt!==fe&&!L){Pt.push(sr);let dr=this.findLongestCommonSequence(Pt)[0],us=this.decode(dr);$e.text=us,Be.push($e),Pt=[],sr=[],$e=We()}fe=$e.language=Lt}}else if(Dt>=Mt&&Dt<=It){let Rt=(Dt-Mt)*q+ot,Lt=(0,h.round)(Rt,2);if(Pr!==null&&Dt>=Pr)rr=!0;else if(rr||Pt.length>0&&Dt<yr)rr=!1;else if($e.timestamp[0]===null)$e.timestamp[0]=Lt;else if(Lt!==$e.timestamp[0]){$e.timestamp[1]=Lt,Pt.push(sr),Le&&tr.push(br);let[dr,us]=this.findLongestCommonSequence(Pt,tr),Rr=this.decode(dr);$e.text=Rr,Le&&($e.words=this.collateWordTimestamps(dr,us,fe)),Be.push($e),Pt=[],sr=[],tr=[],br=[],$e=We()}}else if(sr.push(Dt),Le){let Rt=(0,h.round)(qt[zt]+ot,2),Lt;if(zt+1<qt.length){Lt=(0,h.round)(qt[zt+1]+ot,2);let dr=this.decode([Dt]);_.test(dr)&&(Lt=(0,h.round)(Math.min(Rt+q,Lt),2))}else Lt=null;br.push([Rt,Lt])}}if("stride"in At){let[zt,Dt,Rt]=At.stride;ot+=zt-Rt}sr.length>0?(Pt.push(sr),Le&&tr.push(br)):Pt.every(zt=>zt.length===0)&&($e=We(),Pt=[],sr=[],tr=[],br=[])}if(Pt.length>0){if(ee&&L)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.");let[At,Kt]=this.findLongestCommonSequence(Pt,tr),qt=this.decode(At);$e.text=qt,Le&&($e.words=this.collateWordTimestamps(At,Kt,fe)),Be.push($e)}let Jt=Object.create(null),Or=Be.map(At=>At.text).join("");if(L||W){for(let At=0;At<Be.length;++At){let Kt=Be[At];L||delete Kt.timestamp,W||delete Kt.language}if(Le){let At=[];for(let Kt of Be)for(let qt of Kt.words)At.push(qt);Jt={chunks:At}}else Jt={chunks:Be}}return[Or,Jt]}findLongestCommonSequence(g,L=null){let W=g[0],q=W.length,ee=[],fe=Array.isArray(L)&&L.length>0,Le=fe?[]:null,We=fe?L[0]:null;for(let Be=1;Be<g.length;++Be){let $e=g[Be],ot=0,Mt=[q,q,0,0],Tt=$e.length;for(let Jt=1;Jt<q+Tt;++Jt){let Or=Math.max(0,q-Jt),At=Math.min(q,q+Tt-Jt),Kt=W.slice(Or,At),qt=Math.max(0,Jt-q),Pr=Math.min(Tt,Jt),yr=$e.slice(qt,Pr);if(Kt.length!==yr.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let sr;fe?sr=Kt.filter((Dt,Rt)=>Dt===yr[Rt]&&We[Or+Rt]<=L[Be][qt+Rt]).length:sr=Kt.filter((Dt,Rt)=>Dt===yr[Rt]).length;let br=Jt/1e4,zt=sr/Jt+br;sr>1&&zt>ot&&(ot=zt,Mt=[Or,At,qt,Pr])}let[It,Pt,tr,rr]=Mt,lr=Math.floor((Pt+It)/2),vr=Math.floor((rr+tr)/2);ee.push(...W.slice(0,lr)),W=$e.slice(vr),q=W.length,fe&&(Le.push(...We.slice(0,lr)),We=L[Be].slice(vr))}return ee.push(...W),fe?(Le.push(...We),[ee,Le]):[ee,[]]}collateWordTimestamps(g,L,W){let[q,ee,fe]=this.combineTokensIntoWords(g,W),Le=[];for(let We=0;We<q.length;++We){let Be=fe[We];Le.push({text:q[We],timestamp:[L[Be.at(0)][0],L[Be.at(-1)][1]]})}return Le}combineTokensIntoWords(g,L,W=`"'\u201C\xA1\xBF([{-`,q=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){L=L??"english";let ee,fe,Le;return["chinese","japanese","thai","lao","myanmar"].includes(L)?[ee,fe,Le]=this.splitTokensOnUnicode(g):[ee,fe,Le]=this.splitTokensOnSpaces(g),this.mergePunctuations(ee,fe,Le,W,q)}decode(g,L){let W;return L?.decode_with_timestamps?(g instanceof u.Tensor&&(g=S(g)),W=this.decodeWithTimestamps(g,L)):W=super.decode(g,L),W}decodeWithTimestamps(g,L){let W=L?.time_precision??.02,q=Array.from(this.all_special_ids).at(-1)+1,ee=[[]];for(let fe of g)if(fe=Number(fe),fe>=q){let Le=((fe-q)*W).toFixed(2);ee.push(`<|${Le}|>`),ee.push([])}else ee[ee.length-1].push(fe);return ee=ee.map(fe=>typeof fe=="string"?fe:super.decode(fe,L)),ee.join("")}splitTokensOnUnicode(g){let L=this.decode(g,{decode_with_timestamps:!0}),W="\uFFFD",q=[],ee=[],fe=[],Le=[],We=[],Be=0;for(let $e=0;$e<g.length;++$e){let ot=g[$e];Le.push(ot),We.push($e);let Mt=this.decode(Le,{decode_with_timestamps:!0});(!Mt.includes(W)||L[Be+Mt.indexOf(W)]===W)&&(q.push(Mt),ee.push(Le),fe.push(We),Le=[],We=[],Be+=Mt.length)}return[q,ee,fe]}splitTokensOnSpaces(g){let[L,W,q]=this.splitTokensOnUnicode(g),ee=[],fe=[],Le=[],We=new RegExp(`^[${D}]$`,"gu");for(let Be=0;Be<L.length;++Be){let $e=L[Be],ot=W[Be],Mt=q[Be],Tt=ot[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),It=$e.startsWith(" "),Pt=$e.trim(),tr=We.test(Pt);if(Tt||It||tr||ee.length===0)ee.push($e),fe.push(ot),Le.push(Mt);else{let rr=ee.length-1;ee[rr]+=$e,fe[rr].push(...ot),Le[rr].push(...Mt)}}return[ee,fe,Le]}mergePunctuations(g,L,W,q,ee){let fe=structuredClone(g),Le=structuredClone(L),We=structuredClone(W),Be=fe.length-2,$e=fe.length-1;for(;Be>=0;)fe[Be].startsWith(" ")&&q.includes(fe[Be].trim())?(fe[$e]=fe[Be]+fe[$e],Le[$e]=(0,o.mergeArrays)(Le[Be],Le[$e]),We[$e]=(0,o.mergeArrays)(We[Be],We[$e]),fe[Be]="",Le[Be]=[],We[Be]=[]):$e=Be,--Be;for(Be=0,$e=1;$e<fe.length;)!fe[Be].endsWith(" ")&&ee.includes(fe[$e])?(fe[Be]+=fe[$e],Le[Be]=(0,o.mergeArrays)(Le[Be],Le[$e]),We[Be]=(0,o.mergeArrays)(We[Be],We[$e]),fe[$e]="",Le[$e]=[],We[$e]=[]):Be=$e,++$e;return[fe.filter(ot=>ot),Le.filter(ot=>ot.length>0),We.filter(ot=>ot.length>0)]}}class Ir extends rt{}class Sr extends rt{}class Dr extends rt{}class Tr extends rt{constructor(g,L){super(g,L),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(W=>this.languageRegex.test(W)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(g){if(g===null)return null;let[L,...W]=g.trim().split(this.languageRegex);if(W.length===0)return super._encode_text(L);if(W.length===2){let[q,ee]=W;return this.supported_language_codes.includes(q)||console.warn(`Unsupported language code "${q}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([q],super._encode_text(ee))}}}class ir extends rt{}class ke extends rt{}class De extends rt{}class Qe extends rt{}class xt extends rt{}class Qr extends rt{constructor(g,L){super(g,L),this.decoder=new mt({})}}class Lr extends rt{}class Xr extends rt{}class Is{static async from_pretrained(g,{progress_callback:L=null,config:W=null,cache_dir:q=null,local_files_only:ee=!1,revision:fe="main",legacy:Le=null}={}){let[We,Be]=await f(g,{progress_callback:L,config:W,cache_dir:q,local_files_only:ee,revision:fe,legacy:Le}),$e=Be.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",ot=this.TOKENIZER_CLASS_MAPPING[$e];return ot||(console.warn(`Unknown tokenizer class "${$e}", attempting to construct from base class.`),ot=rt),new ot(We,Be)}}v(Is,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Ke,DistilBertTokenizer:R,CamembertTokenizer:V,DebertaTokenizer:_t,DebertaV2Tokenizer:Gr,BertTokenizer:Ur,HerbertTokenizer:m,ConvBertTokenizer:j,RoFormerTokenizer:C,XLMTokenizer:te,ElectraTokenizer:me,MobileBertTokenizer:Wr,SqueezeBertTokenizer:pr,AlbertTokenizer:zr,GPT2Tokenizer:qe,BartTokenizer:je,MBartTokenizer:st,MBart50Tokenizer:Ge,RobertaTokenizer:ct,WhisperTokenizer:Hr,CodeGenTokenizer:Ir,CLIPTokenizer:Sr,SiglipTokenizer:Dr,MarianTokenizer:Tr,BloomTokenizer:ft,NllbTokenizer:Mr,M2M100Tokenizer:wr,LlamaTokenizer:Ut,CodeLlamaTokenizer:ar,XLMRobertaTokenizer:Xt,MPNetTokenizer:Cr,FalconTokenizer:kr,GPTNeoXTokenizer:Fr,EsmTokenizer:cr,Wav2Vec2CTCTokenizer:ir,BlenderbotTokenizer:ke,BlenderbotSmallTokenizer:De,SpeechT5Tokenizer:Qe,NougatTokenizer:xt,VitsTokenizer:Qr,Qwen2Tokenizer:Kr,GemmaTokenizer:Ar,Grok1Tokenizer:$r,CohereTokenizer:Lr,MgpstrTokenizer:Xr,PreTrainedTokenizer:rt})},"./src/utils/audio.js":(d,t,e)=>{e.r(t),e.d(t,{RawAudio:()=>U,hamming:()=>i,hanning:()=>f,mel_filter_bank:()=>N,read_audio:()=>p,spectrogram:()=>M,window_function:()=>I});var r=e("./src/utils/hub.js"),o=e("./src/utils/maths.js"),a=e("./src/utils/core.js"),h=e("./src/env.js"),u=e("./src/utils/tensor.js"),l=e("?7992");async function p(B,Q){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let $=await(await(0,r.getFile)(B)).arrayBuffer(),Y=new AudioContext({sampleRate:Q});typeof Q>"u"&&console.warn(`No sampling rate provided, using default of ${Y.sampleRate}Hz.`);let se=await Y.decodeAudioData($),oe;if(se.numberOfChannels===2){let ue=Math.sqrt(2),be=se.getChannelData(0),pe=se.getChannelData(1);oe=new Float32Array(be.length);for(let J=0;J<se.length;++J)oe[J]=ue*(be[J]+pe[J])/2}else oe=se.getChannelData(0);return oe}function w(B,Q){if(B<1)return new Float64Array;if(B===1)return new Float64Array([1]);let $=1-Q,Y=2*Math.PI/(B-1),se=new Float64Array(B);for(let oe=0;oe<B;++oe)se[oe]=Q-$*Math.cos(oe*Y);return se}function f(B){return w(B,.5)}function i(B){return w(B,.54)}let y={htk:B=>2595*Math.log10(1+B/700),kaldi:B=>1127*Math.log(1+B/700),slaney:(B,Q=1e3,$=15,Y=27/Math.log(6.4))=>B>=Q?$+Math.log(B/Q)*Y:3*B/200};function E(B,Q="htk"){let $=y[Q];if(!$)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?$(B):B.map(Y=>$(Y))}let S={htk:B=>700*(10**(B/2595)-1),kaldi:B=>700*(Math.exp(B/1127)-1),slaney:(B,Q=1e3,$=15,Y=Math.log(6.4)/27)=>B>=$?Q*Math.exp(Y*(B-$)):200*B/3};function z(B,Q="htk"){let $=S[Q];if(!$)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?$(B):B.map(Y=>$(Y))}function k(B,Q){let $=Float64Array.from({length:Q.length-1},(ue,be)=>Q[be+1]-Q[be]),Y=Array.from({length:B.length},()=>new Array(Q.length));for(let ue=0;ue<B.length;++ue){let be=Y[ue];for(let pe=0;pe<Q.length;++pe)be[pe]=Q[pe]-B[ue]}let se=Q.length-2,oe=Array.from({length:se},()=>new Array(B.length));for(let ue=0;ue<B.length;++ue){let be=Y[ue];for(let pe=0;pe<se;++pe){let J=-be[pe]/$[pe],F=be[pe+2]/$[pe+1];oe[pe][ue]=Math.max(0,Math.min(J,F))}}return oe}function A(B,Q,$){let Y=(Q-B)/($-1);return Float64Array.from({length:$},(se,oe)=>B+Y*oe)}function N(B,Q,$,Y,se,oe=null,ue="htk",be=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(B<2)throw new Error(`Require num_frequency_bins: ${B} >= 2`);if($>Y)throw new Error(`Require min_frequency: ${$} <= max_frequency: ${Y}`);let pe=E($,ue),J=E(Y,ue),F=A(pe,J,Q+2),K=z(F,ue),Z;if(be){let xe=se/((B-1)*2);Z=E(Float64Array.from({length:B},(ye,Oe)=>Oe*xe),ue),K=F}else Z=A(0,Math.floor(se/2),B);let ie=k(Z,K);if(oe!==null&&oe==="slaney")for(let xe=0;xe<Q;++xe){let ye=ie[xe],Oe=2/(K[xe+2]-K[xe]);for(let He=0;He<B;++He)ye[He]*=Oe}return ie}function x(B,Q,$){let Y=new B.constructor(B.length+Q+$),se=B.length-1;for(let oe=0;oe<B.length;++oe)Y[Q+oe]=B[oe];for(let oe=1;oe<=Q;++oe)Y[Q-oe]=B[(0,a.calculateReflectOffset)(oe,se)];for(let oe=1;oe<=$;++oe)Y[se+Q+oe]=B[(0,a.calculateReflectOffset)(se-oe,se)];return Y}function P(B,Q,$,Y,se){if($<=0)throw new Error("reference must be greater than zero");if(Y<=0)throw new Error("min_value must be greater than zero");$=Math.max(Y,$);let oe=Math.log10($);for(let ue=0;ue<B.length;++ue)B[ue]=Q*Math.log10(Math.max(Y,B[ue])-oe);if(se!==null){if(se<=0)throw new Error("db_range must be greater than zero");let ue=(0,o.max)(B)[0]-se;for(let be=0;be<B.length;++be)B[be]=Math.max(B[be],ue)}return B}function D(B,Q=1,$=1e-5,Y=null){return P(B,20,Q,$,Y)}function _(B,Q=1,$=1e-10,Y=null){return P(B,10,Q,$,Y)}async function M(B,Q,$,Y,{fft_length:se=null,power:oe=1,center:ue=!0,pad_mode:be="reflect",onesided:pe=!0,preemphasis:J=null,preemphasis_htk_flavor:F=!0,mel_filters:K=null,mel_floor:Z=1e-10,log_mel:ie=null,reference:xe=1,min_value:ye=1e-10,db_range:Oe=null,remove_dc_offset:He=null,min_num_frames:we=null,max_num_frames:T=null,do_pad:X=!0,transpose:de=!1,mel_offset:he=0}={}){let Te=Q.length;if(se===null&&(se=$),$>se)throw Error(`frame_length (${$}) may not be larger than fft_length (${se})`);if(Te!==$)throw new Error(`Length of the window (${Te}) must equal frame_length (${$})`);if(Y<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&K!==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(!F)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(ue)switch(be){case"reflect":{let ze=Math.floor((se-1)/2)+1;B=x(B,ze,ze);break}case"constant":{let ze=Math.floor(se/2),Ae=new B.constructor(B.length+2*ze);Ae.set(B,ze),B=Ae;break}default:throw new Error(`pad_mode="${be}" not implemented yet.`)}let ge=Math.floor(1+Math.floor((B.length-$)/Y));we!==null&&ge<we&&(ge=we);let le=pe?Math.floor(se/2)+1:se,ve=ge,ce=ge;T!==null&&(T>ge?X&&(ce=T):ce=ve=T);let Me=new o.FFT(se),Re=new Float64Array(se),Ce=new Float64Array(Me.outputBufferSize),Ie=new Float32Array(le*ce);for(let ze=0;ze<ve;++ze){let Ae=ze*Y,et=Math.min(B.length-Ae,$);et!==$&&Re.fill(0,0,$);for(let Ue=0;Ue<et;++Ue)Re[Ue]=B[Ae+Ue];if(He){let Ue=0;for(let mt=0;mt<et;++mt)Ue+=Re[mt];let lt=Ue/et;for(let mt=0;mt<et;++mt)Re[mt]-=lt}if(J!==null){for(let Ue=et-1;Ue>=1;--Ue)Re[Ue]-=J*Re[Ue-1];Re[0]*=1-J}for(let Ue=0;Ue<Q.length;++Ue)Re[Ue]*=Q[Ue];Me.realTransform(Ce,Re);for(let Ue=0;Ue<le;++Ue){let lt=Ue<<1;Ie[Ue*ce+ze]=Ce[lt]**2+Ce[lt+1]**2}}if(oe!==null&&oe!==2){let ze=oe/2;for(let Ae=0;Ae<Ie.length;++Ae)Ie[Ae]**=ze}let Fe=K.length,Je=await(0,u.matmul)(new u.Tensor("float32",K.flat(),[Fe,le]),new u.Tensor("float32",Ie,[le,ce]));de&&(Je=Je.transpose(1,0));let Ve=Je.data;for(let ze=0;ze<Ve.length;++ze)Ve[ze]=he+Math.max(Z,Ve[ze]);if(oe!==null&&ie!==null){let ze=Math.min(Ve.length,ve*Fe);switch(ie){case"log":for(let Ae=0;Ae<ze;++Ae)Ve[Ae]=Math.log(Ve[Ae]);break;case"log10":for(let Ae=0;Ae<ze;++Ae)Ve[Ae]=Math.log10(Ve[Ae]);break;case"dB":if(oe===1)D(Ve,xe,ye,Oe);else if(oe===2)_(Ve,xe,ye,Oe);else throw new Error(`Cannot use log_mel option '${ie}' with power ${oe}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${ie}'`)}}return Je}function I(B,Q,{periodic:$=!0,frame_length:Y=null,center:se=!0}={}){let oe=$?B+1:B,ue;switch(Q){case"boxcar":ue=new Float64Array(oe).fill(1);break;case"hann":case"hann_window":ue=f(oe);break;case"hamming":ue=i(oe);break;case"povey":ue=f(oe).map(be=>Math.pow(be,.85));break;default:throw new Error(`Unknown window type ${Q}.`)}if($&&(ue=ue.subarray(0,B)),Y===null)return ue;if(B>Y)throw new Error(`Length of the window (${B}) may not be larger than frame_length (${Y})`);return ue}function O(B,Q){let $=44,Y=new ArrayBuffer($+B.length*4),se=new DataView(Y);G(se,0,"RIFF"),se.setUint32(4,36+B.length*4,!0),G(se,8,"WAVE"),G(se,12,"fmt "),se.setUint32(16,16,!0),se.setUint16(20,3,!0),se.setUint16(22,1,!0),se.setUint32(24,Q,!0),se.setUint32(28,Q*4,!0),se.setUint16(32,4,!0),se.setUint16(34,32,!0),G(se,36,"data"),se.setUint32(40,B.length*4,!0);for(let oe=0;oe<B.length;++oe,$+=4)se.setFloat32($,B[oe],!0);return Y}function G(B,Q,$){for(let Y=0;Y<$.length;++Y)B.setUint8(Q+Y,$.charCodeAt(Y))}class U{constructor(Q,$){this.audio=Q,this.sampling_rate=$}toWav(){return O(this.audio,this.sampling_rate)}toBlob(){let Q=this.toWav();return new Blob([Q],{type:"audio/wav"})}async save(Q){let $;if(h.apis.IS_BROWSER_ENV){if(h.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");$=a.saveBlob}else if(h.apis.IS_FS_AVAILABLE)$=async(Y,se)=>{let oe=await se.arrayBuffer();l.writeFileSync(Y,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await $(Q,this.toBlob())}}},"./src/utils/constants.js":(d,t,e)=>{e.r(t),e.d(t,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>a,GENERATION_CONFIG_NAME:()=>p,GITHUB_ISSUE_URL:()=>r,IMAGE_PROCESSOR_NAME:()=>h,PROCESSOR_NAME:()=>u});let r="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",a="preprocessor_config.json",h=a,u="processor_config.json",l="chat_template.jinja",p="generation_config.json"},"./src/utils/core.js":(d,t,e)=>{e.r(t),e.d(t,{calculateDimensions:()=>p,calculateReflectOffset:()=>y,count:()=>k,dispatchCallback:()=>r,escapeRegExp:()=>a,isIntegralNumber:()=>u,isNullishDimension:()=>l,isTypedArray:()=>h,len:()=>z,mergeArrays:()=>f,pick:()=>S,pop:()=>w,product:()=>i,reverseDictionary:()=>o,saveBlob:()=>E});function r(A,N){A&&A(N)}function o(A){return Object.fromEntries(Object.entries(A).map(([N,x])=>[x,N]))}function a(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h(A){return A?.prototype?.__proto__?.constructor?.name==="TypedArray"}function u(A){return Number.isInteger(A)||typeof A=="bigint"}function l(A){return A==null||A===-1}function p(A){let N=[],x=A;for(;Array.isArray(x);)N.push(x.length),x=x[0];return N}function w(A,N,x=void 0){let P=A[N];if(P!==void 0)return delete A[N],P;if(x===void 0)throw Error(`Key ${N} does not exist in object.`);return x}function f(...A){return Array.prototype.concat.apply([],A)}function i(...A){return A.reduce((N,x)=>N.flatMap(P=>x.map(D=>[P,D])))}function y(A,N){return Math.abs((A+N)%(2*N)-N)}function E(A,N){let x=URL.createObjectURL(N),P=document.createElement("a");P.href=x,P.download=A,P.click(),P.remove(),URL.revokeObjectURL(x)}function S(A,N){return Object.assign({},...N.map(x=>{if(A[x]!==void 0)return{[x]:A[x]}}))}function z(A){let N=0;for(let x of A)++N;return N}function k(A,N){let x=0;for(let P of A)P===N&&++x;return x}},"./src/utils/data-structures.js":(d,t,e)=>{e.r(t),e.d(t,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>p,PriorityQueue:()=>r,TokenLattice:()=>h});class r{constructor(f=(y,E)=>y>E,i=1/0){this._heap=[],this._comparator=f,this._maxSize=i}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...f){return this.extend(f)}extend(f){for(let i of f)if(this.size<this._maxSize)this._heap.push(i),this._siftUp();else{let y=this._smallest();this._comparator(i,this._heap[y])&&(this._heap[y]=i,this._siftUpFrom(y))}return this.size}pop(){let f=this.peek(),i=this.size-1;return i>0&&this._swap(0,i),this._heap.pop(),this._siftDown(),f}replace(f){let i=this.peek();return this._heap[0]=f,this._siftDown(),i}_parent(f){return(f+1>>>1)-1}_left(f){return(f<<1)+1}_right(f){return f+1<<1}_greater(f,i){return this._comparator(this._heap[f],this._heap[i])}_swap(f,i){let y=this._heap[f];this._heap[f]=this._heap[i],this._heap[i]=y}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(f){for(;f>0&&this._greater(f,this._parent(f));)this._swap(f,this._parent(f)),f=this._parent(f)}_siftDown(){let f=0;for(;this._left(f)<this.size&&this._greater(this._left(f),f)||this._right(f)<this.size&&this._greater(this._right(f),f);){let i=this._right(f)<this.size&&this._greater(this._right(f),this._left(f))?this._right(f):this._left(f);this._swap(f,i),f=i}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}}class o{constructor(){this.root=a.default()}extend(f){for(let i of f)this.push(i)}push(f){let i=this.root;for(let y of f){let E=i.children.get(y);E===void 0&&(E=a.default(),i.children.set(y,E)),i=E}i.isLeaf=!0}*commonPrefixSearch(f){let i=this.root;if(i===void 0)return;let y="";for(let E of f){if(y+=E,i=i.children.get(E),i===void 0)return;i.isLeaf&&(yield y)}}}class a{constructor(f,i){this.isLeaf=f,this.children=i}static default(){return new a(!1,new Map)}}class h{constructor(f,i,y){this.chars=Array.from(f),this.len=this.chars.length,this.bosTokenId=i,this.eosTokenId=y,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},()=>[]),this.endNodes=Array.from({length:this.len+1},()=>[]);let E=new u(this.bosTokenId,0,0,0,0),S=new u(this.eosTokenId,1,this.len,0,0);this.nodes.push(E.clone()),this.nodes.push(S.clone()),this.beginNodes[this.len].push(S),this.endNodes[0].push(E)}insert(f,i,y,E){let S=this.nodes.length,z=new u(E,S,f,i,y);this.beginNodes[f].push(z),this.endNodes[f+i].push(z),this.nodes.push(z)}viterbi(){let f=this.len,i=0;for(;i<=f;){if(this.beginNodes[i].length==0)return[];for(let k of this.beginNodes[i]){k.prev=null;let A=0,N=null;for(let x of this.endNodes[i]){let P=x.backtraceScore+k.score;(N===null||P>A)&&(N=x.clone(),A=P)}if(N!==null)k.prev=N,k.backtraceScore=A;else return[]}++i}let y=[],S=this.beginNodes[f][0].prev;if(S===null)return[];let z=S.clone();for(;z.prev!==null;)y.push(z.clone()),z=z.clone().prev.clone();return y.reverse(),y}piece(f){return this.chars.slice(f.pos,f.pos+f.length).join("")}tokens(){return this.viterbi().map(i=>this.piece(i))}tokenIds(){return this.viterbi().map(i=>i.tokenId)}}class u{constructor(f,i,y,E,S){this.tokenId=f,this.nodeId=i,this.pos=y,this.length=E,this.score=S,this.prev=null,this.backtraceScore=0}clone(){let f=new u(this.tokenId,this.nodeId,this.pos,this.length,this.score);return f.prev=this.prev,f.backtraceScore=this.backtraceScore,f}}class l{constructor(f){this.trie=this._buildTrie(f)}_buildTrie(f){var y;let i=Object.create(null);for(let E of f){let S=i;for(let z=0;z<E.length;++z)S=S[y=E[z]]??(S[y]=Object.create(null));S.end=E}return i}split(f){let i=[],y=f.length,E=0,S=0;for(;S<y;){let z=this.trie,k=null,A=S;for(;A<y&&(z=z[f[A]]);)z.end&&(k=z.end),++A;k?(S>E&&i.push(f.slice(E,S)),i.push(k),S+=k.length,E=S):++S}return E<y&&i.push(f.slice(E)),i}}class p{constructor(f){this.capacity=f,this.cache=new Map}get(f){if(!this.cache.has(f))return;let i=this.cache.get(f);return this.cache.delete(f),this.cache.set(f,i),i}put(f,i){this.cache.has(f)&&this.cache.delete(f),this.cache.set(f,i),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(d,t,e)=>{e.r(t),e.d(t,{DEVICE_TYPES:()=>r});let r=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(d,t,e)=>{e.r(t),e.d(t,{DATA_TYPES:()=>h,DEFAULT_DEVICE_DTYPE_MAPPING:()=>u,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>a});var r=e("./src/env.js"),o=e("./src/utils/devices.js");let a=function(){let p;return async function(){if(p===void 0)if(!r.apis.IS_WEBGPU_AVAILABLE)p=!1;else try{p=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{p=!1}return p}}(),h=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),u=Object.freeze({[o.DEVICE_TYPES.wasm]:h.q8}),l=Object.freeze({[h.fp32]:"",[h.fp16]:"_fp16",[h.int8]:"_int8",[h.uint8]:"_uint8",[h.q8]:"_quantized",[h.q4]:"_q4",[h.q4f16]:"_q4f16",[h.bnb4]:"_bnb4"})},"./src/utils/generic.js":(d,t,e)=>{e.r(t),e.d(t,{Callable:()=>r});let r=class{constructor(){let o=function(...a){return o._call(...a)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(d,t,e)=>{e.r(t),e.d(t,{MAX_EXTERNAL_DATA_CHUNKS:()=>u,getFile:()=>y,getModelFile:()=>A,getModelJSON:()=>x,getModelText:()=>N});var r=e("?7992"),o=e("?5af5"),a=e("./src/env.js"),h=e("./src/utils/core.js");let u=100,l={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"};class p{constructor(M){if(this.filePath=M,this.headers=new Headers,this.exists=r.existsSync(M),this.exists){this.status=200,this.statusText="OK";let I=r.statSync(M);this.headers.set("content-length",I.size.toString()),this.updateContentType();let O=r.createReadStream(M);this.body=new ReadableStream({start(G){O.on("data",U=>G.enqueue(U)),O.on("end",()=>G.close()),O.on("error",U=>G.error(U))},cancel(){O.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let M=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[M]??"application/octet-stream")}clone(){let M=new p(this.filePath);return M.exists=this.exists,M.status=this.status,M.statusText=this.statusText,M.headers=new Headers(this.headers),M}async arrayBuffer(){return(await r.promises.readFile(this.filePath)).buffer}async blob(){let M=await r.promises.readFile(this.filePath);return new Blob([M],{type:this.headers.get("content-type")})}async text(){return await r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function w(_,M=null,I=null){let O;try{O=new URL(_)}catch{return!1}return!(M&&!M.includes(O.protocol)||I&&!I.includes(O.hostname))}let f=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function i(_){return!(!f.test(_)||_.includes("..")||_.includes("--")||_.endsWith(".git")||_.endsWith(".ipynb"))}async function y(_){if(a.env.useFS&&!w(_,["http:","https:","blob:"]))return new p(_ instanceof URL?_.protocol==="file:"?_.pathname:_.toString():_);if(typeof process<"u"&&process?.release?.name==="node"){let M=!!process.env?.TESTING_REMOTELY,I=a.env.version,O=new Headers;if(O.set("User-Agent",`transformers.js/${I}; is_ci/${M};`),w(_,["http:","https:"],["huggingface.co","hf.co"])){let U=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;U&&O.set("Authorization",`Bearer ${U}`)}return fetch(_,{headers:O})}else return fetch(_)}let E={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"};function S(_,M,I){if(!I)return null;let O=E[_]??`Error (${_}) occurred while trying to load file`;throw Error(`${O}: "${M}".`)}class z{constructor(M){this.path=M}async match(M){let I=o.join(this.path,M),O=new p(I);if(O.exists)return O}async put(M,I,O=void 0){let G=o.join(this.path,M);try{let U=I.headers.get("Content-Length"),B=parseInt(U??"0"),Q=0;await r.promises.mkdir(o.dirname(G),{recursive:!0});let $=r.createWriteStream(G),Y=I.body.getReader();for(;;){let{done:se,value:oe}=await Y.read();if(se)break;await new Promise((be,pe)=>{$.write(oe,J=>{if(J){pe(J);return}be()})}),Q+=oe.length;let ue=B?Q/B*100:0;O?.({progress:ue,loaded:Q,total:B})}$.close()}catch(U){try{await r.promises.unlink(G)}catch{}throw U}}}async function k(_,...M){for(let I of M)try{let O=await _.match(I);if(O)return O}catch{continue}}async function A(_,M,I=!0,O={},G=!1){if(!a.env.allowLocalModels){if(O.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(!a.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,h.dispatchCallback)(O.progress_callback,{status:"initiate",name:_,file:M});let U;if(!U&&a.env.useCustomCache){if(!a.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!a.env.customCache.match||!a.env.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");U=a.env.customCache}if(!U&&a.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{U=await caches.open("transformers-cache")}catch(Z){console.warn("An error occurred while opening the browser cache:",Z)}}if(!U&&a.env.useFSCache){if(!a.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");U=new z(O.cache_dir??a.env.cacheDir)}let B=O.revision??"main",Q=D(_,M),$=i(_),Y=$?D(a.env.localModelPath,Q):Q,se=D(a.env.remoteHost,a.env.remotePathTemplate.replaceAll("{model}",_).replaceAll("{revision}",encodeURIComponent(B)),M),oe,ue=U instanceof z?B==="main"?Q:D(_,B,M):se,be=!1,pe;U&&(pe=await k(U,Y,ue));let J=pe!==void 0;if(pe===void 0){if(a.env.allowLocalModels)if(w(Q,["http:","https:"])){if(O.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Q}.`);if(!a.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Q}.`)}else try{pe=await y(Y),oe=Y}catch(ie){console.warn(`Unable to load from local path "${Y}": "${ie}"`)}if(pe===void 0||pe.status===404){if(O.local_files_only||!a.env.allowRemoteModels){if(I)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Y}".`);return null}if(!$)throw Error(`Local file missing at "${Y}" and download aborted due to invalid model ID "${_}".`);if(pe=await y(se),pe.status!==200)return S(pe.status,se,I);oe=ue}be=U&&typeof Response<"u"&&pe instanceof Response&&pe.status===200}(0,h.dispatchCallback)(O.progress_callback,{status:"download",name:_,file:M});let F;if(!(a.apis.IS_NODE_ENV&&G)){let Z;O.progress_callback?J&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Z=new Uint8Array(await pe.arrayBuffer()),(0,h.dispatchCallback)(O.progress_callback,{status:"progress",name:_,file:M,progress:100,loaded:Z.length,total:Z.length})):Z=await P(pe,ie=>{(0,h.dispatchCallback)(O.progress_callback,{status:"progress",name:_,file:M,...ie})}):Z=new Uint8Array(await pe.arrayBuffer()),F=Z}if(be&&oe&&await U.match(oe)===void 0)if(F)await U.put(oe,new Response(F,{headers:pe.headers})).catch(Z=>{console.warn(`Unable to add response to browser cache: ${Z}.`)});else{let Z=O.progress_callback?ie=>(0,h.dispatchCallback)(O.progress_callback,{status:"progress",name:_,file:M,...ie}):void 0;await U.put(oe,pe,Z)}if((0,h.dispatchCallback)(O.progress_callback,{status:"done",name:_,file:M}),F){if(!a.apis.IS_NODE_ENV&&G)throw new Error("Cannot return path in a browser environment.");return F}if(pe instanceof p)return pe.filePath;let K=await U?.match(oe);if(K instanceof p)return K.filePath;if(K instanceof Response)return new Uint8Array(await K.arrayBuffer());if(typeof K=="string")return K;throw new Error("Unable to get model file path or buffer.")}async function N(_,M,I=!0,O={}){let G=await A(_,M,I,O,!1);return G===null?null:new TextDecoder("utf-8").decode(G)}async function x(_,M,I=!0,O={}){let G=await N(_,M,I,O);return G===null?{}:JSON.parse(G)}async function P(_,M){let I=_.headers.get("Content-Length");I===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let O=parseInt(I??"0"),G=new Uint8Array(O),U=0,B=_.body.getReader();async function Q(){let{done:$,value:Y}=await B.read();if($)return;let se=U+Y.length;if(se>O){O=se;let ue=new Uint8Array(O);ue.set(G),G=ue}G.set(Y,U),U=se;let oe=U/O*100;return M({progress:oe,loaded:U,total:O}),Q()}return await Q(),G}function D(..._){return _=_.map((M,I)=>(I&&(M=M.replace(new RegExp("^/"),"")),I!==_.length-1&&(M=M.replace(new RegExp("/$"),"")),M)),_.join("/")}},"./src/utils/image.js":(d,t,e)=>{e.r(t),e.d(t,{RawImage:()=>E,load_image:()=>S});var r=e("./src/utils/core.js"),o=e("./src/utils/hub.js"),a=e("./src/env.js"),h=e("./src/utils/tensor.js"),u=e("?2b25");let l,p,w,f=a.apis.IS_BROWSER_ENV||a.apis.IS_WEBWORKER_ENV;if(f)l=(z,k)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(z,k)},w=self.createImageBitmap,p=self.ImageData;else if(u)w=async z=>{let A=(await z.metadata()).channels,{data:N,info:x}=await z.rotate().raw().toBuffer({resolveWithObject:!0}),P=new E(new Uint8ClampedArray(N),x.width,x.height,x.channels);return A!==void 0&&A!==x.channels&&P.convert(A),P};else throw new Error("Unable to load image processing library.");let i={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},y=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class E{constructor(k,A,N,x){this.data=k,this.width=A,this.height=N,this.channels=x}get size(){return[this.width,this.height]}static async read(k){if(k instanceof E)return k;if(typeof k=="string"||k instanceof URL)return await this.fromURL(k);if(k instanceof Blob)return await this.fromBlob(k);if(typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&k instanceof OffscreenCanvas)return this.fromCanvas(k);throw new Error(`Unsupported input type: ${typeof k}`)}static fromCanvas(k){if(!f)throw new Error("fromCanvas() is only supported in browser environments.");let N=k.getContext("2d").getImageData(0,0,k.width,k.height).data;return new E(N,k.width,k.height,4)}static async fromURL(k){let A=await(0,o.getFile)(k);if(A.status!==200)throw new Error(`Unable to read image from "${k}" (${A.status} ${A.statusText})`);let N=await A.blob();return this.fromBlob(N)}static async fromBlob(k){if(f){let A=await w(k),N=l(A.width,A.height).getContext("2d");return N.drawImage(A,0,0),new this(N.getImageData(0,0,A.width,A.height).data,A.width,A.height,4)}else{let A=u(await k.arrayBuffer());return await w(A)}}static fromTensor(k,A="CHW"){if(k.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${k.dims.length} dimensions.`);if(A==="CHW")k=k.transpose(1,2,0);else if(A!=="HWC")throw new Error(`Unsupported channel format: ${A}`);if(!(k.data instanceof Uint8ClampedArray||k.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${k.type}`);switch(k.dims[2]){case 1:case 2:case 3:case 4:return new E(k.data,k.dims[1],k.dims[0],k.dims[2]);default:throw new Error(`Unsupported number of channels: ${k.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let k=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let A=0,N=0;A<this.data.length;A+=this.channels){let x=this.data[A],P=this.data[A+1],D=this.data[A+2];k[N++]=Math.round(.2989*x+.587*P+.114*D)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(k,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let k=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let A=0,N=0;A<this.data.length;++A)k[N++]=this.data[A],k[N++]=this.data[A],k[N++]=this.data[A];break;case 4:for(let A=0,N=0;A<this.data.length;A+=4)k[N++]=this.data[A],k[N++]=this.data[A+1],k[N++]=this.data[A+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(k,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let k=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let A=0,N=0;A<this.data.length;++A)k[N++]=this.data[A],k[N++]=this.data[A],k[N++]=this.data[A],k[N++]=255;break;case 3:for(let A=0,N=0;A<this.data.length;A+=3)k[N++]=this.data[A],k[N++]=this.data[A+1],k[N++]=this.data[A+2],k[N++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(k,this.width,this.height,4)}putAlpha(k){if(k.width!==this.width||k.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${k.width}x${k.height}`);if(k.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${k.channels}`);let A=this.data,N=k.data,x=this.width*this.height;if(this.channels===3){let P=new Uint8ClampedArray(x*4);for(let D=0,_=0,M=0;D<x;++D)P[M++]=A[_++],P[M++]=A[_++],P[M++]=A[_++],P[M++]=N[D];return this._update(P,this.width,this.height,4)}else if(this.channels===4){for(let P=0;P<x;++P)A[4*P+3]=N[P];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(k,A,{resample:N=2}={}){if(this.width===k&&this.height===A)return this;let x=i[N]??N,P=(0,r.isNullishDimension)(k),D=(0,r.isNullishDimension)(A);if(P&&D)return this;if(P?k=A/this.height*this.width:D&&(A=k/this.width*this.height),f){let _=this.channels,M=this.toCanvas(),I=l(k,A).getContext("2d");return I.drawImage(M,0,0,k,A),new E(I.getImageData(0,0,k,A).data,k,A,4).convert(_)}else{let _=this.toSharp();switch(x){case"box":case"hamming":(x==="box"||x==="hamming")&&(console.warn(`Resampling method ${x} is not yet supported. Using bilinear instead.`),x="bilinear");case"nearest":case"bilinear":case"bicubic":_=_.affine([k/this.width,0,0,A/this.height],{interpolator:x});break;case"lanczos":_=_.resize({width:k,height:A,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${x} is not supported.`)}return await w(_)}}async pad([k,A,N,x]){if(k=Math.max(k,0),A=Math.max(A,0),N=Math.max(N,0),x=Math.max(x,0),k===0&&A===0&&N===0&&x===0)return this;if(f){let P=this.channels,D=this.toCanvas(),_=this.width+k+A,M=this.height+N+x,I=l(_,M).getContext("2d");return I.drawImage(D,0,0,this.width,this.height,k,N,this.width,this.height),new E(I.getImageData(0,0,_,M).data,_,M,4).convert(P)}else{let P=this.toSharp().extend({left:k,right:A,top:N,bottom:x});return await w(P)}}async crop([k,A,N,x]){if(k=Math.max(k,0),A=Math.max(A,0),N=Math.min(N,this.width-1),x=Math.min(x,this.height-1),k===0&&A===0&&N===this.width-1&&x===this.height-1)return this;let P=N-k+1,D=x-A+1;if(f){let _=this.channels,M=this.toCanvas(),I=l(P,D).getContext("2d");return I.drawImage(M,k,A,P,D,0,0,P,D),new E(I.getImageData(0,0,P,D).data,P,D,4).convert(_)}else{let _=this.toSharp().extract({left:k,top:A,width:P,height:D});return await w(_)}}async center_crop(k,A){if(this.width===k&&this.height===A)return this;let N=(this.width-k)/2,x=(this.height-A)/2;if(f){let P=this.channels,D=this.toCanvas(),_=l(k,A).getContext("2d"),M=0,I=0,O=0,G=0;return N>=0?M=N:O=-N,x>=0?I=x:G=-x,_.drawImage(D,M,I,k,A,O,G,k,A),new E(_.getImageData(0,0,k,A).data,k,A,4).convert(P)}else{let P=this.toSharp();if(N>=0&&x>=0)P=P.extract({left:Math.floor(N),top:Math.floor(x),width:k,height:A});else if(N<=0&&x<=0){let D=Math.floor(-x),_=Math.floor(-N);P=P.extend({top:D,left:_,right:k-this.width-_,bottom:A-this.height-D})}else{let D=[0,0],_=0;x<0?(D[0]=Math.floor(-x),D[1]=A-this.height-D[0]):_=Math.floor(x);let M=[0,0],I=0;N<0?(M[0]=Math.floor(-N),M[1]=k-this.width-M[0]):I=Math.floor(N),P=P.extend({top:D[0],bottom:D[1],left:M[0],right:M[1]}).extract({left:I,top:_,width:k,height:A})}return await w(P)}}async toBlob(k="image/png",A=1){if(!f)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:k,quality:A})}toTensor(k="CHW"){let A=new h.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(k!=="HWC")if(k==="CHW")A=A.permute(2,0,1);else throw new Error(`Unsupported channel format: ${k}`);return A}toCanvas(){if(!f)throw new Error("toCanvas() is only supported in browser environments.");let k=this.clone().rgba(),A=l(k.width,k.height),N=new p(k.data,k.width,k.height);return A.getContext("2d").putImageData(N,0,0),A}split(){let{data:k,width:A,height:N,channels:x}=this,P=k.constructor,D=k.length/x,_=Array.from({length:x},()=>new P(D));for(let M=0;M<D;++M){let I=x*M;for(let O=0;O<x;++O)_[O][M]=k[I+O]}return _.map(M=>new E(M,A,N,1))}_update(k,A,N,x=null){return this.data=k,this.width=A,this.height=N,x!==null&&(this.channels=x),this}clone(){return new E(this.data.slice(),this.width,this.height,this.channels)}convert(k){if(this.channels===k)return this;switch(k){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(k){if(f){if(a.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let A=k.split(".").pop().toLowerCase(),N=y.get(A)??"image/png",x=await this.toBlob(N);(0,r.saveBlob)(k,x)}else{if(a.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(k);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(f)throw new Error("toSharp() is only supported in server-side environments.");return u(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}let S=E.read.bind(E)},"./src/utils/maths.js":(d,t,e)=>{e.r(t),e.d(t,{FFT:()=>S,bankers_round:()=>A,cos_sim:()=>l,dot:()=>u,dynamic_time_warping:()=>N,interpolate_data:()=>r,log_softmax:()=>h,magnitude:()=>p,max:()=>f,medianFilter:()=>z,min:()=>w,permute_data:()=>o,round:()=>k,softmax:()=>a});function r(x,[P,D,_],[M,I],O="bilinear",G=!1){let U=I/_,B=M/D,Q=new x.constructor(M*I*P),$=D*_,Y=M*I;for(let se=0;se<M;++se)for(let oe=0;oe<I;++oe){let ue=se*I+oe,be=(oe+.5)/U-.5,pe=(se+.5)/B-.5,J=Math.floor(be),F=Math.floor(pe),K=Math.min(J+1,_-1),Z=Math.min(F+1,D-1);J=Math.max(J,0),F=Math.max(F,0);let ie=be-J,xe=pe-F,ye=(1-ie)*(1-xe),Oe=ie*(1-xe),He=(1-ie)*xe,we=ie*xe,T=F*_,X=Z*_,de=T+J,he=T+K,Te=X+J,ge=X+K;for(let le=0;le<P;++le){let ve=le*$;Q[le*Y+ue]=ye*x[ve+de]+Oe*x[ve+he]+He*x[ve+Te]+we*x[ve+ge]}}return Q}function o(x,P,D){let _=new Array(D.length),M=new Array(D.length);for(let G=D.length-1,U=1;G>=0;--G)M[G]=U,_[G]=P[D[G]],U*=_[G];let I=D.map((G,U)=>M[D.indexOf(U)]),O=new x.constructor(x.length);for(let G=0;G<x.length;++G){let U=0;for(let B=P.length-1,Q=G;B>=0;--B)U+=Q%P[B]*I[B],Q=Math.floor(Q/P[B]);O[U]=x[G]}return[O,_]}function a(x){let P=f(x)[0],D=x.map(I=>Math.exp(I-P)),_=D.reduce((I,O)=>I+O,0);return D.map(I=>I/_)}function h(x){let P=f(x)[0],D=0;for(let I=0;I<x.length;++I)D+=Math.exp(x[I]-P);let _=Math.log(D);return x.map(I=>I-P-_)}function u(x,P){let D=0;for(let _=0;_<x.length;++_)D+=x[_]*P[_];return D}function l(x,P){let D=u(x,P),_=p(x),M=p(P);return D/(_*M)}function p(x){return Math.sqrt(x.reduce((P,D)=>P+D*D,0))}function w(x){if(x.length===0)throw Error("Array must not be empty");let P=x[0],D=0;for(let _=1;_<x.length;++_)x[_]<P&&(P=x[_],D=_);return[P,D]}function f(x){if(x.length===0)throw Error("Array must not be empty");let P=x[0],D=0;for(let _=1;_<x.length;++_)x[_]>P&&(P=x[_],D=_);return[P,D]}function i(x){return x>0&&(x&x-1)===0}class y{constructor(P){if(this.size=P|0,this.size<=1||!i(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=P<<1,this.table=new Float64Array(this.size*2);for(let _=0;_<this.table.length;_+=2){let M=Math.PI*_/this.size;this.table[_]=Math.cos(M),this.table[_+1]=-Math.sin(M)}let D=0;for(let _=1;this.size>_;_<<=1)++D;this._width=D%2===0?D-1:D,this._bitrev=new Int32Array(1<<this._width);for(let _=0;_<this._bitrev.length;++_){this._bitrev[_]=0;for(let M=0;M<this._width;M+=2){let I=this._width-M-2;this._bitrev[_]|=(_>>>M&3)<<I}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(P,D){let _=D||new Array(P.length>>>1);for(let M=0;M<P.length;M+=2)_[M>>>1]=P[M];return _}toComplexArray(P,D){let _=D||this.createComplexArray();for(let M=0;M<_.length;M+=2)_[M]=P[M>>>1],_[M+1]=0;return _}transform(P,D){if(P===D)throw new Error("Input and output buffers must be different");this._transform4(P,D,1)}realTransform(P,D){if(P===D)throw new Error("Input and output buffers must be different");this._realTransform4(P,D,1)}inverseTransform(P,D){if(P===D)throw new Error("Input and output buffers must be different");this._transform4(P,D,-1);for(let _=0;_<P.length;++_)P[_]/=this.size}_transform4(P,D,_){let M=this._csize,O=1<<this._width,G=M/O<<1,U,B,Q=this._bitrev;if(G===4)for(U=0,B=0;U<M;U+=G,++B){let Y=Q[B];this._singleTransform2(D,P,U,Y,O)}else for(U=0,B=0;U<M;U+=G,++B){let Y=Q[B];this._singleTransform4(D,P,U,Y,O,_)}let $=this.table;for(O>>=2;O>=2;O>>=2){G=M/O<<1;let Y=G>>>2;for(U=0;U<M;U+=G){let se=U+Y-1;for(let oe=U,ue=0;oe<se;oe+=2,ue+=O){let be=oe,pe=be+Y,J=pe+Y,F=J+Y,K=P[be],Z=P[be+1],ie=P[pe],xe=P[pe+1],ye=P[J],Oe=P[J+1],He=P[F],we=P[F+1],T=$[ue],X=_*$[ue+1],de=ie*T-xe*X,he=ie*X+xe*T,Te=$[2*ue],ge=_*$[2*ue+1],le=ye*Te-Oe*ge,ve=ye*ge+Oe*Te,ce=$[3*ue],Me=_*$[3*ue+1],Re=He*ce-we*Me,Ce=He*Me+we*ce,Ie=K+le,Fe=Z+ve,Je=K-le,Ve=Z-ve,ze=de+Re,Ae=he+Ce,et=_*(de-Re),Ue=_*(he-Ce);P[be]=Ie+ze,P[be+1]=Fe+Ae,P[pe]=Je+Ue,P[pe+1]=Ve-et,P[J]=Ie-ze,P[J+1]=Fe-Ae,P[F]=Je-Ue,P[F+1]=Ve+et}}}}_singleTransform2(P,D,_,M,I){let O=P[M],G=P[M+1],U=P[M+I],B=P[M+I+1];D[_]=O+U,D[_+1]=G+B,D[_+2]=O-U,D[_+3]=G-B}_singleTransform4(P,D,_,M,I,O){let G=I*2,U=I*3,B=P[M],Q=P[M+1],$=P[M+I],Y=P[M+I+1],se=P[M+G],oe=P[M+G+1],ue=P[M+U],be=P[M+U+1],pe=B+se,J=Q+oe,F=B-se,K=Q-oe,Z=$+ue,ie=Y+be,xe=O*($-ue),ye=O*(Y-be);D[_]=pe+Z,D[_+1]=J+ie,D[_+2]=F+ye,D[_+3]=K-xe,D[_+4]=pe-Z,D[_+5]=J-ie,D[_+6]=F-ye,D[_+7]=K+xe}_realTransform4(P,D,_){let M=this._csize,O=1<<this._width,G=M/O<<1,U,B,Q=this._bitrev;if(G===4)for(U=0,B=0;U<M;U+=G,++B){let se=Q[B];this._singleRealTransform2(D,P,U,se>>>1,O>>>1)}else for(U=0,B=0;U<M;U+=G,++B){let se=Q[B];this._singleRealTransform4(D,P,U,se>>>1,O>>>1,_)}let $=this.table;for(O>>=2;O>=2;O>>=2){G=M/O<<1;let se=G>>>1,oe=se>>>1,ue=oe>>>1;for(U=0;U<M;U+=G)for(let be=0,pe=0;be<=ue;be+=2,pe+=O){let J=U+be,F=J+oe,K=F+oe,Z=K+oe,ie=P[J],xe=P[J+1],ye=P[F],Oe=P[F+1],He=P[K],we=P[K+1],T=P[Z],X=P[Z+1],de=ie,he=xe,Te=$[pe],ge=_*$[pe+1],le=ye*Te-Oe*ge,ve=ye*ge+Oe*Te,ce=$[2*pe],Me=_*$[2*pe+1],Re=He*ce-we*Me,Ce=He*Me+we*ce,Ie=$[3*pe],Fe=_*$[3*pe+1],Je=T*Ie-X*Fe,Ve=T*Fe+X*Ie,ze=de+Re,Ae=he+Ce,et=de-Re,Ue=he-Ce,lt=le+Je,mt=ve+Ve,bt=_*(le-Je),Vt=_*(ve-Ve);if(P[J]=ze+lt,P[J+1]=Ae+mt,P[F]=et+Vt,P[F+1]=Ue-bt,be===0){P[K]=ze-lt,P[K+1]=Ae-mt;continue}if(be===ue)continue;let vt=U+oe-be,Ht=U+se-be;P[vt]=et-_*Vt,P[vt+1]=-Ue-_*bt,P[Ht]=ze-_*lt,P[Ht+1]=-Ae+_*mt}}let Y=M>>>1;for(let se=2;se<Y;se+=2)P[M-se]=P[se],P[M-se+1]=-P[se+1]}_singleRealTransform2(P,D,_,M,I){let O=P[M],G=P[M+I];D[_]=O+G,D[_+1]=0,D[_+2]=O-G,D[_+3]=0}_singleRealTransform4(P,D,_,M,I,O){let G=I*2,U=I*3,B=P[M],Q=P[M+I],$=P[M+G],Y=P[M+U],se=B+$,oe=B-$,ue=Q+Y,be=O*(Q-Y);D[_]=se+ue,D[_+1]=0,D[_+2]=oe,D[_+3]=-be,D[_+4]=se-ue,D[_+5]=0,D[_+6]=oe,D[_+7]=be}}class E{constructor(P){let D=2*(P-1),_=2*(2*P-1),M=2**Math.ceil(Math.log2(_));this.bufferSize=M,this._a=D;let I=new Float64Array(_),O=new Float64Array(M);this._chirpBuffer=new Float64Array(M),this._buffer1=new Float64Array(M),this._buffer2=new Float64Array(M),this._outBuffer1=new Float64Array(M),this._outBuffer2=new Float64Array(M);let G=-2*Math.PI/P,U=Math.cos(G),B=Math.sin(G);for(let Q=0;Q<_>>1;++Q){let $=(Q+1-P)**2/2,Y=Math.sqrt(U**2+B**2)**$,se=$*Math.atan2(B,U),oe=2*Q;I[oe]=Y*Math.cos(se),I[oe+1]=Y*Math.sin(se),O[oe]=I[oe],O[oe+1]=-I[oe+1]}this._slicedChirpBuffer=I.subarray(D,_),this._f=new y(M>>1),this._f.transform(this._chirpBuffer,O)}_transform(P,D,_){let M=this._buffer1,I=this._buffer2,O=this._outBuffer1,G=this._outBuffer2,U=this._chirpBuffer,B=this._slicedChirpBuffer,Q=this._a;if(_)for(let $=0;$<B.length;$+=2){let Y=$+1,se=$>>1,oe=D[se];M[$]=oe*B[$],M[Y]=oe*B[Y]}else for(let $=0;$<B.length;$+=2){let Y=$+1;M[$]=D[$]*B[$]-D[Y]*B[Y],M[Y]=D[$]*B[Y]+D[Y]*B[$]}this._f.transform(O,M);for(let $=0;$<U.length;$+=2){let Y=$+1;I[$]=O[$]*U[$]-O[Y]*U[Y],I[Y]=O[$]*U[Y]+O[Y]*U[$]}this._f.inverseTransform(G,I);for(let $=0;$<G.length;$+=2){let Y=G[$+Q],se=G[$+Q+1],oe=B[$],ue=B[$+1];P[$]=Y*oe-se*ue,P[$+1]=Y*ue+se*oe}}transform(P,D){this._transform(P,D,!1)}realTransform(P,D){this._transform(P,D,!0)}}class S{constructor(P){this.fft_length=P,this.isPowerOfTwo=i(P),this.isPowerOfTwo?(this.fft=new y(P),this.outputBufferSize=2*P):(this.fft=new E(P),this.outputBufferSize=this.fft.bufferSize)}realTransform(P,D){this.fft.realTransform(P,D)}transform(P,D){this.fft.transform(P,D)}}function z(x,P){if(P%2===0||P<=0)throw new Error("Window size must be a positive odd number");let D=new x.constructor(x.length),_=new x.constructor(P),M=Math.floor(P/2);for(let I=0;I<x.length;++I){let O=0;for(let G=-M;G<=M;++G){let U=I+G;U<0?U=Math.abs(U):U>=x.length&&(U=2*(x.length-1)-U),_[O++]=x[U]}_.sort(),D[I]=_[M]}return D}function k(x,P){let D=Math.pow(10,P);return Math.round(x*D)/D}function A(x){let P=Math.round(x);return Math.abs(x)%1===.5?P%2===0?P:P-1:P}function N(x){let P=x.length,D=x[0].length,_=[P+1,D+1],M=Array.from({length:_[0]},()=>Array(_[1]).fill(1/0));M[0][0]=0;let I=Array.from({length:_[0]},()=>Array(_[1]).fill(-1));for(let Q=1;Q<_[1];++Q)for(let $=1;$<_[0];++$){let Y=M[$-1][Q-1],se=M[$-1][Q],oe=M[$][Q-1],ue,be;Y<se&&Y<oe?(ue=Y,be=0):se<Y&&se<oe?(ue=se,be=1):(ue=oe,be=2),M[$][Q]=x[$-1][Q-1]+ue,I[$][Q]=be}for(let Q=0;Q<_[1];++Q)I[0][Q]=2;for(let Q=0;Q<_[0];++Q)I[Q][0]=1;let O=P,G=D,U=[],B=[];for(;O>0||G>0;)switch(U.push(O-1),B.push(G-1),I[O][G]){case 0:--O,--G;break;case 1:--O;break;case 2:--G;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${O}, ${G}]. Please file a bug report.`)}return U.reverse(),B.reverse(),[U,B]}},"./src/utils/tensor.js":(d,t,e)=>{e.r(t),e.d(t,{DataTypeMap:()=>h,Tensor:()=>u,cat:()=>D,full:()=>B,full_like:()=>Q,interpolate:()=>w,interpolate_4d:()=>f,layer_norm:()=>A,matmul:()=>i,mean:()=>O,mean_pooling:()=>k,ones:()=>$,ones_like:()=>Y,permute:()=>p,quantize_embeddings:()=>pe,rand:()=>ue,randn:()=>be,rfft:()=>y,slice:()=>z,stack:()=>_,std_mean:()=>I,topk:()=>E,zeros:()=>se,zeros_like:()=>oe});var r=e("./src/utils/maths.js"),o=e("./src/backends/onnx.js"),a=e("./src/ops/registry.js");let h=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});class u{constructor(...F){v(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(K,Z)=>{if(typeof Z=="string"){let ie=Number(Z);if(Number.isInteger(ie))return K._getitem(ie)}return K[Z]},set:(K,Z,ie)=>K[Z]=ie})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[F,...K]=this.dims;if(K.length>0){let Z=K.reduce((ie,xe)=>ie*xe);for(let ie=0;ie<F;++ie)yield this._subarray(ie,Z,K)}else yield*this.data}_getitem(F){let[K,...Z]=this.dims;if(F=P(F,K),Z.length>0){let ie=Z.reduce((xe,ye)=>xe*ye);return this._subarray(F,ie,Z)}else return new u(this.type,[this.data[F]],Z)}indexOf(F){let K=this.data;for(let Z=0;Z<K.length;++Z)if(K[Z]==F)return Z;return-1}_subarray(F,K,Z){let ie=F*K,xe=(F+1)*K,ye="subarray"in this.data?this.data.subarray(ie,xe):this.data.slice(ie,xe);return new u(this.type,ye,Z)}item(){let F=this.data;if(F.length!==1)throw new Error(`a Tensor with ${F.length} elements cannot be converted to Scalar`);return F[0]}tolist(){return l(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let F=this.data;for(let K=0;K<F.length;++K)F[K]=1/(1+Math.exp(-F[K]));return this}map(F){return this.clone().map_(F)}map_(F){let K=this.data;for(let Z=0;Z<K.length;++Z)K[Z]=F(K[Z],Z,K);return this}mul(F){return this.clone().mul_(F)}mul_(F){let K=this.data;for(let Z=0;Z<K.length;++Z)K[Z]*=F;return this}div(F){return this.clone().div_(F)}div_(F){let K=this.data;for(let Z=0;Z<K.length;++Z)K[Z]/=F;return this}add(F){return this.clone().add_(F)}add_(F){let K=this.data;for(let Z=0;Z<K.length;++Z)K[Z]+=F;return this}sub(F){return this.clone().sub_(F)}sub_(F){let K=this.data;for(let Z=0;Z<K.length;++Z)K[Z]-=F;return this}clone(){return new u(this.type,this.data.slice(),this.dims.slice())}slice(...F){let K=[],Z=[];for(let T=0;T<this.dims.length;++T){let X=F[T];if(X==null)Z.push([0,this.dims[T]]),K.push(this.dims[T]);else if(typeof X=="number")X=P(X,this.dims[T],T),Z.push([X,X+1]);else if(Array.isArray(X)&&X.length===2){let[de,he]=X;if(de=de===null?0:P(de,this.dims[T],T,!1),he=he===null?this.dims[T]:P(he,this.dims[T],T,!1),de>he)throw new Error(`Invalid slice: ${X}`);let Te=[Math.max(de,0),Math.min(he,this.dims[T])];Z.push(Te),K.push(Te[1]-Te[0])}else throw new Error(`Invalid slice: ${X}`)}let ie=Z.map(([T,X])=>X-T),xe=ie.reduce((T,X)=>T*X),ye=this.data,Oe=new ye.constructor(xe),He=this.stride(),we=!0;for(let T=1;T<ie.length;++T)if(Z[T][0]!==0||Z[T][1]!==this.dims[T]){we=!1;break}if(we){let T=Z[0][0]*He[0],X=Z[0][1]*He[0];if(ArrayBuffer.isView(ye))Oe.set(ye.subarray(T,X));else if(Array.isArray(ye)){let de=ye.slice(T,X);for(let he=0;he<de.length;++he)Oe[he]=de[he]}else throw new Error("Unsupported data type for slicing")}else for(let T=0;T<xe;++T){let X=0;for(let de=ie.length-1,he=T;de>=0;--de){let Te=ie[de];X+=(he%Te+Z[de][0])*He[de],he=Math.floor(he/Te)}Oe[T]=ye[X]}return new u(this.type,Oe,K)}permute(...F){return p(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,K=!1){return this.norm(1,F,K)}norm(F="fro",K=null,Z=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);let ie=this.data,xe=(we,T)=>we+T**F;if(K===null){let we=ie.reduce(xe,0)**(1/F);return new u(this.type,[we],[])}let[ye,Oe,He]=M(xe,this,K,Z);if(F!==1)for(let we=0;we<Oe.length;++we)Oe[we]=Oe[we]**(1/F);return new u(ye,Oe,He)}normalize_(F=2,K=1){K=P(K,this.dims.length);let Z=this.norm(F,K,!0),ie=this.data,xe=Z.data;for(let ye=0;ye<ie.length;++ye){let Oe=0;for(let He=this.dims.length-1,we=ye,T=1;He>=0;--He){let X=this.dims[He];if(He!==K){let de=we%X;Oe+=de*T,T*=this.dims[He]}we=Math.floor(we/X)}ie[ye]/=xe[Oe]}return this}normalize(F=2,K=1){return this.clone().normalize_(F,K)}stride(){return G(this.dims)}squeeze(F=null){return new u(this.type,this.data,N(this.dims,F))}squeeze_(F=null){return this.dims=N(this.dims,F),this}unsqueeze(F=null){return new u(this.type,this.data,x(this.dims,F))}unsqueeze_(F=null){return this.dims=x(this.dims,F),this}flatten_(F=0,K=-1){K=(K+this.dims.length)%this.dims.length;let Z=this.dims.slice(0,F),ie=this.dims.slice(F,K+1),xe=this.dims.slice(K+1);return this.dims=[...Z,ie.reduce((ye,Oe)=>ye*Oe,1),...xe],this}flatten(F=0,K=-1){return this.clone().flatten_(F,K)}view(...F){let K=-1;for(let ie=0;ie<F.length;++ie)if(F[ie]===-1){if(K!==-1)throw new Error("Only one dimension can be inferred");K=ie}let Z=this.data;if(K!==-1){let ie=F.reduce((xe,ye,Oe)=>Oe!==K?xe*ye:xe,1);F[K]=Z.length/ie}return new u(this.type,Z,F)}neg_(){let F=this.data;for(let K=0;K<F.length;++K)F[K]=-F[K];return this}neg(){return this.clone().neg_()}gt(F){let K=new Uint8Array(this.data.length),Z=this.data;for(let ie=0;ie<Z.length;++ie)K[ie]=Z[ie]>F?1:0;return new u("bool",K,this.dims)}lt(F){let K=new Uint8Array(this.data.length),Z=this.data;for(let ie=0;ie<Z.length;++ie)K[ie]=Z[ie]<F?1:0;return new u("bool",K,this.dims)}clamp_(F,K){let Z=this.data;for(let ie=0;ie<Z.length;++ie)Z[ie]=Math.min(Math.max(Z[ie],F),K);return this}clamp(F,K){return this.clone().clamp_(F,K)}round_(){let F=this.data;for(let K=0;K<F.length;++K)F[K]=Math.round(F[K]);return this}round(){return this.clone().round_()}mean(F=null,K=!1){return O(this,F,K)}min(F=null,K=!1){if(F===null){let ye=(0,r.min)(this.data)[0];return new u(this.type,[ye],[])}let[Z,ie,xe]=M((ye,Oe)=>Math.min(ye,Oe),this,F,K,1/0);return new u(Z,ie,xe)}max(F=null,K=!1){if(F===null){let ye=(0,r.max)(this.data)[0];return new u(this.type,[ye],[])}let[Z,ie,xe]=M((ye,Oe)=>Math.max(ye,Oe),this,F,K,-1/0);return new u(Z,ie,xe)}argmin(F=null,K=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");let Z=(0,r.min)(this.data)[1];return new u("int64",[BigInt(Z)],[])}argmax(F=null,K=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");let Z=(0,r.max)(this.data)[1];return new u("int64",[BigInt(Z)],[])}to(F){if(this.type===F)return this;if(!h.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let K,Z=["int64","uint64"].includes(this.type),ie=["int64","uint64"].includes(F);return Z&&!ie?K=Number:!Z&&ie&&(["float16","float32","float64"].includes(this.type)?K=xe=>BigInt(Math.floor(xe)):K=BigInt),new u(F,h[F].from(this.data,K),this.dims)}}function l(J,F){let K=J.length,Z=F.reduce((xe,ye)=>xe*ye);if(K!==Z)throw Error(`cannot reshape array of size ${K} into shape (${F})`);let ie=J;for(let xe=F.length-1;xe>=0;xe--)ie=ie.reduce((ye,Oe)=>{let He=ye[ye.length-1];return He.length<F[xe]?He.push(Oe):ye.push([Oe]),ye},[[]]);return ie[0]}function p(J,F){let[K,Z]=(0,r.permute_data)(J.data,J.dims,F);return new u(J.type,K,Z)}function w(J,[F,K],Z="bilinear",ie=!1){let xe=J.dims.at(-3)??1,ye=J.dims.at(-2),Oe=J.dims.at(-1),He=(0,r.interpolate_data)(J.data,[xe,ye,Oe],[F,K],Z,ie);return new u(J.type,He,[xe,F,K])}async function f(J,{size:F=null,mode:K="bilinear"}={}){if(J.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!F)throw new Error("`interpolate_4d` requires a `size` argument.");let Z;if(F.length===2)Z=[...J.dims.slice(0,2),...F];else if(F.length===3)Z=[J.dims[0],...F];else if(F.length===4)Z=F;else throw new Error("`size` must be of length 2, 3, or 4.");let ie;if(K==="nearest")ie=await a.TensorOpRegistry.nearest_interpolate_4d;else if(K==="bilinear")ie=await a.TensorOpRegistry.bilinear_interpolate_4d;else if(K==="bicubic")ie=await a.TensorOpRegistry.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${K}`);let xe=new u("int64",new BigInt64Array(Z.map(BigInt)),[Z.length]);return await ie({x:J,s:xe})}async function i(J,F){return await(await a.TensorOpRegistry.matmul)({a:J,b:F})}async function y(J,F){return await(await a.TensorOpRegistry.rfft)({x:J,a:F})}async function E(J,F){let K=await a.TensorOpRegistry.top_k;return F==null?F=J.dims.at(-1):F=Math.min(F,J.dims.at(-1)),await K({x:J,k:new u("int64",[BigInt(F)],[1])})}let S=J=>new u("int64",J,[J.length]);async function z(J,F,K,Z,ie){return await(await a.TensorOpRegistry.slice)({x:J,s:S(F),e:S(K),a:S(Z),t:S(ie??new Array(Z.length).fill(1))})}function k(J,F){let K=J.data,Z=F.data,ie=[J.dims[0],J.dims[2]],xe=new K.constructor(ie[0]*ie[1]),[ye,Oe,He]=J.dims,we=0;for(let T=0;T<ye;++T){let X=T*He*Oe;for(let de=0;de<He;++de){let he=0,Te=0,ge=T*Oe,le=X+de;for(let ce=0;ce<Oe;++ce){let Me=Number(Z[ge+ce]);Te+=Me,he+=K[le+ce*He]*Me}let ve=he/Te;xe[we++]=ve}}return new u(J.type,xe,ie)}function A(J,F,{eps:K=1e-5}={}){if(J.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[Z,ie]=J.dims;if(F.length!==1&&F[0]!==ie)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[xe,ye]=I(J,1,0,!0),Oe=xe.data,He=ye.data,we=J.data,T=new we.constructor(we.length);for(let X=0;X<Z;++X){let de=X*ie;for(let he=0;he<ie;++he){let Te=de+he;T[Te]=(we[Te]-He[X])/(Oe[X]+K)}}return new u(J.type,T,J.dims)}function N(J,F){return J=J.slice(),F===null?J=J.filter(K=>K!==1):typeof F=="number"?J[F]===1&&J.splice(F,1):Array.isArray(F)&&(J=J.filter((K,Z)=>K!==1||!F.includes(Z))),J}function x(J,F){return F=P(F,J.length+1),J=J.slice(),J.splice(F,0,1),J}function P(J,F,K=null,Z=!0){if(J<-F||J>=F){if(Z)throw new Error(`IndexError: index ${J} is out of bounds for dimension${K===null?"":" "+K} with size ${F}`);return J<-F?0:F}return J<0&&(J=(J%F+F)%F),J}function D(J,F=0){F=P(F,J[0].dims.length);let K=J[0].dims.slice();K[F]=J.reduce((ye,Oe)=>ye+Oe.dims[F],0);let Z=K.reduce((ye,Oe)=>ye*Oe,1),ie=new J[0].data.constructor(Z),xe=J[0].type;if(F===0){let ye=0;for(let Oe of J){let He=Oe.data;ie.set(He,ye),ye+=He.length}}else{let ye=0;for(let Oe=0;Oe<J.length;++Oe){let{data:He,dims:we}=J[Oe];for(let T=0;T<He.length;++T){let X=0;for(let de=we.length-1,he=T,Te=1;de>=0;--de){let ge=we[de],le=he%ge;de===F&&(le+=ye),X+=le*Te,Te*=K[de],he=Math.floor(he/ge)}ie[X]=He[T]}ye+=we[F]}}return new u(xe,ie,K)}function _(J,F=0){return D(J.map(K=>K.unsqueeze(F)),F)}function M(J,F,K=null,Z=!1,ie=null){let xe=F.data,ye=F.dims;K=P(K,ye.length);let Oe=ye.slice();Oe[K]=1;let He=new xe.constructor(xe.length/ye[K]);ie!==null&&He.fill(ie);for(let we=0;we<xe.length;++we){let T=0;for(let X=ye.length-1,de=we,he=1;X>=0;--X){let Te=ye[X];if(X!==K){let ge=de%Te;T+=ge*he,he*=Oe[X]}de=Math.floor(de/Te)}He[T]=J(He[T],xe[we],we,T)}return Z||Oe.splice(K,1),[F.type,He,Oe]}function I(J,F=null,K=1,Z=!1){let ie=J.data,xe=J.dims;if(F===null){let he=ie.reduce((ve,ce)=>ve+ce,0)/ie.length,Te=Math.sqrt(ie.reduce((ve,ce)=>ve+(ce-he)**2,0)/(ie.length-K)),ge=new u(J.type,[he],[]);return[new u(J.type,[Te],[]),ge]}F=P(F,xe.length);let ye=O(J,F,Z),Oe=ye.data,[He,we,T]=M((de,he,Te,ge)=>de+(he-Oe[ge])**2,J,F,Z);for(let de=0;de<we.length;++de)we[de]=Math.sqrt(we[de]/(xe[F]-K));return[new u(He,we,T),ye]}function O(J,F=null,K=!1){let Z=J.dims,ie=J.data;if(F===null){let He=ie.reduce((we,T)=>we+T,0);return new u(J.type,[He/ie.length],[])}F=P(F,Z.length);let[xe,ye,Oe]=M((He,we)=>He+we,J,F,K);if(Z[F]!==1)for(let He=0;He<ye.length;++He)ye[He]/=Z[F];return new u(xe,ye,Oe)}function G(J){let F=new Array(J.length);for(let K=J.length-1,Z=1;K>=0;--K)F[K]=Z,Z*=J[K];return F}function U(J,F,K,Z){let ie=J.reduce((xe,ye)=>xe*ye,1);return new u(K,new Z(ie).fill(F),J)}function B(J,F){let K,Z;if(typeof F=="number")K="float32",Z=Float32Array;else if(typeof F=="bigint")K="int64",Z=BigInt64Array;else if(typeof F=="boolean")K="bool",Z=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return U(J,F,K,Z)}function Q(J,F){return B(J.dims,F)}function $(J){return U(J,1n,"int64",BigInt64Array)}function Y(J){return $(J.dims)}function se(J){return U(J,0n,"int64",BigInt64Array)}function oe(J){return se(J.dims)}function ue(J){let F=J.reduce((K,Z)=>K*Z,1);return new u("float32",Float32Array.from({length:F},()=>Math.random()),J)}function be(J){let F=J.reduce((Z,ie)=>Z*ie,1);function K(){let Z=1-Math.random(),ie=1-Math.random();return Math.sqrt(-2*Math.log(Z))*Math.cos(2*Math.PI*ie)}return new u("float32",Float32Array.from({length:F},()=>K()),J)}function pe(J,F){if(J.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(J.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");let K=F==="binary",Z=K?"int8":"uint8",ie=K?Int8Array:Uint8Array,xe=J.data,ye=new ie(xe.length/8);for(let Oe=0;Oe<xe.length;++Oe){let He=xe[Oe]>0?1:0,we=Math.floor(Oe/8),T=Oe%8;ye[we]|=He<<7-T,K&&T===0&&(ye[we]-=128)}return new u(Z,ye,[J.dims[0],J.dims[1]/8])}},"./src/utils/video.js":(d,t,e)=>{e.r(t),e.d(t,{RawVideo:()=>h,RawVideoFrame:()=>a,load_video:()=>u});var r=e("./src/utils/image.js"),o=e("./src/env.js");class a{constructor(p,w){this.image=p,this.timestamp=w}}class h{constructor(p,w){p.length>0&&p[0]instanceof r.RawImage&&(p=p.map((f,i)=>new a(f,(i+1)/(p.length+1)*w))),this.frames=p,this.duration=w}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function u(l,{num_frames:p=null,fps:w=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(p==null&&w==null)throw new Error("Either num_frames or fps must be provided.");let f=[],i=document.createElement("video");if(i.crossOrigin="anonymous",i.muted=!0,typeof l=="string")i.src=l;else if(l instanceof Blob)i.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)i.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(N=>i.onloadedmetadata=N),i.seekable.start(0)===i.seekable.end(0)){let x=await(await fetch(i.src)).blob();i.src=URL.createObjectURL(x),await new Promise(P=>i.onloadedmetadata=P)}let y=i.duration,E,S;p!=null?(E=p,S=p===1?0:y/(p-1)):(S=1/w,E=Math.floor(y/S));let z=[];for(let N=0;N<E;++N)z.push(p===1?y/2:N*S);let k=document.createElement("canvas");k.width=i.videoWidth,k.height=i.videoHeight;let A=k.getContext("2d",{willReadFrequently:!0});for(let N of z){i.currentTime=N,await new Promise(_=>{i.onseeked=_}),A.drawImage(i,0,0,k.width,k.height);let x=A.getImageData(0,0,k.width,k.height),P=new r.RawImage(x.data,k.width,k.height,4),D=new a(P,N);f.push(D)}return i.remove(),new h(f,y)}}},ch={};(()=>{var d=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,t;wt.t=function(e,r){if(r&1&&(e=this(e)),r&8||typeof e=="object"&&e&&(r&4&&e.__esModule||r&16&&typeof e.then=="function"))return e;var o=Object.create(null);wt.r(o);var a={};t=t||[null,d({}),d([]),d(d)];for(var h=r&2&&e;typeof h=="object"&&!~t.indexOf(h);h=d(h))Object.getOwnPropertyNames(h).forEach(u=>a[u]=()=>e[u]);return a.default=()=>e,wt.d(o,a),o}})();wt.d=(d,t)=>{for(var e in t)wt.o(t,e)&&!wt.o(d,e)&&Object.defineProperty(d,e,{enumerable:!0,get:t[e]})};wt.o=(d,t)=>Object.prototype.hasOwnProperty.call(d,t);wt.r=d=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(d,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(d,"__esModule",{value:!0})};s={};(()=>{wt.r(s),wt.d(s,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ASTForAudioClassification:()=>e.ASTForAudioClassification,ASTModel:()=>e.ASTModel,ASTPreTrainedModel:()=>e.ASTPreTrainedModel,AlbertForMaskedLM:()=>e.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>e.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>e.AlbertForSequenceClassification,AlbertModel:()=>e.AlbertModel,AlbertPreTrainedModel:()=>e.AlbertPreTrainedModel,AlbertTokenizer:()=>r.AlbertTokenizer,ArceeForCausalLM:()=>e.ArceeForCausalLM,ArceeModel:()=>e.ArceeModel,ArceePreTrainedModel:()=>e.ArceePreTrainedModel,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>i.AutoFeatureExtractor,AutoImageProcessor:()=>S.AutoImageProcessor,AutoModel:()=>e.AutoModel,AutoModelForAudioClassification:()=>e.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>e.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>e.AutoModelForAudioTextToText,AutoModelForCTC:()=>e.AutoModelForCTC,AutoModelForCausalLM:()=>e.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>e.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>e.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>e.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>e.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>e.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>e.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>e.AutoModelForImageTextToText,AutoModelForImageToImage:()=>e.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>e.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>e.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>e.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>e.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>e.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>e.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>e.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>e.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>e.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>e.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>e.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>e.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>e.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>e.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>e.AutoModelForVision2Seq,AutoModelForXVector:()=>e.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>e.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>A.AutoProcessor,AutoTokenizer:()=>r.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>t.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>e.BartForConditionalGeneration,BartForSequenceClassification:()=>e.BartForSequenceClassification,BartModel:()=>e.BartModel,BartPretrainedModel:()=>e.BartPretrainedModel,BartTokenizer:()=>r.BartTokenizer,BaseModelOutput:()=>e.BaseModelOutput,BaseStreamer:()=>N.BaseStreamer,BeitFeatureExtractor:()=>E.BeitFeatureExtractor,BeitForImageClassification:()=>e.BeitForImageClassification,BeitModel:()=>e.BeitModel,BeitPreTrainedModel:()=>e.BeitPreTrainedModel,BertForMaskedLM:()=>e.BertForMaskedLM,BertForQuestionAnswering:()=>e.BertForQuestionAnswering,BertForSequenceClassification:()=>e.BertForSequenceClassification,BertForTokenClassification:()=>e.BertForTokenClassification,BertModel:()=>e.BertModel,BertPreTrainedModel:()=>e.BertPreTrainedModel,BertTokenizer:()=>r.BertTokenizer,BitImageProcessor:()=>E.BitImageProcessor,BlenderbotForConditionalGeneration:()=>e.BlenderbotForConditionalGeneration,BlenderbotModel:()=>e.BlenderbotModel,BlenderbotPreTrainedModel:()=>e.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>e.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>e.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>e.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>r.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>r.BlenderbotTokenizer,BloomForCausalLM:()=>e.BloomForCausalLM,BloomModel:()=>e.BloomModel,BloomPreTrainedModel:()=>e.BloomPreTrainedModel,BloomTokenizer:()=>r.BloomTokenizer,CLIPFeatureExtractor:()=>E.CLIPFeatureExtractor,CLIPImageProcessor:()=>E.CLIPImageProcessor,CLIPModel:()=>e.CLIPModel,CLIPPreTrainedModel:()=>e.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>e.CLIPSegForImageSegmentation,CLIPSegModel:()=>e.CLIPSegModel,CLIPSegPreTrainedModel:()=>e.CLIPSegPreTrainedModel,CLIPTextModel:()=>e.CLIPTextModel,CLIPTextModelWithProjection:()=>e.CLIPTextModelWithProjection,CLIPTokenizer:()=>r.CLIPTokenizer,CLIPVisionModel:()=>e.CLIPVisionModel,CLIPVisionModelWithProjection:()=>e.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>e.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>e.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>e.CamembertForSequenceClassification,CamembertForTokenClassification:()=>e.CamembertForTokenClassification,CamembertModel:()=>e.CamembertModel,CamembertPreTrainedModel:()=>e.CamembertPreTrainedModel,CamembertTokenizer:()=>r.CamembertTokenizer,CausalLMOutput:()=>e.CausalLMOutput,CausalLMOutputWithPast:()=>e.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>E.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>e.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>e.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>e.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>f.ClapFeatureExtractor,ClapModel:()=>e.ClapModel,ClapPreTrainedModel:()=>e.ClapPreTrainedModel,ClapTextModelWithProjection:()=>e.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>P.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>e.CodeGenForCausalLM,CodeGenModel:()=>e.CodeGenModel,CodeGenPreTrainedModel:()=>e.CodeGenPreTrainedModel,CodeGenTokenizer:()=>r.CodeGenTokenizer,CodeLlamaTokenizer:()=>r.CodeLlamaTokenizer,CohereForCausalLM:()=>e.CohereForCausalLM,CohereModel:()=>e.CohereModel,CoherePreTrainedModel:()=>e.CoherePreTrainedModel,CohereTokenizer:()=>r.CohereTokenizer,ConvBertForMaskedLM:()=>e.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>e.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>e.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>e.ConvBertForTokenClassification,ConvBertModel:()=>e.ConvBertModel,ConvBertPreTrainedModel:()=>e.ConvBertPreTrainedModel,ConvBertTokenizer:()=>r.ConvBertTokenizer,ConvNextFeatureExtractor:()=>E.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>e.ConvNextForImageClassification,ConvNextImageProcessor:()=>E.ConvNextImageProcessor,ConvNextModel:()=>e.ConvNextModel,ConvNextPreTrainedModel:()=>e.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>e.ConvNextV2ForImageClassification,ConvNextV2Model:()=>e.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>e.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>e.DFineForObjectDetection,DFineModel:()=>e.DFineModel,DFinePreTrainedModel:()=>e.DFinePreTrainedModel,DINOv3ConvNextModel:()=>e.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>e.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>E.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>e.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>e.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>E.DPTFeatureExtractor,DPTForDepthEstimation:()=>e.DPTForDepthEstimation,DPTImageProcessor:()=>E.DPTImageProcessor,DPTModel:()=>e.DPTModel,DPTPreTrainedModel:()=>e.DPTPreTrainedModel,DacDecoderModel:()=>e.DacDecoderModel,DacDecoderOutput:()=>e.DacDecoderOutput,DacEncoderModel:()=>e.DacEncoderModel,DacEncoderOutput:()=>e.DacEncoderOutput,DacFeatureExtractor:()=>f.DacFeatureExtractor,DacModel:()=>e.DacModel,DacPreTrainedModel:()=>e.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>e.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>e.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>e.DebertaForSequenceClassification,DebertaForTokenClassification:()=>e.DebertaForTokenClassification,DebertaModel:()=>e.DebertaModel,DebertaPreTrainedModel:()=>e.DebertaPreTrainedModel,DebertaTokenizer:()=>r.DebertaTokenizer,DebertaV2ForMaskedLM:()=>e.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>e.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>e.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>e.DebertaV2ForTokenClassification,DebertaV2Model:()=>e.DebertaV2Model,DebertaV2PreTrainedModel:()=>e.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>r.DebertaV2Tokenizer,DecisionTransformerModel:()=>e.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>e.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>E.DeiTFeatureExtractor,DeiTForImageClassification:()=>e.DeiTForImageClassification,DeiTImageProcessor:()=>E.DeiTImageProcessor,DeiTModel:()=>e.DeiTModel,DeiTPreTrainedModel:()=>e.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>e.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>e.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DepthProForDepthEstimation:()=>e.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>e.DepthProPreTrainedModel,DetrFeatureExtractor:()=>E.DetrFeatureExtractor,DetrForObjectDetection:()=>e.DetrForObjectDetection,DetrForSegmentation:()=>e.DetrForSegmentation,DetrImageProcessor:()=>E.DetrImageProcessor,DetrModel:()=>e.DetrModel,DetrObjectDetectionOutput:()=>e.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>e.DetrPreTrainedModel,DetrSegmentationOutput:()=>e.DetrSegmentationOutput,Dinov2ForImageClassification:()=>e.Dinov2ForImageClassification,Dinov2Model:()=>e.Dinov2Model,Dinov2PreTrainedModel:()=>e.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>e.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>e.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>e.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>e.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>e.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>e.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>e.DistilBertForTokenClassification,DistilBertModel:()=>e.DistilBertModel,DistilBertPreTrainedModel:()=>e.DistilBertPreTrainedModel,DistilBertTokenizer:()=>r.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>E.DonutFeatureExtractor,DonutImageProcessor:()=>E.DonutImageProcessor,DonutSwinModel:()=>e.DonutSwinModel,DonutSwinPreTrainedModel:()=>e.DonutSwinPreTrainedModel,EdgeTamModel:()=>e.EdgeTamModel,EfficientNetForImageClassification:()=>e.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>E.EfficientNetImageProcessor,EfficientNetModel:()=>e.EfficientNetModel,EfficientNetPreTrainedModel:()=>e.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>e.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>e.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>e.ElectraForSequenceClassification,ElectraForTokenClassification:()=>e.ElectraForTokenClassification,ElectraModel:()=>e.ElectraModel,ElectraPreTrainedModel:()=>e.ElectraPreTrainedModel,ElectraTokenizer:()=>r.ElectraTokenizer,EncodecFeatureExtractor:()=>f.EncodecFeatureExtractor,EosTokenCriteria:()=>x.EosTokenCriteria,Ernie4_5ForCausalLM:()=>e.Ernie4_5ForCausalLM,Ernie4_5Model:()=>e.Ernie4_5Model,Ernie4_5PreTrainedModel:()=>e.Ernie4_5PreTrainedModel,EsmForMaskedLM:()=>e.EsmForMaskedLM,EsmForSequenceClassification:()=>e.EsmForSequenceClassification,EsmForTokenClassification:()=>e.EsmForTokenClassification,EsmModel:()=>e.EsmModel,EsmPreTrainedModel:()=>e.EsmPreTrainedModel,EsmTokenizer:()=>r.EsmTokenizer,ExaoneForCausalLM:()=>e.ExaoneForCausalLM,ExaoneModel:()=>e.ExaoneModel,ExaonePreTrainedModel:()=>e.ExaonePreTrainedModel,FFT:()=>p.FFT,FalconForCausalLM:()=>e.FalconForCausalLM,FalconModel:()=>e.FalconModel,FalconPreTrainedModel:()=>e.FalconPreTrainedModel,FalconTokenizer:()=>r.FalconTokenizer,FastViTForImageClassification:()=>e.FastViTForImageClassification,FastViTModel:()=>e.FastViTModel,FastViTPreTrainedModel:()=>e.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>w.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>e.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>e.Florence2PreTrainedModel,Florence2Processor:()=>k.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>P.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>P.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>E.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>e.GLPNForDepthEstimation,GLPNModel:()=>e.GLPNModel,GLPNPreTrainedModel:()=>e.GLPNPreTrainedModel,GPT2LMHeadModel:()=>e.GPT2LMHeadModel,GPT2Model:()=>e.GPT2Model,GPT2PreTrainedModel:()=>e.GPT2PreTrainedModel,GPT2Tokenizer:()=>r.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>e.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>e.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>e.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>e.GPTJForCausalLM,GPTJModel:()=>e.GPTJModel,GPTJPreTrainedModel:()=>e.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>e.GPTNeoForCausalLM,GPTNeoModel:()=>e.GPTNeoModel,GPTNeoPreTrainedModel:()=>e.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>e.GPTNeoXForCausalLM,GPTNeoXModel:()=>e.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>e.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>r.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>e.Gemma2ForCausalLM,Gemma2Model:()=>e.Gemma2Model,Gemma2PreTrainedModel:()=>e.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>e.Gemma3ForCausalLM,Gemma3Model:()=>e.Gemma3Model,Gemma3PreTrainedModel:()=>e.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>f.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>e.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>e.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>k.Gemma3nProcessor,GemmaForCausalLM:()=>e.GemmaForCausalLM,GemmaModel:()=>e.GemmaModel,GemmaPreTrainedModel:()=>e.GemmaPreTrainedModel,GemmaTokenizer:()=>r.GemmaTokenizer,GlmForCausalLM:()=>e.GlmForCausalLM,GlmModel:()=>e.GlmModel,GlmPreTrainedModel:()=>e.GlmPreTrainedModel,GraniteForCausalLM:()=>e.GraniteForCausalLM,GraniteModel:()=>e.GraniteModel,GraniteMoeHybridForCausalLM:()=>e.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>e.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>e.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>e.GranitePreTrainedModel,Grok1Tokenizer:()=>r.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>e.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>E.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>e.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>k.GroundingDinoProcessor,GroupViTModel:()=>e.GroupViTModel,GroupViTPreTrainedModel:()=>e.GroupViTPreTrainedModel,HeliumForCausalLM:()=>e.HeliumForCausalLM,HeliumModel:()=>e.HeliumModel,HeliumPreTrainedModel:()=>e.HeliumPreTrainedModel,HerbertTokenizer:()=>r.HerbertTokenizer,HieraForImageClassification:()=>e.HieraForImageClassification,HieraModel:()=>e.HieraModel,HieraPreTrainedModel:()=>e.HieraPreTrainedModel,HubertForCTC:()=>e.HubertForCTC,HubertForSequenceClassification:()=>e.HubertForSequenceClassification,HubertModel:()=>e.HubertModel,HubertPreTrainedModel:()=>e.HubertPreTrainedModel,IJepaForImageClassification:()=>e.IJepaForImageClassification,IJepaModel:()=>e.IJepaModel,IJepaPreTrainedModel:()=>e.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>e.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>E.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>e.Idefics3PreTrainedModel,Idefics3Processor:()=>k.Idefics3Processor,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>f.ImageFeatureExtractor,ImageMattingOutput:()=>e.ImageMattingOutput,ImageProcessor:()=>y.ImageProcessor,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>x.InterruptableStoppingCriteria,JAISLMHeadModel:()=>e.JAISLMHeadModel,JAISModel:()=>e.JAISModel,JAISPreTrainedModel:()=>e.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>E.JinaCLIPImageProcessor,JinaCLIPModel:()=>e.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>e.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>k.JinaCLIPProcessor,JinaCLIPTextModel:()=>e.JinaCLIPTextModel,JinaCLIPVisionModel:()=>e.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>e.Lfm2ForCausalLM,Lfm2Model:()=>e.Lfm2Model,Lfm2PreTrainedModel:()=>e.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>e.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>e.Llama4ForCausalLM,Llama4PreTrainedModel:()=>e.Llama4PreTrainedModel,LlamaForCausalLM:()=>e.LlamaForCausalLM,LlamaModel:()=>e.LlamaModel,LlamaPreTrainedModel:()=>e.LlamaPreTrainedModel,LlamaTokenizer:()=>r.LlamaTokenizer,LlavaForConditionalGeneration:()=>e.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>e.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>E.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>e.LlavaPreTrainedModel,LlavaProcessor:()=>k.LlavaProcessor,LlavaQwen2ForCausalLM:()=>e.LlavaQwen2ForCausalLM,LogitsProcessor:()=>P.LogitsProcessor,LogitsProcessorList:()=>P.LogitsProcessorList,LogitsWarper:()=>P.LogitsWarper,LongT5ForConditionalGeneration:()=>e.LongT5ForConditionalGeneration,LongT5Model:()=>e.LongT5Model,LongT5PreTrainedModel:()=>e.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>e.M2M100ForConditionalGeneration,M2M100Model:()=>e.M2M100Model,M2M100PreTrainedModel:()=>e.M2M100PreTrainedModel,M2M100Tokenizer:()=>r.M2M100Tokenizer,MBart50Tokenizer:()=>r.MBart50Tokenizer,MBartForCausalLM:()=>e.MBartForCausalLM,MBartForConditionalGeneration:()=>e.MBartForConditionalGeneration,MBartForSequenceClassification:()=>e.MBartForSequenceClassification,MBartModel:()=>e.MBartModel,MBartPreTrainedModel:()=>e.MBartPreTrainedModel,MBartTokenizer:()=>r.MBartTokenizer,MPNetForMaskedLM:()=>e.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>e.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>e.MPNetForSequenceClassification,MPNetForTokenClassification:()=>e.MPNetForTokenClassification,MPNetModel:()=>e.MPNetModel,MPNetPreTrainedModel:()=>e.MPNetPreTrainedModel,MPNetTokenizer:()=>r.MPNetTokenizer,MT5ForConditionalGeneration:()=>e.MT5ForConditionalGeneration,MT5Model:()=>e.MT5Model,MT5PreTrainedModel:()=>e.MT5PreTrainedModel,MarianMTModel:()=>e.MarianMTModel,MarianModel:()=>e.MarianModel,MarianPreTrainedModel:()=>e.MarianPreTrainedModel,MarianTokenizer:()=>r.MarianTokenizer,Mask2FormerImageProcessor:()=>E.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>e.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MaskFormerModel:()=>e.MaskFormerModel,MaskFormerPreTrainedModel:()=>e.MaskFormerPreTrainedModel,MaskedLMOutput:()=>e.MaskedLMOutput,MaxLengthCriteria:()=>x.MaxLengthCriteria,Metric3DForDepthEstimation:()=>e.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>e.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>e.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>e.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>e.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>e.MgpstrModelOutput,MgpstrPreTrainedModel:()=>e.MgpstrPreTrainedModel,MgpstrProcessor:()=>k.MgpstrProcessor,MgpstrTokenizer:()=>r.MgpstrTokenizer,MimiDecoderModel:()=>e.MimiDecoderModel,MimiDecoderOutput:()=>e.MimiDecoderOutput,MimiEncoderModel:()=>e.MimiEncoderModel,MimiEncoderOutput:()=>e.MimiEncoderOutput,MimiModel:()=>e.MimiModel,MimiPreTrainedModel:()=>e.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>P.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>P.MinNewTokensLengthLogitsProcessor,Ministral3ForCausalLM:()=>e.Ministral3ForCausalLM,Ministral3Model:()=>e.Ministral3Model,Ministral3PreTrainedModel:()=>e.Ministral3PreTrainedModel,MinistralForCausalLM:()=>e.MinistralForCausalLM,MinistralModel:()=>e.MinistralModel,MinistralPreTrainedModel:()=>e.MinistralPreTrainedModel,Mistral3ForConditionalGeneration:()=>e.Mistral3ForConditionalGeneration,MistralForCausalLM:()=>e.MistralForCausalLM,MistralModel:()=>e.MistralModel,MistralPreTrainedModel:()=>e.MistralPreTrainedModel,MobileBertForMaskedLM:()=>e.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>e.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>e.MobileBertForSequenceClassification,MobileBertModel:()=>e.MobileBertModel,MobileBertPreTrainedModel:()=>e.MobileBertPreTrainedModel,MobileBertTokenizer:()=>r.MobileBertTokenizer,MobileLLMForCausalLM:()=>e.MobileLLMForCausalLM,MobileLLMModel:()=>e.MobileLLMModel,MobileLLMPreTrainedModel:()=>e.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>E.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>e.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>e.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>E.MobileNetV1ImageProcessor,MobileNetV1Model:()=>e.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>e.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>E.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>e.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>e.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>E.MobileNetV2ImageProcessor,MobileNetV2Model:()=>e.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>e.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>E.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>e.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>e.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>E.MobileNetV3ImageProcessor,MobileNetV3Model:()=>e.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>e.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>E.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>e.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>e.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>E.MobileNetV4ImageProcessor,MobileNetV4Model:()=>e.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>e.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>E.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>e.MobileViTForImageClassification,MobileViTImageProcessor:()=>E.MobileViTImageProcessor,MobileViTModel:()=>e.MobileViTModel,MobileViTPreTrainedModel:()=>e.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>e.MobileViTV2ForImageClassification,MobileViTV2Model:()=>e.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>e.MobileViTV2PreTrainedModel,ModelOutput:()=>e.ModelOutput,ModernBertDecoderForCausalLM:()=>e.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>e.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>e.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>e.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>e.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>e.ModernBertForTokenClassification,ModernBertModel:()=>e.ModernBertModel,ModernBertPreTrainedModel:()=>e.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>e.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>f.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>e.MoonshineForConditionalGeneration,MoonshineModel:()=>e.MoonshineModel,MoonshinePreTrainedModel:()=>e.MoonshinePreTrainedModel,MoonshineProcessor:()=>k.MoonshineProcessor,MptForCausalLM:()=>e.MptForCausalLM,MptModel:()=>e.MptModel,MptPreTrainedModel:()=>e.MptPreTrainedModel,MultiModalityCausalLM:()=>e.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>e.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>e.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>e.MusicgenForConditionalGeneration,MusicgenModel:()=>e.MusicgenModel,MusicgenPreTrainedModel:()=>e.MusicgenPreTrainedModel,NanoChatForCausalLM:()=>e.NanoChatForCausalLM,NanoChatModel:()=>e.NanoChatModel,NanoChatPreTrainedModel:()=>e.NanoChatPreTrainedModel,NeoBertForMaskedLM:()=>e.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>e.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>e.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>e.NeoBertForTokenClassification,NeoBertModel:()=>e.NeoBertModel,NeoBertPreTrainedModel:()=>e.NeoBertPreTrainedModel,NllbTokenizer:()=>r.NllbTokenizer,NoBadWordsLogitsProcessor:()=>P.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>P.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>e.NomicBertModel,NomicBertPreTrainedModel:()=>e.NomicBertPreTrainedModel,NougatImageProcessor:()=>E.NougatImageProcessor,NougatTokenizer:()=>r.NougatTokenizer,OPTForCausalLM:()=>e.OPTForCausalLM,OPTModel:()=>e.OPTModel,OPTPreTrainedModel:()=>e.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>e.Olmo2ForCausalLM,Olmo2Model:()=>e.Olmo2Model,Olmo2PreTrainedModel:()=>e.Olmo2PreTrainedModel,OlmoForCausalLM:()=>e.OlmoForCausalLM,OlmoModel:()=>e.OlmoModel,OlmoPreTrainedModel:()=>e.OlmoPreTrainedModel,OpenELMForCausalLM:()=>e.OpenELMForCausalLM,OpenELMModel:()=>e.OpenELMModel,OpenELMPreTrainedModel:()=>e.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>E.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>e.OwlViTForObjectDetection,OwlViTImageProcessor:()=>E.OwlViTImageProcessor,OwlViTModel:()=>e.OwlViTModel,OwlViTPreTrainedModel:()=>e.OwlViTPreTrainedModel,OwlViTProcessor:()=>k.OwlViTProcessor,Owlv2ForObjectDetection:()=>e.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>E.Owlv2ImageProcessor,Owlv2Model:()=>e.Owlv2Model,Owlv2PreTrainedModel:()=>e.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>e.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>e.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>k.PaliGemmaProcessor,ParakeetFeatureExtractor:()=>f.ParakeetFeatureExtractor,ParakeetForCTC:()=>e.ParakeetForCTC,ParakeetPreTrainedModel:()=>e.ParakeetPreTrainedModel,PatchTSMixerForPrediction:()=>e.PatchTSMixerForPrediction,PatchTSMixerModel:()=>e.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>e.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>e.PatchTSTForPrediction,PatchTSTModel:()=>e.PatchTSTModel,PatchTSTPreTrainedModel:()=>e.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>e.Phi3ForCausalLM,Phi3Model:()=>e.Phi3Model,Phi3PreTrainedModel:()=>e.Phi3PreTrainedModel,Phi3VForCausalLM:()=>e.Phi3VForCausalLM,Phi3VImageProcessor:()=>E.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>e.Phi3VPreTrainedModel,Phi3VProcessor:()=>k.Phi3VProcessor,PhiForCausalLM:()=>e.PhiForCausalLM,PhiModel:()=>e.PhiModel,PhiPreTrainedModel:()=>e.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PixtralImageProcessor:()=>E.PixtralImageProcessor,PixtralProcessor:()=>k.PixtralProcessor,PreTrainedModel:()=>e.PreTrainedModel,PreTrainedTokenizer:()=>r.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>e.PretrainedMixin,Processor:()=>z.Processor,PvtForImageClassification:()=>e.PvtForImageClassification,PvtImageProcessor:()=>E.PvtImageProcessor,PvtModel:()=>e.PvtModel,PvtPreTrainedModel:()=>e.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>f.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>e.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>e.PyAnnoteModel,PyAnnotePreTrainedModel:()=>e.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>k.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>e.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>e.Qwen2ForCausalLM,Qwen2Model:()=>e.Qwen2Model,Qwen2PreTrainedModel:()=>e.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>r.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>e.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>E.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>e.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>k.Qwen2VLProcessor,Qwen3ForCausalLM:()=>e.Qwen3ForCausalLM,Qwen3Model:()=>e.Qwen3Model,Qwen3PreTrainedModel:()=>e.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>e.RFDetrForObjectDetection,RFDetrModel:()=>e.RFDetrModel,RFDetrObjectDetectionOutput:()=>e.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>e.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>e.RTDetrForObjectDetection,RTDetrImageProcessor:()=>E.RTDetrImageProcessor,RTDetrModel:()=>e.RTDetrModel,RTDetrObjectDetectionOutput:()=>e.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>e.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>e.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>e.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>e.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>e.RTDetrV2PreTrainedModel,RawAudio:()=>a.RawAudio,RawImage:()=>h.RawImage,RawVideo:()=>u.RawVideo,RawVideoFrame:()=>u.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>P.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>e.ResNetForImageClassification,ResNetModel:()=>e.ResNetModel,ResNetPreTrainedModel:()=>e.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>e.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>e.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>e.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>e.RoFormerForTokenClassification,RoFormerModel:()=>e.RoFormerModel,RoFormerPreTrainedModel:()=>e.RoFormerPreTrainedModel,RoFormerTokenizer:()=>r.RoFormerTokenizer,RobertaForMaskedLM:()=>e.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>e.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>e.RobertaForSequenceClassification,RobertaForTokenClassification:()=>e.RobertaForTokenClassification,RobertaModel:()=>e.RobertaModel,RobertaPreTrainedModel:()=>e.RobertaPreTrainedModel,RobertaTokenizer:()=>r.RobertaTokenizer,Sam2ImageProcessor:()=>E.Sam2ImageProcessor,Sam2ImageSegmentationOutput:()=>e.Sam2ImageSegmentationOutput,Sam2Model:()=>e.Sam2Model,Sam2PreTrainedModel:()=>e.Sam2PreTrainedModel,Sam2Processor:()=>k.Sam2Processor,Sam2VideoProcessor:()=>k.Sam2VideoProcessor,Sam3ImageProcessor:()=>E.Sam3ImageProcessor,Sam3TrackerModel:()=>e.Sam3TrackerModel,SamImageProcessor:()=>E.SamImageProcessor,SamImageSegmentationOutput:()=>e.SamImageSegmentationOutput,SamModel:()=>e.SamModel,SamPreTrainedModel:()=>e.SamPreTrainedModel,SamProcessor:()=>k.SamProcessor,SapiensForDepthEstimation:()=>e.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>e.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>e.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>e.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>f.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>E.SegformerFeatureExtractor,SegformerForImageClassification:()=>e.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>e.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>E.SegformerImageProcessor,SegformerModel:()=>e.SegformerModel,SegformerPreTrainedModel:()=>e.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>e.Seq2SeqLMOutput,SequenceClassifierOutput:()=>e.SequenceClassifierOutput,SiglipImageProcessor:()=>E.SiglipImageProcessor,SiglipModel:()=>e.SiglipModel,SiglipPreTrainedModel:()=>e.SiglipPreTrainedModel,SiglipTextModel:()=>e.SiglipTextModel,SiglipTokenizer:()=>r.SiglipTokenizer,SiglipVisionModel:()=>e.SiglipVisionModel,SmolLM3ForCausalLM:()=>e.SmolLM3ForCausalLM,SmolLM3Model:()=>e.SmolLM3Model,SmolLM3PreTrainedModel:()=>e.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>e.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>E.SmolVLMImageProcessor,SmolVLMProcessor:()=>k.SmolVLMProcessor,SnacDecoderModel:()=>e.SnacDecoderModel,SnacEncoderModel:()=>e.SnacEncoderModel,SnacFeatureExtractor:()=>f.SnacFeatureExtractor,SnacModel:()=>e.SnacModel,SnacPreTrainedModel:()=>e.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>f.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>e.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>e.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>e.SpeechT5HifiGan,SpeechT5Model:()=>e.SpeechT5Model,SpeechT5PreTrainedModel:()=>e.SpeechT5PreTrainedModel,SpeechT5Processor:()=>k.SpeechT5Processor,SpeechT5Tokenizer:()=>r.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>e.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>e.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>e.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>e.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>e.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>r.SqueezeBertTokenizer,StableLmForCausalLM:()=>e.StableLmForCausalLM,StableLmModel:()=>e.StableLmModel,StableLmPreTrainedModel:()=>e.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>e.Starcoder2ForCausalLM,Starcoder2Model:()=>e.Starcoder2Model,Starcoder2PreTrainedModel:()=>e.Starcoder2PreTrainedModel,StoppingCriteria:()=>x.StoppingCriteria,StoppingCriteriaList:()=>x.StoppingCriteriaList,StyleTextToSpeech2Model:()=>e.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>e.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>t.SummarizationPipeline,SupertonicForConditionalGeneration:()=>e.SupertonicForConditionalGeneration,SupertonicPreTrainedModel:()=>e.SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor:()=>P.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>e.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>E.Swin2SRImageProcessor,Swin2SRModel:()=>e.Swin2SRModel,Swin2SRPreTrainedModel:()=>e.Swin2SRPreTrainedModel,SwinForImageClassification:()=>e.SwinForImageClassification,SwinForSemanticSegmentation:()=>e.SwinForSemanticSegmentation,SwinModel:()=>e.SwinModel,SwinPreTrainedModel:()=>e.SwinPreTrainedModel,T5ForConditionalGeneration:()=>e.T5ForConditionalGeneration,T5Model:()=>e.T5Model,T5PreTrainedModel:()=>e.T5PreTrainedModel,T5Tokenizer:()=>r.T5Tokenizer,TableTransformerForObjectDetection:()=>e.TableTransformerForObjectDetection,TableTransformerModel:()=>e.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>e.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>e.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>P.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>N.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>e.TokenClassifierOutput,TokenizerModel:()=>r.TokenizerModel,TopKLogitsWarper:()=>P.TopKLogitsWarper,TopPLogitsWarper:()=>P.TopPLogitsWarper,TrOCRForCausalLM:()=>e.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>e.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UltravoxModel:()=>e.UltravoxModel,UltravoxPreTrainedModel:()=>e.UltravoxPreTrainedModel,UltravoxProcessor:()=>k.UltravoxProcessor,UniSpeechForCTC:()=>e.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>e.UniSpeechForSequenceClassification,UniSpeechModel:()=>e.UniSpeechModel,UniSpeechPreTrainedModel:()=>e.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>e.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>e.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>e.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>e.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>e.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>k.VLChatProcessor,VLMImageProcessor:()=>E.VLMImageProcessor,VaultGemmaForCausalLM:()=>e.VaultGemmaForCausalLM,VaultGemmaModel:()=>e.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>e.VaultGemmaPreTrainedModel,ViTFeatureExtractor:()=>E.ViTFeatureExtractor,ViTForImageClassification:()=>e.ViTForImageClassification,ViTImageProcessor:()=>E.ViTImageProcessor,ViTMAEModel:()=>e.ViTMAEModel,ViTMAEPreTrainedModel:()=>e.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>e.ViTMSNForImageClassification,ViTMSNModel:()=>e.ViTMSNModel,ViTMSNPreTrainedModel:()=>e.ViTMSNPreTrainedModel,ViTModel:()=>e.ViTModel,ViTPreTrainedModel:()=>e.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>e.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>e.VitMatteForImageMatting,VitMatteImageProcessor:()=>E.VitMatteImageProcessor,VitMattePreTrainedModel:()=>e.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>e.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>E.VitPoseImageProcessor,VitPosePreTrainedModel:()=>e.VitPosePreTrainedModel,VitsModel:()=>e.VitsModel,VitsModelOutput:()=>e.VitsModelOutput,VitsPreTrainedModel:()=>e.VitsPreTrainedModel,VitsTokenizer:()=>r.VitsTokenizer,VoxtralForConditionalGeneration:()=>e.VoxtralForConditionalGeneration,VoxtralProcessor:()=>k.VoxtralProcessor,Wav2Vec2BertForCTC:()=>e.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>e.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>e.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>e.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>r.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>f.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>e.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>e.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>e.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>e.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>e.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>k.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>k.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>e.WavLMForAudioFrameClassification,WavLMForCTC:()=>e.WavLMForCTC,WavLMForSequenceClassification:()=>e.WavLMForSequenceClassification,WavLMForXVector:()=>e.WavLMForXVector,WavLMModel:()=>e.WavLMModel,WavLMPreTrainedModel:()=>e.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>f.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>e.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>e.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>e.WhisperForConditionalGeneration,WhisperModel:()=>e.WhisperModel,WhisperPreTrainedModel:()=>e.WhisperPreTrainedModel,WhisperProcessor:()=>k.WhisperProcessor,WhisperTextStreamer:()=>N.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>P.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>r.WhisperTokenizer,XLMForQuestionAnswering:()=>e.XLMForQuestionAnswering,XLMForSequenceClassification:()=>e.XLMForSequenceClassification,XLMForTokenClassification:()=>e.XLMForTokenClassification,XLMModel:()=>e.XLMModel,XLMPreTrainedModel:()=>e.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>e.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>e.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>e.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>e.XLMRobertaForTokenClassification,XLMRobertaModel:()=>e.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>e.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>r.XLMRobertaTokenizer,XLMTokenizer:()=>r.XLMTokenizer,XLMWithLMHeadModel:()=>e.XLMWithLMHeadModel,XVectorOutput:()=>e.XVectorOutput,YolosFeatureExtractor:()=>E.YolosFeatureExtractor,YolosForObjectDetection:()=>e.YolosForObjectDetection,YolosImageProcessor:()=>E.YolosImageProcessor,YolosModel:()=>e.YolosModel,YolosObjectDetectionOutput:()=>e.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>e.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>p.bankers_round,cat:()=>l.cat,cos_sim:()=>p.cos_sim,dot:()=>p.dot,dynamic_time_warping:()=>p.dynamic_time_warping,env:()=>d.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>o.getCacheShapes,hamming:()=>a.hamming,hanning:()=>a.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>p.interpolate_data,is_chinese_char:()=>r.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>h.load_image,load_video:()=>u.load_video,log_softmax:()=>p.log_softmax,magnitude:()=>p.magnitude,matmul:()=>l.matmul,max:()=>p.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>p.medianFilter,mel_filter_bank:()=>a.mel_filter_bank,min:()=>p.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>p.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,randn:()=>l.randn,read_audio:()=>a.read_audio,rfft:()=>l.rfft,round:()=>p.round,slice:()=>l.slice,softmax:()=>p.softmax,spectrogram:()=>a.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>a.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var d=wt("./src/env.js"),t=wt("./src/pipelines.js"),e=wt("./src/models.js"),r=wt("./src/tokenizers.js"),o=wt("./src/configs.js"),a=wt("./src/utils/audio.js"),h=wt("./src/utils/image.js"),u=wt("./src/utils/video.js"),l=wt("./src/utils/tensor.js"),p=wt("./src/utils/maths.js"),w=wt("./src/base/feature_extraction_utils.js"),f=wt("./src/models/feature_extractors.js"),i=wt("./src/models/auto/feature_extraction_auto.js"),y=wt("./src/base/image_processors_utils.js"),E=wt("./src/models/image_processors.js"),S=wt("./src/models/auto/image_processing_auto.js"),z=wt("./src/base/processing_utils.js"),k=wt("./src/models/processors.js"),A=wt("./src/models/auto/processing_auto.js"),N=wt("./src/generation/streamers.js"),x=wt("./src/generation/stopping_criteria.js"),P=wt("./src/generation/logits_process.js")})();Tf=s.ASTFeatureExtractor,vf=s.ASTForAudioClassification,Pf=s.ASTModel,bf=s.ASTPreTrainedModel,xf=s.AlbertForMaskedLM,yf=s.AlbertForQuestionAnswering,Ef=s.AlbertForSequenceClassification,Cf=s.AlbertModel,kf=s.AlbertPreTrainedModel,Ff=s.AlbertTokenizer,Af=s.ArceeForCausalLM,If=s.ArceeModel,Sf=s.ArceePreTrainedModel,Df=s.AudioClassificationPipeline,Lf=s.AutoConfig,Of=s.AutoFeatureExtractor,Rf=s.AutoImageProcessor,Bf=s.AutoModel,Nf=s.AutoModelForAudioClassification,jf=s.AutoModelForAudioFrameClassification,Vf=s.AutoModelForAudioTextToText,Uf=s.AutoModelForCTC,zf=s.AutoModelForCausalLM,Wf=s.AutoModelForDepthEstimation,Gf=s.AutoModelForDocumentQuestionAnswering,Kf=s.AutoModelForImageClassification,$f=s.AutoModelForImageFeatureExtraction,Hf=s.AutoModelForImageMatting,Qf=s.AutoModelForImageSegmentation,Xf=s.AutoModelForImageTextToText,Jf=s.AutoModelForImageToImage,qf=s.AutoModelForMaskGeneration,Yf=s.AutoModelForMaskedLM,Zf=s.AutoModelForNormalEstimation,eg=s.AutoModelForObjectDetection,tg=s.AutoModelForPoseEstimation,rg=s.AutoModelForQuestionAnswering,sg=s.AutoModelForSemanticSegmentation,og=s.AutoModelForSeq2SeqLM,ng=s.AutoModelForSequenceClassification,ag=s.AutoModelForSpeechSeq2Seq,ig=s.AutoModelForTextToSpectrogram,lg=s.AutoModelForTextToWaveform,cg=s.AutoModelForTokenClassification,dg=s.AutoModelForUniversalSegmentation,_g=s.AutoModelForVision2Seq,ug=s.AutoModelForXVector,pg=s.AutoModelForZeroShotObjectDetection,mg=s.AutoProcessor,hg=s.AutoTokenizer,fg=s.AutomaticSpeechRecognitionPipeline,gg=s.BackgroundRemovalPipeline,Mg=s.BartForConditionalGeneration,wg=s.BartForSequenceClassification,Tg=s.BartModel,vg=s.BartPretrainedModel,Pg=s.BartTokenizer,bg=s.BaseModelOutput,xg=s.BaseStreamer,yg=s.BeitFeatureExtractor,Eg=s.BeitForImageClassification,Cg=s.BeitModel,kg=s.BeitPreTrainedModel,Fg=s.BertForMaskedLM,Ag=s.BertForQuestionAnswering,Ig=s.BertForSequenceClassification,Sg=s.BertForTokenClassification,Dg=s.BertModel,Lg=s.BertPreTrainedModel,Og=s.BertTokenizer,Rg=s.BitImageProcessor,Bg=s.BlenderbotForConditionalGeneration,Ng=s.BlenderbotModel,jg=s.BlenderbotPreTrainedModel,Vg=s.BlenderbotSmallForConditionalGeneration,Ug=s.BlenderbotSmallModel,zg=s.BlenderbotSmallPreTrainedModel,Wg=s.BlenderbotSmallTokenizer,Gg=s.BlenderbotTokenizer,Kg=s.BloomForCausalLM,$g=s.BloomModel,Hg=s.BloomPreTrainedModel,Qg=s.BloomTokenizer,Xg=s.CLIPFeatureExtractor,Jg=s.CLIPImageProcessor,qg=s.CLIPModel,Yg=s.CLIPPreTrainedModel,Zg=s.CLIPSegForImageSegmentation,eM=s.CLIPSegModel,tM=s.CLIPSegPreTrainedModel,rM=s.CLIPTextModel,sM=s.CLIPTextModelWithProjection,oM=s.CLIPTokenizer,nM=s.CLIPVisionModel,aM=s.CLIPVisionModelWithProjection,iM=s.CamembertForMaskedLM,lM=s.CamembertForQuestionAnswering,cM=s.CamembertForSequenceClassification,dM=s.CamembertForTokenClassification,_M=s.CamembertModel,uM=s.CamembertPreTrainedModel,pM=s.CamembertTokenizer,mM=s.CausalLMOutput,hM=s.CausalLMOutputWithPast,fM=s.ChineseCLIPFeatureExtractor,gM=s.ChineseCLIPModel,MM=s.ChineseCLIPPreTrainedModel,wM=s.ClapAudioModelWithProjection,TM=s.ClapFeatureExtractor,vM=s.ClapModel,PM=s.ClapPreTrainedModel,bM=s.ClapTextModelWithProjection,xM=s.ClassifierFreeGuidanceLogitsProcessor,yM=s.CodeGenForCausalLM,EM=s.CodeGenModel,CM=s.CodeGenPreTrainedModel,kM=s.CodeGenTokenizer,FM=s.CodeLlamaTokenizer,AM=s.CohereForCausalLM,IM=s.CohereModel,SM=s.CoherePreTrainedModel,DM=s.CohereTokenizer,LM=s.ConvBertForMaskedLM,OM=s.ConvBertForQuestionAnswering,RM=s.ConvBertForSequenceClassification,BM=s.ConvBertForTokenClassification,NM=s.ConvBertModel,jM=s.ConvBertPreTrainedModel,VM=s.ConvBertTokenizer,UM=s.ConvNextFeatureExtractor,zM=s.ConvNextForImageClassification,WM=s.ConvNextImageProcessor,GM=s.ConvNextModel,KM=s.ConvNextPreTrainedModel,$M=s.ConvNextV2ForImageClassification,HM=s.ConvNextV2Model,QM=s.ConvNextV2PreTrainedModel,XM=s.DFineForObjectDetection,JM=s.DFineModel,qM=s.DFinePreTrainedModel,YM=s.DINOv3ConvNextModel,ZM=s.DINOv3ConvNextPreTrainedModel,ew=s.DINOv3ViTImageProcessor,tw=s.DINOv3ViTModel,rw=s.DINOv3ViTPreTrainedModel,sw=s.DPTFeatureExtractor,ow=s.DPTForDepthEstimation,nw=s.DPTImageProcessor,aw=s.DPTModel,iw=s.DPTPreTrainedModel,lw=s.DacDecoderModel,cw=s.DacDecoderOutput,dw=s.DacEncoderModel,_w=s.DacEncoderOutput,uw=s.DacFeatureExtractor,pw=s.DacModel,mw=s.DacPreTrainedModel,hw=s.DataTypeMap,fw=s.DebertaForMaskedLM,gw=s.DebertaForQuestionAnswering,Mw=s.DebertaForSequenceClassification,ww=s.DebertaForTokenClassification,Tw=s.DebertaModel,vw=s.DebertaPreTrainedModel,Pw=s.DebertaTokenizer,bw=s.DebertaV2ForMaskedLM,xw=s.DebertaV2ForQuestionAnswering,yw=s.DebertaV2ForSequenceClassification,Ew=s.DebertaV2ForTokenClassification,Cw=s.DebertaV2Model,kw=s.DebertaV2PreTrainedModel,Fw=s.DebertaV2Tokenizer,Aw=s.DecisionTransformerModel,Iw=s.DecisionTransformerPreTrainedModel,Sw=s.DeiTFeatureExtractor,Dw=s.DeiTForImageClassification,Lw=s.DeiTImageProcessor,Ow=s.DeiTModel,Rw=s.DeiTPreTrainedModel,Bw=s.DepthAnythingForDepthEstimation,Nw=s.DepthAnythingPreTrainedModel,jw=s.DepthEstimationPipeline,Vw=s.DepthProForDepthEstimation,Uw=s.DepthProPreTrainedModel,zw=s.DetrFeatureExtractor,Ww=s.DetrForObjectDetection,Gw=s.DetrForSegmentation,Kw=s.DetrImageProcessor,$w=s.DetrModel,Hw=s.DetrObjectDetectionOutput,Qw=s.DetrPreTrainedModel,Xw=s.DetrSegmentationOutput,Jw=s.Dinov2ForImageClassification,qw=s.Dinov2Model,Yw=s.Dinov2PreTrainedModel,Zw=s.Dinov2WithRegistersForImageClassification,eT=s.Dinov2WithRegistersModel,tT=s.Dinov2WithRegistersPreTrainedModel,rT=s.DistilBertForMaskedLM,sT=s.DistilBertForQuestionAnswering,oT=s.DistilBertForSequenceClassification,nT=s.DistilBertForTokenClassification,aT=s.DistilBertModel,iT=s.DistilBertPreTrainedModel,lT=s.DistilBertTokenizer,cT=s.DocumentQuestionAnsweringPipeline,dT=s.DonutFeatureExtractor,_T=s.DonutImageProcessor,uT=s.DonutSwinModel,pT=s.DonutSwinPreTrainedModel,mT=s.EdgeTamModel,hT=s.EfficientNetForImageClassification,fT=s.EfficientNetImageProcessor,gT=s.EfficientNetModel,MT=s.EfficientNetPreTrainedModel,wT=s.ElectraForMaskedLM,TT=s.ElectraForQuestionAnswering,vT=s.ElectraForSequenceClassification,PT=s.ElectraForTokenClassification,bT=s.ElectraModel,xT=s.ElectraPreTrainedModel,yT=s.ElectraTokenizer,ET=s.EncodecFeatureExtractor,CT=s.EosTokenCriteria,kT=s.Ernie4_5ForCausalLM,FT=s.Ernie4_5Model,AT=s.Ernie4_5PreTrainedModel,IT=s.EsmForMaskedLM,ST=s.EsmForSequenceClassification,DT=s.EsmForTokenClassification,LT=s.EsmModel,OT=s.EsmPreTrainedModel,RT=s.EsmTokenizer,BT=s.ExaoneForCausalLM,NT=s.ExaoneModel,jT=s.ExaonePreTrainedModel,VT=s.FFT,UT=s.FalconForCausalLM,zT=s.FalconModel,WT=s.FalconPreTrainedModel,GT=s.FalconTokenizer,KT=s.FastViTForImageClassification,$T=s.FastViTModel,HT=s.FastViTPreTrainedModel,QT=s.FeatureExtractionPipeline,XT=s.FeatureExtractor,JT=s.FillMaskPipeline,qT=s.Florence2ForConditionalGeneration,YT=s.Florence2PreTrainedModel,ZT=s.Florence2Processor,ev=s.ForcedBOSTokenLogitsProcessor,tv=s.ForcedEOSTokenLogitsProcessor,rv=s.GLPNFeatureExtractor,sv=s.GLPNForDepthEstimation,ov=s.GLPNModel,nv=s.GLPNPreTrainedModel,av=s.GPT2LMHeadModel,iv=s.GPT2Model,lv=s.GPT2PreTrainedModel,cv=s.GPT2Tokenizer,dv=s.GPTBigCodeForCausalLM,_v=s.GPTBigCodeModel,uv=s.GPTBigCodePreTrainedModel,pv=s.GPTJForCausalLM,mv=s.GPTJModel,hv=s.GPTJPreTrainedModel,fv=s.GPTNeoForCausalLM,gv=s.GPTNeoModel,Mv=s.GPTNeoPreTrainedModel,wv=s.GPTNeoXForCausalLM,Tv=s.GPTNeoXModel,vv=s.GPTNeoXPreTrainedModel,Pv=s.GPTNeoXTokenizer,bv=s.Gemma2ForCausalLM,xv=s.Gemma2Model,yv=s.Gemma2PreTrainedModel,Ev=s.Gemma3ForCausalLM,Cv=s.Gemma3Model,kv=s.Gemma3PreTrainedModel,Fv=s.Gemma3nAudioFeatureExtractor,Av=s.Gemma3nForConditionalGeneration,Iv=s.Gemma3nPreTrainedModel,Sv=s.Gemma3nProcessor,Dv=s.GemmaForCausalLM,Lv=s.GemmaModel,Ov=s.GemmaPreTrainedModel,Rv=s.GemmaTokenizer,Bv=s.GlmForCausalLM,Nv=s.GlmModel,jv=s.GlmPreTrainedModel,Vv=s.GraniteForCausalLM,Uv=s.GraniteModel,zv=s.GraniteMoeHybridForCausalLM,Wv=s.GraniteMoeHybridModel,Gv=s.GraniteMoeHybridPreTrainedModel,Kv=s.GranitePreTrainedModel,$v=s.Grok1Tokenizer,Hv=s.GroundingDinoForObjectDetection,Qv=s.GroundingDinoImageProcessor,Xv=s.GroundingDinoPreTrainedModel,Jv=s.GroundingDinoProcessor,qv=s.GroupViTModel,Yv=s.GroupViTPreTrainedModel,Zv=s.HeliumForCausalLM,eP=s.HeliumModel,tP=s.HeliumPreTrainedModel,rP=s.HerbertTokenizer,sP=s.HieraForImageClassification,oP=s.HieraModel,nP=s.HieraPreTrainedModel,aP=s.HubertForCTC,iP=s.HubertForSequenceClassification,lP=s.HubertModel,cP=s.HubertPreTrainedModel,dP=s.IJepaForImageClassification,_P=s.IJepaModel,uP=s.IJepaPreTrainedModel,pP=s.Idefics3ForConditionalGeneration,mP=s.Idefics3ImageProcessor,hP=s.Idefics3PreTrainedModel,fP=s.Idefics3Processor,gP=s.ImageClassificationPipeline,MP=s.ImageFeatureExtractionPipeline,wP=s.ImageFeatureExtractor,TP=s.ImageMattingOutput,vP=s.ImageProcessor,PP=s.ImageSegmentationPipeline,bP=s.ImageToImagePipeline,xP=s.ImageToTextPipeline,yP=s.InterruptableStoppingCriteria,EP=s.JAISLMHeadModel,CP=s.JAISModel,kP=s.JAISPreTrainedModel,FP=s.JinaCLIPImageProcessor,AP=s.JinaCLIPModel,IP=s.JinaCLIPPreTrainedModel,SP=s.JinaCLIPProcessor,DP=s.JinaCLIPTextModel,LP=s.JinaCLIPVisionModel,OP=s.Lfm2ForCausalLM,RP=s.Lfm2Model,BP=s.Lfm2PreTrainedModel,NP=s.LiteWhisperForConditionalGeneration,jP=s.Llama4ForCausalLM,VP=s.Llama4PreTrainedModel,UP=s.LlamaForCausalLM,zP=s.LlamaModel,WP=s.LlamaPreTrainedModel,GP=s.LlamaTokenizer,KP=s.LlavaForConditionalGeneration,$P=s.LlavaOnevisionForConditionalGeneration,HP=s.LlavaOnevisionImageProcessor,QP=s.LlavaPreTrainedModel,XP=s.LlavaProcessor,JP=s.LlavaQwen2ForCausalLM,qP=s.LogitsProcessor,YP=s.LogitsProcessorList,ZP=s.LogitsWarper,eb=s.LongT5ForConditionalGeneration,tb=s.LongT5Model,rb=s.LongT5PreTrainedModel,sb=s.M2M100ForConditionalGeneration,ob=s.M2M100Model,nb=s.M2M100PreTrainedModel,ab=s.M2M100Tokenizer,ib=s.MBart50Tokenizer,lb=s.MBartForCausalLM,cb=s.MBartForConditionalGeneration,db=s.MBartForSequenceClassification,_b=s.MBartModel,ub=s.MBartPreTrainedModel,pb=s.MBartTokenizer,mb=s.MPNetForMaskedLM,hb=s.MPNetForQuestionAnswering,fb=s.MPNetForSequenceClassification,gb=s.MPNetForTokenClassification,Mb=s.MPNetModel,wb=s.MPNetPreTrainedModel,Tb=s.MPNetTokenizer,vb=s.MT5ForConditionalGeneration,Pb=s.MT5Model,bb=s.MT5PreTrainedModel,xb=s.MarianMTModel,yb=s.MarianModel,Eb=s.MarianPreTrainedModel,Cb=s.MarianTokenizer,kb=s.Mask2FormerImageProcessor,Fb=s.MaskFormerFeatureExtractor,Ab=s.MaskFormerForInstanceSegmentation,Ib=s.MaskFormerImageProcessor,Sb=s.MaskFormerModel,Db=s.MaskFormerPreTrainedModel,Lb=s.MaskedLMOutput,Ob=s.MaxLengthCriteria,Rb=s.Metric3DForDepthEstimation,Bb=s.Metric3DPreTrainedModel,Nb=s.Metric3Dv2ForDepthEstimation,jb=s.Metric3Dv2PreTrainedModel,Vb=s.MgpstrForSceneTextRecognition,Ub=s.MgpstrModelOutput,zb=s.MgpstrPreTrainedModel,Wb=s.MgpstrProcessor,Gb=s.MgpstrTokenizer,Kb=s.MimiDecoderModel,$b=s.MimiDecoderOutput,Hb=s.MimiEncoderModel,Qb=s.MimiEncoderOutput,Xb=s.MimiModel,Jb=s.MimiPreTrainedModel,qb=s.MinLengthLogitsProcessor,Yb=s.MinNewTokensLengthLogitsProcessor,Zb=s.Ministral3ForCausalLM,ex=s.Ministral3Model,tx=s.Ministral3PreTrainedModel,rx=s.MinistralForCausalLM,sx=s.MinistralModel,ox=s.MinistralPreTrainedModel,nx=s.Mistral3ForConditionalGeneration,ax=s.MistralForCausalLM,ix=s.MistralModel,lx=s.MistralPreTrainedModel,cx=s.MobileBertForMaskedLM,dx=s.MobileBertForQuestionAnswering,_x=s.MobileBertForSequenceClassification,ux=s.MobileBertModel,px=s.MobileBertPreTrainedModel,mx=s.MobileBertTokenizer,hx=s.MobileLLMForCausalLM,fx=s.MobileLLMModel,gx=s.MobileLLMPreTrainedModel,Mx=s.MobileNetV1FeatureExtractor,wx=s.MobileNetV1ForImageClassification,Tx=s.MobileNetV1ForSemanticSegmentation,vx=s.MobileNetV1ImageProcessor,Px=s.MobileNetV1Model,bx=s.MobileNetV1PreTrainedModel,xx=s.MobileNetV2FeatureExtractor,yx=s.MobileNetV2ForImageClassification,Ex=s.MobileNetV2ForSemanticSegmentation,Cx=s.MobileNetV2ImageProcessor,kx=s.MobileNetV2Model,Fx=s.MobileNetV2PreTrainedModel,Ax=s.MobileNetV3FeatureExtractor,Ix=s.MobileNetV3ForImageClassification,Sx=s.MobileNetV3ForSemanticSegmentation,Dx=s.MobileNetV3ImageProcessor,Lx=s.MobileNetV3Model,Ox=s.MobileNetV3PreTrainedModel,Rx=s.MobileNetV4FeatureExtractor,Bx=s.MobileNetV4ForImageClassification,Nx=s.MobileNetV4ForSemanticSegmentation,jx=s.MobileNetV4ImageProcessor,Vx=s.MobileNetV4Model,Ux=s.MobileNetV4PreTrainedModel,zx=s.MobileViTFeatureExtractor,Wx=s.MobileViTForImageClassification,Gx=s.MobileViTImageProcessor,Kx=s.MobileViTModel,$x=s.MobileViTPreTrainedModel,Hx=s.MobileViTV2ForImageClassification,Qx=s.MobileViTV2Model,Xx=s.MobileViTV2PreTrainedModel,Jx=s.ModelOutput,qx=s.ModernBertDecoderForCausalLM,Yx=s.ModernBertDecoderModel,Zx=s.ModernBertDecoderPreTrainedModel,ey=s.ModernBertForMaskedLM,ty=s.ModernBertForSequenceClassification,ry=s.ModernBertForTokenClassification,sy=s.ModernBertModel,oy=s.ModernBertPreTrainedModel,ny=s.Moondream1ForConditionalGeneration,ay=s.MoonshineFeatureExtractor,iy=s.MoonshineForConditionalGeneration,ly=s.MoonshineModel,cy=s.MoonshinePreTrainedModel,dy=s.MoonshineProcessor,_y=s.MptForCausalLM,uy=s.MptModel,py=s.MptPreTrainedModel,my=s.MultiModalityCausalLM,hy=s.MultiModalityPreTrainedModel,fy=s.MusicgenForCausalLM,gy=s.MusicgenForConditionalGeneration,My=s.MusicgenModel,wy=s.MusicgenPreTrainedModel,Ty=s.NanoChatForCausalLM,vy=s.NanoChatModel,Py=s.NanoChatPreTrainedModel,by=s.NeoBertForMaskedLM,xy=s.NeoBertForQuestionAnswering,yy=s.NeoBertForSequenceClassification,Ey=s.NeoBertForTokenClassification,Cy=s.NeoBertModel,ky=s.NeoBertPreTrainedModel,Fy=s.NllbTokenizer,Ay=s.NoBadWordsLogitsProcessor,Iy=s.NoRepeatNGramLogitsProcessor,Sy=s.NomicBertModel,Dy=s.NomicBertPreTrainedModel,Ly=s.NougatImageProcessor,Oy=s.NougatTokenizer,Ry=s.OPTForCausalLM,By=s.OPTModel,Ny=s.OPTPreTrainedModel,jy=s.ObjectDetectionPipeline,Vy=s.Olmo2ForCausalLM,Uy=s.Olmo2Model,zy=s.Olmo2PreTrainedModel,Wy=s.OlmoForCausalLM,Gy=s.OlmoModel,Ky=s.OlmoPreTrainedModel,$y=s.OpenELMForCausalLM,Hy=s.OpenELMModel,Qy=s.OpenELMPreTrainedModel,Xy=s.OwlViTFeatureExtractor,Jy=s.OwlViTForObjectDetection,qy=s.OwlViTImageProcessor,Yy=s.OwlViTModel,Zy=s.OwlViTPreTrainedModel,eE=s.OwlViTProcessor,tE=s.Owlv2ForObjectDetection,rE=s.Owlv2ImageProcessor,sE=s.Owlv2Model,oE=s.Owlv2PreTrainedModel,nE=s.PaliGemmaForConditionalGeneration,aE=s.PaliGemmaPreTrainedModel,iE=s.PaliGemmaProcessor,lE=s.ParakeetFeatureExtractor,cE=s.ParakeetForCTC,dE=s.ParakeetPreTrainedModel,_E=s.PatchTSMixerForPrediction,uE=s.PatchTSMixerModel,pE=s.PatchTSMixerPreTrainedModel,mE=s.PatchTSTForPrediction,hE=s.PatchTSTModel,fE=s.PatchTSTPreTrainedModel,gE=s.Phi3ForCausalLM,ME=s.Phi3Model,wE=s.Phi3PreTrainedModel,TE=s.Phi3VForCausalLM,vE=s.Phi3VImageProcessor,PE=s.Phi3VPreTrainedModel,bE=s.Phi3VProcessor,xE=s.PhiForCausalLM,yE=s.PhiModel,EE=s.PhiPreTrainedModel,CE=s.Pipeline,kE=s.PixtralImageProcessor,FE=s.PixtralProcessor,AE=s.PreTrainedModel,IE=s.PreTrainedTokenizer,SE=s.PretrainedConfig,DE=s.PretrainedMixin,LE=s.Processor,OE=s.PvtForImageClassification,RE=s.PvtImageProcessor,BE=s.PvtModel,NE=s.PvtPreTrainedModel,jE=s.PyAnnoteFeatureExtractor,VE=s.PyAnnoteForAudioFrameClassification,UE=s.PyAnnoteModel,zE=s.PyAnnotePreTrainedModel,WE=s.PyAnnoteProcessor,GE=s.QuestionAnsweringModelOutput,KE=s.QuestionAnsweringPipeline,$E=s.Qwen2ForCausalLM,HE=s.Qwen2Model,QE=s.Qwen2PreTrainedModel,XE=s.Qwen2Tokenizer,JE=s.Qwen2VLForConditionalGeneration,qE=s.Qwen2VLImageProcessor,YE=s.Qwen2VLPreTrainedModel,ZE=s.Qwen2VLProcessor,eC=s.Qwen3ForCausalLM,tC=s.Qwen3Model,rC=s.Qwen3PreTrainedModel,sC=s.RFDetrForObjectDetection,oC=s.RFDetrModel,nC=s.RFDetrObjectDetectionOutput,aC=s.RFDetrPreTrainedModel,iC=s.RTDetrForObjectDetection,lC=s.RTDetrImageProcessor,cC=s.RTDetrModel,dC=s.RTDetrObjectDetectionOutput,_C=s.RTDetrPreTrainedModel,uC=s.RTDetrV2ForObjectDetection,pC=s.RTDetrV2Model,mC=s.RTDetrV2ObjectDetectionOutput,hC=s.RTDetrV2PreTrainedModel,fC=s.RawAudio,gC=s.RawImage,MC=s.RawVideo,wC=s.RawVideoFrame,TC=s.RepetitionPenaltyLogitsProcessor,vC=s.ResNetForImageClassification,PC=s.ResNetModel,bC=s.ResNetPreTrainedModel,xC=s.RoFormerForMaskedLM,yC=s.RoFormerForQuestionAnswering,EC=s.RoFormerForSequenceClassification,CC=s.RoFormerForTokenClassification,kC=s.RoFormerModel,FC=s.RoFormerPreTrainedModel,AC=s.RoFormerTokenizer,IC=s.RobertaForMaskedLM,SC=s.RobertaForQuestionAnswering,DC=s.RobertaForSequenceClassification,LC=s.RobertaForTokenClassification,OC=s.RobertaModel,RC=s.RobertaPreTrainedModel,BC=s.RobertaTokenizer,NC=s.Sam2ImageProcessor,jC=s.Sam2ImageSegmentationOutput,VC=s.Sam2Model,UC=s.Sam2PreTrainedModel,zC=s.Sam2Processor,WC=s.Sam2VideoProcessor,GC=s.Sam3ImageProcessor,KC=s.Sam3TrackerModel,$C=s.SamImageProcessor,HC=s.SamImageSegmentationOutput,QC=s.SamModel,XC=s.SamPreTrainedModel,JC=s.SamProcessor,qC=s.SapiensForDepthEstimation,YC=s.SapiensForNormalEstimation,ZC=s.SapiensForSemanticSegmentation,ek=s.SapiensPreTrainedModel,tk=s.SeamlessM4TFeatureExtractor,rk=s.SegformerFeatureExtractor,sk=s.SegformerForImageClassification,ok=s.SegformerForSemanticSegmentation,nk=s.SegformerImageProcessor,ak=s.SegformerModel,ik=s.SegformerPreTrainedModel,lk=s.Seq2SeqLMOutput,ck=s.SequenceClassifierOutput,dk=s.SiglipImageProcessor,_k=s.SiglipModel,uk=s.SiglipPreTrainedModel,pk=s.SiglipTextModel,mk=s.SiglipTokenizer,hk=s.SiglipVisionModel,fk=s.SmolLM3ForCausalLM,gk=s.SmolLM3Model,Mk=s.SmolLM3PreTrainedModel,wk=s.SmolVLMForConditionalGeneration,Tk=s.SmolVLMImageProcessor,vk=s.SmolVLMProcessor,Pk=s.SnacDecoderModel,bk=s.SnacEncoderModel,xk=s.SnacFeatureExtractor,yk=s.SnacModel,Ek=s.SnacPreTrainedModel,Ck=s.SpeechT5FeatureExtractor,kk=s.SpeechT5ForSpeechToText,Fk=s.SpeechT5ForTextToSpeech,Ak=s.SpeechT5HifiGan,Ik=s.SpeechT5Model,Sk=s.SpeechT5PreTrainedModel,Dk=s.SpeechT5Processor,Lk=s.SpeechT5Tokenizer,Ok=s.SqueezeBertForMaskedLM,Rk=s.SqueezeBertForQuestionAnswering,Bk=s.SqueezeBertForSequenceClassification,Nk=s.SqueezeBertModel,jk=s.SqueezeBertPreTrainedModel,Vk=s.SqueezeBertTokenizer,Uk=s.StableLmForCausalLM,zk=s.StableLmModel,Wk=s.StableLmPreTrainedModel,Gk=s.Starcoder2ForCausalLM,Kk=s.Starcoder2Model,$k=s.Starcoder2PreTrainedModel,Hk=s.StoppingCriteria,Qk=s.StoppingCriteriaList,Xk=s.StyleTextToSpeech2Model,Jk=s.StyleTextToSpeech2PreTrainedModel,qk=s.SummarizationPipeline,Yk=s.SupertonicForConditionalGeneration,Zk=s.SupertonicPreTrainedModel,eF=s.SuppressTokensAtBeginLogitsProcessor,tF=s.Swin2SRForImageSuperResolution,rF=s.Swin2SRImageProcessor,sF=s.Swin2SRModel,oF=s.Swin2SRPreTrainedModel,nF=s.SwinForImageClassification,aF=s.SwinForSemanticSegmentation,iF=s.SwinModel,lF=s.SwinPreTrainedModel,cF=s.T5ForConditionalGeneration,dF=s.T5Model,_F=s.T5PreTrainedModel,uF=s.T5Tokenizer,pF=s.TableTransformerForObjectDetection,mF=s.TableTransformerModel,hF=s.TableTransformerObjectDetectionOutput,fF=s.TableTransformerPreTrainedModel,gF=s.TemperatureLogitsWarper,MF=s.Tensor,wF=s.Text2TextGenerationPipeline,TF=s.TextClassificationPipeline,vF=s.TextGenerationPipeline,PF=s.TextStreamer,bF=s.TextToAudioPipeline,xF=s.TokenClassificationPipeline,yF=s.TokenClassifierOutput,EF=s.TokenizerModel,CF=s.TopKLogitsWarper,kF=s.TopPLogitsWarper,FF=s.TrOCRForCausalLM,AF=s.TrOCRPreTrainedModel,IF=s.TranslationPipeline,SF=s.UltravoxModel,DF=s.UltravoxPreTrainedModel,LF=s.UltravoxProcessor,OF=s.UniSpeechForCTC,RF=s.UniSpeechForSequenceClassification,BF=s.UniSpeechModel,NF=s.UniSpeechPreTrainedModel,jF=s.UniSpeechSatForAudioFrameClassification,VF=s.UniSpeechSatForCTC,UF=s.UniSpeechSatForSequenceClassification,zF=s.UniSpeechSatModel,WF=s.UniSpeechSatPreTrainedModel,GF=s.VLChatProcessor,KF=s.VLMImageProcessor,$F=s.VaultGemmaForCausalLM,HF=s.VaultGemmaModel,QF=s.VaultGemmaPreTrainedModel,XF=s.ViTFeatureExtractor,JF=s.ViTForImageClassification,qF=s.ViTImageProcessor,YF=s.ViTMAEModel,ZF=s.ViTMAEPreTrainedModel,eA=s.ViTMSNForImageClassification,tA=s.ViTMSNModel,rA=s.ViTMSNPreTrainedModel,sA=s.ViTModel,oA=s.ViTPreTrainedModel,nA=s.VisionEncoderDecoderModel,aA=s.VitMatteForImageMatting,iA=s.VitMatteImageProcessor,lA=s.VitMattePreTrainedModel,cA=s.VitPoseForPoseEstimation,dA=s.VitPoseImageProcessor,_A=s.VitPosePreTrainedModel,uA=s.VitsModel,pA=s.VitsModelOutput,mA=s.VitsPreTrainedModel,hA=s.VitsTokenizer,fA=s.VoxtralForConditionalGeneration,gA=s.VoxtralProcessor,MA=s.Wav2Vec2BertForCTC,wA=s.Wav2Vec2BertForSequenceClassification,TA=s.Wav2Vec2BertModel,vA=s.Wav2Vec2BertPreTrainedModel,PA=s.Wav2Vec2CTCTokenizer,bA=s.Wav2Vec2FeatureExtractor,xA=s.Wav2Vec2ForAudioFrameClassification,yA=s.Wav2Vec2ForCTC,EA=s.Wav2Vec2ForSequenceClassification,CA=s.Wav2Vec2Model,kA=s.Wav2Vec2PreTrainedModel,FA=s.Wav2Vec2Processor,AA=s.Wav2Vec2ProcessorWithLM,IA=s.WavLMForAudioFrameClassification,SA=s.WavLMForCTC,DA=s.WavLMForSequenceClassification,LA=s.WavLMForXVector,OA=s.WavLMModel,RA=s.WavLMPreTrainedModel,BA=s.WeSpeakerFeatureExtractor,NA=s.WeSpeakerResNetModel,jA=s.WeSpeakerResNetPreTrainedModel,VA=s.WhisperFeatureExtractor,UA=s.WhisperForConditionalGeneration,zA=s.WhisperModel,WA=s.WhisperPreTrainedModel,GA=s.WhisperProcessor,KA=s.WhisperTextStreamer,$A=s.WhisperTimeStampLogitsProcessor,HA=s.WhisperTokenizer,QA=s.XLMForQuestionAnswering,XA=s.XLMForSequenceClassification,JA=s.XLMForTokenClassification,qA=s.XLMModel,YA=s.XLMPreTrainedModel,ZA=s.XLMRobertaForMaskedLM,eI=s.XLMRobertaForQuestionAnswering,tI=s.XLMRobertaForSequenceClassification,rI=s.XLMRobertaForTokenClassification,sI=s.XLMRobertaModel,oI=s.XLMRobertaPreTrainedModel,nI=s.XLMRobertaTokenizer,aI=s.XLMTokenizer,iI=s.XLMWithLMHeadModel,lI=s.XVectorOutput,cI=s.YolosFeatureExtractor,dI=s.YolosForObjectDetection,_I=s.YolosImageProcessor,uI=s.YolosModel,pI=s.YolosObjectDetectionOutput,mI=s.YolosPreTrainedModel,hI=s.ZeroShotAudioClassificationPipeline,fI=s.ZeroShotClassificationPipeline,gI=s.ZeroShotImageClassificationPipeline,MI=s.ZeroShotObjectDetectionPipeline,wI=s.bankers_round,TI=s.cat,vI=s.cos_sim,PI=s.dot,bI=s.dynamic_time_warping,xI=s.env,yI=s.full,EI=s.full_like,CI=s.getCacheShapes,kI=s.hamming,FI=s.hanning,AI=s.interpolate,II=s.interpolate_4d,SI=s.interpolate_data,DI=s.is_chinese_char,LI=s.layer_norm,OI=s.load_image,RI=s.load_video,BI=s.log_softmax,NI=s.magnitude,jI=s.matmul,VI=s.max,UI=s.mean,zI=s.mean_pooling,WI=s.medianFilter,GI=s.mel_filter_bank,KI=s.min,$I=s.ones,HI=s.ones_like,QI=s.permute,XI=s.permute_data,JI=s.pipeline,qI=s.quantize_embeddings,YI=s.rand,ZI=s.randn,eS=s.read_audio,tS=s.rfft,rS=s.round,sS=s.slice,oS=s.softmax,nS=s.spectrogram,aS=s.stack,iS=s.std_mean,lS=s.topk,cS=s.window_function,dS=s.zeros,_S=s.zeros_like});var VS={};ti(VS,{ArtifactsClient:()=>jo,AudioTranscriptions:()=>Ts,AuthType:()=>Rs,CapabilitiesClient:()=>Ps,ChatClient:()=>bs,CompatibilityLevel:()=>on,ContractModelStatus:()=>tn,ControlClient:()=>xs,DeviceAuth:()=>No,DeviceClass:()=>rn,DeviceContext:()=>es,DevicesClient:()=>Oo,ERROR_CODE_MAP:()=>or,EVENT_REQUIRED_ATTRIBUTES:()=>di,EngineRegistry:()=>Qs,ErrorCode:()=>Zr,ExperimentsClient:()=>en,FederatedAnalyticsClient:()=>qo,FederatedClient:()=>Xo,FinishReason:()=>sn,GradientCache:()=>Zo,InferenceEngine:()=>ys,ModelManager:()=>Es,ModelsClient:()=>Cs,MonitoringClient:()=>So,OTLP_RESOURCE_ATTRIBUTES:()=>Ws,OctomilAudio:()=>vs,OctomilClient:()=>Io,OctomilError:()=>Pe,OctomilText:()=>As,PrincipalType:()=>Bs,ResponsesClient:()=>ks,RoutingClient:()=>Fs,Scope:()=>Ns,SecAggPlus:()=>Yo,SecureAggregation:()=>Js,SettingsClient:()=>Do,StreamingInferenceEngine:()=>Qo,SyncManager:()=>Bo,TELEMETRY_EVENTS:()=>Er,TelemetryReporter:()=>os,TextPredictionsClient:()=>Ks,ToolRunner:()=>Vo,TrainingClient:()=>Lo,WeightExtractor:()=>Xs,addGaussianNoise:()=>Mh,assertModelIntegrity:()=>Am,benchmarkResultOk:()=>jS,clipGradients:()=>gh,closeTelemetry:()=>Fm,computeHash:()=>$s,configure:()=>vm,createModelCache:()=>yo,createTransformersJsLocalResponsesRuntime:()=>mh,dequantize:()=>Th,detectDeviceCapabilities:()=>Fo,embed:()=>ko,generateResponseId:()=>rs,getDeviceContext:()=>zs,getInstallId:()=>Ao,getPublishableKeyEnvironment:()=>wm,getTelemetry:()=>km,initTelemetry:()=>Cm,messagesToResponseInput:()=>Eo,quantize:()=>wh,resetInstallIdCache:()=>Em,shamirReconstruct:()=>bi,shamirSplit:()=>Pi,validatePublishableKey:()=>Co,verifyModelIntegrity:()=>pi});var Rs=(o=>(o.OrgApiKey="org_api_key",o.DeviceToken="device_token",o.ServiceToken="service_token",o.PublishableKey="publishable_key",o))(Rs||{});var Bs=(o=>(o.User="user",o.OrgApiClient="org_api_client",o.Device="device",o.ServiceWorker="service_worker",o))(Bs||{});var Ns=(y=>(y.CatalogRead="catalog:read",y.ModelsRead="models:read",y.ModelsWrite="models:write",y.DevicesRegister="devices:register",y.DevicesHeartbeat="devices:heartbeat",y.ControlRefresh="control:refresh",y.TelemetryWrite="telemetry:write",y.RolloutsRead="rollouts:read",y.RolloutsWrite="rollouts:write",y.BenchmarksWrite="benchmarks:write",y.EvalsWrite="evals:write",y.CloudInference="cloud:inference",y.CloudCredentials="cloud:credentials",y))(Ns||{});var Zr=(F=>(F.InvalidApiKey="invalid_api_key",F.AuthenticationFailed="authentication_failed",F.Forbidden="forbidden",F.DeviceNotRegistered="device_not_registered",F.TokenExpired="token_expired",F.DeviceRevoked="device_revoked",F.NetworkUnavailable="network_unavailable",F.RequestTimeout="request_timeout",F.ServerError="server_error",F.RateLimited="rate_limited",F.InvalidInput="invalid_input",F.UnsupportedModality="unsupported_modality",F.ContextTooLarge="context_too_large",F.ModelNotFound="model_not_found",F.ModelDisabled="model_disabled",F.VersionNotFound="version_not_found",F.DownloadFailed="download_failed",F.ChecksumMismatch="checksum_mismatch",F.InsufficientStorage="insufficient_storage",F.InsufficientMemory="insufficient_memory",F.RuntimeUnavailable="runtime_unavailable",F.AcceleratorUnavailable="accelerator_unavailable",F.ModelLoadFailed="model_load_failed",F.InferenceFailed="inference_failed",F.StreamInterrupted="stream_interrupted",F.PolicyDenied="policy_denied",F.CloudFallbackDisallowed="cloud_fallback_disallowed",F.CloudCredentialsMissing="cloud_credentials_missing",F.CloudCredentialsRevoked="cloud_credentials_revoked",F.CloudProviderAuthFailed="cloud_provider_auth_failed",F.MaxToolRoundsExceeded="max_tool_rounds_exceeded",F.TrainingFailed="training_failed",F.TrainingNotSupported="training_not_supported",F.WeightUploadFailed="weight_upload_failed",F.ControlSyncFailed="control_sync_failed",F.AssignmentNotFound="assignment_not_found",F.Cancelled="cancelled",F.AppBackgrounded="app_backgrounded",F.Unknown="unknown",F))(Zr||{}),ws={invalid_api_key:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},authentication_failed:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"reauthenticate"},forbidden:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_permissions"},device_not_registered:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"register_device"},token_expired:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"reauthenticate"},device_revoked:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"register_device"},network_unavailable:{category:"network",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},request_timeout:{category:"network",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},server_error:{category:"network",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry"},rate_limited:{category:"network",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"retry_after"},invalid_input:{category:"input",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},unsupported_modality:{category:"input",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},context_too_large:{category:"input",retryClass:"never",fallbackEligible:!0,suggestedAction:"reduce_input_or_fallback"},model_not_found:{category:"catalog",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_model_id"},model_disabled:{category:"catalog",retryClass:"never",fallbackEligible:!0,suggestedAction:"use_alternate_model"},version_not_found:{category:"catalog",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_version"},download_failed:{category:"download",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},checksum_mismatch:{category:"download",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"redownload"},insufficient_storage:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"free_storage_or_fallback"},insufficient_memory:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_smaller_model"},runtime_unavailable:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_alternate_runtime"},accelerator_unavailable:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_cpu_or_fallback"},model_load_failed:{category:"runtime",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},inference_failed:{category:"runtime",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},stream_interrupted:{category:"runtime",retryClass:"immediate_safe",fallbackEligible:!0,suggestedAction:"retry"},policy_denied:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_policy"},cloud_fallback_disallowed:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"change_policy_or_fix_local"},cloud_credentials_missing:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},cloud_credentials_revoked:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},cloud_provider_auth_failed:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},max_tool_rounds_exceeded:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"increase_limit_or_simplify"},training_failed:{category:"training",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"retry"},training_not_supported:{category:"training",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},weight_upload_failed:{category:"training",retryClass:"backoff_safe",fallbackEligible:!1,suggestedAction:"retry"},control_sync_failed:{category:"control",retryClass:"backoff_safe",fallbackEligible:!1,suggestedAction:"retry"},assignment_not_found:{category:"control",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_assignment"},cancelled:{category:"lifecycle",retryClass:"never",fallbackEligible:!1,suggestedAction:"none"},app_backgrounded:{category:"lifecycle",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"resume_on_foreground"},unknown:{category:"unknown",retryClass:"never",fallbackEligible:!1,suggestedAction:"report_bug"}};var or={network_unavailable:"NETWORK_UNAVAILABLE",request_timeout:"REQUEST_TIMEOUT",server_error:"SERVER_ERROR",invalid_api_key:"INVALID_API_KEY",authentication_failed:"AUTHENTICATION_FAILED",forbidden:"FORBIDDEN",model_not_found:"MODEL_NOT_FOUND",model_disabled:"MODEL_DISABLED",download_failed:"DOWNLOAD_FAILED",checksum_mismatch:"CHECKSUM_MISMATCH",insufficient_storage:"INSUFFICIENT_STORAGE",runtime_unavailable:"RUNTIME_UNAVAILABLE",model_load_failed:"MODEL_LOAD_FAILED",inference_failed:"INFERENCE_FAILED",insufficient_memory:"INSUFFICIENT_MEMORY",rate_limited:"RATE_LIMITED",invalid_input:"INVALID_INPUT",cancelled:"CANCELLED",unknown:"UNKNOWN",device_not_registered:"DEVICE_NOT_REGISTERED",unsupported_modality:"UNSUPPORTED_MODALITY",context_too_large:"CONTEXT_TOO_LARGE",version_not_found:"VERSION_NOT_FOUND",accelerator_unavailable:"ACCELERATOR_UNAVAILABLE",stream_interrupted:"STREAM_INTERRUPTED",policy_denied:"POLICY_DENIED",cloud_fallback_disallowed:"CLOUD_FALLBACK_DISALLOWED",cloud_credentials_missing:"CLOUD_CREDENTIALS_MISSING",cloud_credentials_revoked:"CLOUD_CREDENTIALS_REVOKED",cloud_provider_auth_failed:"CLOUD_PROVIDER_AUTH_FAILED",max_tool_rounds_exceeded:"MAX_TOOL_ROUNDS_EXCEEDED",control_sync_failed:"CONTROL_SYNC_FAILED",assignment_not_found:"ASSIGNMENT_NOT_FOUND",app_backgrounded:"APP_BACKGROUNDED",training_failed:"TRAINING_FAILED",training_not_supported:"TRAINING_NOT_SUPPORTED",weight_upload_failed:"WEIGHT_UPLOAD_FAILED",token_expired:"TOKEN_EXPIRED",device_revoked:"DEVICE_REVOKED"},js=Object.fromEntries(Object.entries(or).map(([d,t])=>[t,d])),Pe=class d extends Error{constructor(e,r,o){super(r);v(this,"code");v(this,"cause");this.name="OctomilError",this.code=e,this.cause=o}get retryable(){let e=js[this.code];return e!=null&&ws[e].retryClass!=="never"}get category(){let e=js[this.code];return e!=null?ws[e].category:void 0}get retryClass(){let e=js[this.code];return e!=null?ws[e].retryClass:void 0}get fallbackEligible(){let e=js[this.code];return e!=null?ws[e].fallbackEligible:!1}get suggestedAction(){let e=js[this.code];return e!=null?ws[e].suggestedAction:void 0}static fromErrorCode(e,r,o){let a=or[e];return new d(a,r,o)}static fromHttpStatus(e,r){let o=r||`HTTP ${e}`;switch(e){case 400:return new d(or.invalid_input,o);case 401:return new d(or.authentication_failed,o);case 403:return new d(or.forbidden,o);case 404:return new d(or.model_not_found,o);case 429:return new d(or.rate_limited,o);case 500:case 502:case 503:case 504:return new d(or.server_error,o);default:return e>=500?new d(or.server_error,o):new d(or.unknown,o)}}static fromServerResponse(e,r){let o=(typeof r?.message=="string"?r.message:null)??(typeof r?.error=="string"?r.error:null)??`HTTP ${e}`;if(typeof r?.code=="string"&&Object.values(Zr).includes(r.code)){let h=or[r.code];return new d(h,o)}return d.fromHttpStatus(e,o)}};var Ts=class{constructor(t,e){v(this,"serverUrl");v(this,"apiKey");this.serverUrl=t.replace(/\/+$/,""),this.apiKey=e}async create(t){let e=new FormData;if(e.append("file",t.file),t.model&&e.append("model",t.model),t.language&&e.append("language",t.language),t.responseFormat&&e.append("response_format",t.responseFormat),t.timestampGranularities)for(let w of t.timestampGranularities)e.append("timestamp_granularities[]",w);let r=`${this.serverUrl}/v1/audio/transcriptions`,o;try{o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:e})}catch(w){throw new Pe("NETWORK_UNAVAILABLE",`audio.transcriptions.create request failed: ${String(w)}`,w)}if(!o.ok)throw Pe.fromHttpStatus(o.status,`audio.transcriptions.create failed: HTTP ${o.status}`);let a=await o.json(),h=typeof a.text=="string"?a.text:"",u=typeof a.language=="string"?a.language:void 0,l=typeof a.duration_ms=="number"?a.duration_ms:void 0,p=[];return Array.isArray(a.segments)&&(p=a.segments.map(w=>({text:typeof w.text=="string"?w.text:"",startMs:typeof w.start_ms=="number"?w.start_ms:0,endMs:typeof w.end_ms=="number"?w.end_ms:0,confidence:typeof w.confidence=="number"?w.confidence:void 0}))),{text:h,language:u,durationMs:l,segments:p}}};var vs=class{constructor(t,e){v(this,"transcriptions");this.transcriptions=new Ts(t,e)}};var Ps=class{async current(){let e=(typeof navigator<"u"&&navigator.deviceMemory||0)*1024,r;e>=16384?r="flagship":e>=8192?r="high":e>=4096?r="mid":r="low";let o=["wasm"],a=typeof navigator<"u"&&"gpu"in navigator;a&&o.push("webgpu");let h=0;try{if(typeof navigator<"u"&&navigator.storage&&navigator.storage.estimate){let l=await navigator.storage.estimate();h=Math.round((l.quota||0)/(1024*1024))}}catch{}let u=[];return a&&u.push("webgpu"),{deviceClass:r,availableRuntimes:o,memoryMb:e,storageMb:h,platform:"browser",accelerators:u}}};var qh="octomil-models-v1",Yh="octomil-models",bo="blobs",Zh=1,ri=class{async open(){return caches.open(qh)}async get(t){let r=await(await this.open()).match(t);return r?r.arrayBuffer():null}async put(t,e){let r=await this.open(),o=new Response(e,{headers:{"x-octomil-cached-at":new Date().toISOString(),"x-octomil-size":String(e.byteLength)}});await r.put(t,o)}async has(t){return await(await this.open()).match(t)!==void 0}async remove(t){await(await this.open()).delete(t)}async info(t){let r=await(await this.open()).match(t);if(!r)return{cached:!1,sizeBytes:0};let o=r.headers.get("x-octomil-size"),a=r.headers.get("x-octomil-cached-at");return{cached:!0,sizeBytes:o?parseInt(o,10):0,cachedAt:a??void 0}}},xo=class{constructor(){v(this,"dbPromise",null)}openDB(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,e)=>{let r=indexedDB.open(Yh,Zh);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(bo)||o.createObjectStore(bo,{keyPath:"key"})},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error)}),this.dbPromise)}async tx(t){return(await this.openDB()).transaction(bo,t).objectStore(bo)}async get(t){let e=await this.tx("readonly");return new Promise((r,o)=>{let a=e.get(t);a.onsuccess=()=>{let h=a.result;r(h?.data??null)},a.onerror=()=>o(a.error)})}async put(t,e){let r=await this.tx("readwrite"),o={key:t,data:e,sizeBytes:e.byteLength,cachedAt:new Date().toISOString()};return new Promise((a,h)=>{let u=r.put(o);u.onsuccess=()=>a(),u.onerror=()=>h(u.error)})}async has(t){let e=await this.tx("readonly");return new Promise((r,o)=>{let a=e.count(t);a.onsuccess=()=>r(a.result>0),a.onerror=()=>o(a.error)})}async remove(t){let e=await this.tx("readwrite");return new Promise((r,o)=>{let a=e.delete(t);a.onsuccess=()=>r(),a.onerror=()=>o(a.error)})}async info(t){let e=await this.tx("readonly");return new Promise((r,o)=>{let a=e.get(t);a.onsuccess=()=>{let h=a.result;r(h?{cached:!0,sizeBytes:h.sizeBytes,cachedAt:h.cachedAt}:{cached:!1,sizeBytes:0})},a.onerror=()=>o(a.error)})}},Vs=class{async get(t){return null}async put(t,e){}async has(t){return!1}async remove(t){}async info(t){return{cached:!1,sizeBytes:0}}};function yo(d){if(d==="none")return new Vs;if(d==="cache-api")return typeof caches<"u"?new ri:typeof indexedDB<"u"?new xo:new Vs;if(d==="indexeddb")return typeof indexedDB<"u"?new xo:new Vs;throw new Pe("INVALID_INPUT",`Unknown cache strategy: ${d}`)}var _r=class{constructor(t={}){v(this,"serverUrl");v(this,"apiKey");v(this,"orgId");this.serverUrl=(t.serverUrl??"https://api.octomil.com").replace(/\/+$/,""),this.apiKey=t.apiKey,this.orgId=t.orgId}buildUrl(t,e){let r=new URL(t,`${this.serverUrl}/`);for(let[o,a]of Object.entries(e??{}))a==null||a===""||r.searchParams.set(o,String(a));return r.toString()}async requestJson(t,e={},r){let o=await this.request(t,e,r);if(o.status!==204)return await o.json()}async requestVoid(t,e={},r){await this.request(t,e,r)}async request(t,e={},r){let o=new Headers(e.headers);!o.has("Content-Type")&&e.body!==void 0&&o.set("Content-Type","application/json"),this.apiKey&&!o.has("Authorization")&&o.set("Authorization",`Bearer ${this.apiKey}`);let a;try{a=await fetch(this.buildUrl(t,r),{...e,headers:o})}catch(h){throw new Pe("NETWORK_UNAVAILABLE",`Request failed: ${String(h)}`,h)}if(!a.ok){let h=await a.text().catch(()=>"");throw new Pe("NETWORK_UNAVAILABLE",`Request failed: HTTP ${a.status}${h?` ${h}`:""}`)}return a}};var si=class extends _r{constructor(t,e){super({serverUrl:t,apiKey:e})}async requestJson(t,e={},r){return super.requestJson(t,e,r)}},oi=class{constructor(t){this.api=t}async create(t){return this.api.requestJson("/api/v1/chat/threads",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.api.requestJson(`/api/v1/chat/threads/${encodeURIComponent(t)}`,{method:"GET"})}async list(t){return this.api.requestJson("/api/v1/chat/threads",{method:"GET"},t)}},ni=class{constructor(t,e){this.createTurnInternal=t;this.streamTurnInternal=e}async create(t,e){return this.createTurnInternal(t,e)}async*stream(t,e){yield*this.streamTurnInternal(t,e)}},bs=class{constructor(t){v(this,"model");v(this,"serverUrl");v(this,"apiKey");v(this,"getResponses");v(this,"ensureReadyFn");v(this,"api");v(this,"threads");v(this,"turn");this.model=t.model,this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.getResponses=t.getResponses,this.ensureReadyFn=t.ensureReady,this.api=new si(t.serverUrl,t.apiKey),this.threads=new oi(this.api),this.turn=new ni((e,r)=>this.createTurn(e,r),(e,r)=>this.streamTurn(e,r))}async create(t,e={}){this.ensureReadyFn();let r=performance.now(),{instructions:o,input:a}=Eo(t),h=await this.getResponses().create({model:this.model,input:a,instructions:o,maxOutputTokens:e.maxTokens,temperature:e.temperature,topP:e.topP});return{message:{role:"assistant",content:h.output.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("")},latencyMs:performance.now()-r,usage:h.usage?{promptTokens:h.usage.promptTokens,completionTokens:h.usage.completionTokens,totalTokens:h.usage.totalTokens}:void 0}}async*stream(t,e={}){this.ensureReadyFn();let{instructions:r,input:o}=Eo(t),a=0,h=this.getResponses().stream({model:this.model,input:o,instructions:r,maxOutputTokens:e.maxTokens,temperature:e.temperature,topP:e.topP});for await(let u of h)u.type==="text_delta"?yield{index:a++,content:u.delta,done:!1,role:"assistant"}:u.type==="done"&&(yield{index:a,content:"",done:!0,role:"assistant"})}requireServerUrl(t){if(!this.serverUrl)throw new Pe(or.invalid_input,`${t} requires serverUrl to be configured.`)}async createTurn(t,e){return this.ensureReadyFn(),this.requireServerUrl("chat.turn.create()"),this.api.requestJson(`/api/v1/chat/threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify({...e,threadId:t})})}async*streamTurn(t,e){this.ensureReadyFn(),this.requireServerUrl("chat.turn.stream()");let r=await fetch(`${this.serverUrl}/api/v1/chat/threads/${encodeURIComponent(t)}/turns`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{Authorization:`Bearer ${this.apiKey}`}:{}},body:JSON.stringify({...e,threadId:t,stream:!0})});if(!r.ok||!r.body)throw new Pe(or.network_unavailable,`chat.turn.stream() failed: HTTP ${r.status}`);let o=r.body.getReader(),a=new TextDecoder,h="",u=0;for(;;){let{done:l,value:p}=await o.read();h+=a.decode(p??new Uint8Array,{stream:!l});let w=h.indexOf(`
25
-
26
- `);for(;w>=0;){let f=h.slice(0,w);h=h.slice(w+2);let i=f.split(`
27
- `).filter(y=>y.startsWith("data:")).map(y=>y.slice(5).trim()).join(`
28
- `);if(i&&i!=="[DONE]"){let y=JSON.parse(i);y.type==="text_delta"&&(y.delta||y.content)&&(yield{index:u++,content:y.delta??y.content??"",done:!1,role:"assistant"}),y.type==="done"&&(yield{index:u,content:"",done:!0,role:"assistant"})}w=h.indexOf(`
29
-
30
- `)}if(l)break}}};function Eo(d){let t=[],e=[];for(let r of d)if(r.role==="system")t.push(r.content);else{let o=r.role==="assistant"?"[assistant] ":"";e.push(o+r.content)}return{instructions:t.length>0?t.join(`
31
- `):void 0,input:e.join(`
32
- `)}}var Us=class Us{constructor(t){v(this,"installationId");v(this,"orgId");v(this,"appId");v(this,"_registrationState","pending");v(this,"_tokenState",{type:"none"});v(this,"_serverDeviceId",null);this.installationId=t.installationId,this.orgId=t.orgId??null,this.appId=t.appId??null}get registrationState(){return this._registrationState}get tokenState(){return this._tokenState}get serverDeviceId(){return this._serverDeviceId}get isRegistered(){return this._registrationState==="registered"}authHeaders(){return this._tokenState.type==="valid"&&this._tokenState.expiresAt>new Date?{Authorization:`Bearer ${this._tokenState.accessToken}`}:null}telemetryResource(){let t={"device.id":this.installationId,platform:"browser"};return this.orgId&&(t["org.id"]=this.orgId),this.appId&&(t["app.id"]=this.appId),t}_updateRegistered(t,e,r){this._serverDeviceId=t,this._tokenState={type:"valid",accessToken:e,expiresAt:r},this._registrationState="registered"}_updateToken(t,e){this._tokenState={type:"valid",accessToken:t,expiresAt:e}}_markFailed(){this._registrationState="failed"}_markTokenExpired(){this._tokenState={type:"expired"}}static getOrCreateInstallationId(){try{let t=localStorage.getItem(Us.STORAGE_KEY);if(t)return t;let e=crypto.randomUUID();return localStorage.setItem(Us.STORAGE_KEY,e),e}catch{return crypto.randomUUID()}}};v(Us,"STORAGE_KEY","octomil_installation_id");var es=Us;var ef=["oct_pub_test_","oct_pub_live_"];function Co(d){if(!ef.some(t=>d.startsWith(t)))throw new Error("Publishable key must start with 'oct_pub_test_' or 'oct_pub_live_'")}function wm(d){return d.startsWith("oct_pub_test_")?"test":d.startsWith("oct_pub_live_")?"live":null}var Tm=null;function zs(){return Tm}async function vm(d={}){d.auth?.type==="publishable_key"&&Co(d.auth.key);let t=es.getOrCreateInstallationId(),e=d.auth?.type==="anonymous"?d.auth.appId:d.auth?.appId,r=d.auth?.type==="anonymous"?null:d.auth?.orgId??null,o=new es({installationId:t,orgId:r,appId:e??null});return Tm=o,d.auth!=null&&d.monitoring?.enabled===!0&&Pm(o,d).catch(()=>{}),o}async function Pm(d,t,e=0){let a=t.auth?.type==="anonymous"?null:t.auth?.orgId??null;try{let h=t.baseUrl||"https://api.octomil.com",u={"Content-Type":"application/json"};t.auth?.type==="publishable_key"?u.Authorization=`Bearer ${t.auth.key}`:t.auth?.type==="bootstrap_token"&&(u.Authorization=`Bearer ${t.auth.token}`),d.appId&&(u["X-App-Id"]=d.appId);let l=new URL(`${h.replace(/\/+$/,"")}/api/v1/devices/register`);a&&l.searchParams.set("org_id",a);let p=await fetch(l.toString(),{method:"POST",headers:u,body:JSON.stringify({device_identifier:d.installationId,installation_id:d.installationId,platform:"browser",app_id:d.appId})});if(!p.ok){if(p.status===403){console.warn("[Octomil] Registration failed: invalid credentials"),d._markFailed();return}throw new Error(`Registration failed: ${p.status}`)}let w=await p.json(),f=w.device_id??w.id;if(!f||!w.access_token||!w.expires_at)throw new Error("Registration response missing device token fields");d._updateRegistered(f,w.access_token,new Date(w.expires_at)),t.monitoring?.enabled&&tf(d,t)}catch(h){if(console.warn(`[Octomil] Registration attempt ${e+1} failed:`,h),e<10){let u=Math.min(1e3*Math.pow(2,e),3e5),l=u*.1*Math.random(),p=u+l;return await new Promise(w=>setTimeout(w,p)),Pm(d,t,e+1)}d._markFailed()}}function tf(d,t){let e=t.monitoring?.heartbeatIntervalMs??3e5;setInterval(async()=>{let r=d.authHeaders();if(r)try{let o=t.baseUrl||"https://api.octomil.com";if(!d.serverDeviceId)return;await fetch(`${o.replace(/\/+$/,"")}/api/v1/devices/${d.serverDeviceId}/heartbeat`,{method:"PUT",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify({device_identifier:d.installationId})})}catch{}},e)}var ai={octomilResponse:"octomil.response",octomilModelLoad:"octomil.model.load",octomilControlRefresh:"octomil.control.refresh",octomilControlHeartbeat:"octomil.control.heartbeat",octomilToolExecute:"octomil.tool.execute",octomilFallbackCloud:"octomil.fallback.cloud",octomilRolloutSync:"octomil.rollout.sync",octomilArtifactDownload:"octomil.artifact.download",octomilArtifactActivation:"octomil.artifact.activation",octomilFederationRound:"octomil.federation.round",octomilTrainingJob:"octomil.training.job",octomilDeviceSync:"octomil.device.sync",octomilTelemetryUpload:"octomil.telemetry.upload"},PD=Object.values(ai);var bm={modelId:"model.id",modelVersion:"model.version",runtimeExecutor:"runtime.executor",requestMode:"request.mode",locality:"locality",streaming:"streaming",routePolicy:"route.policy",routeDecision:"route.decision",deviceClass:"device.class",fallbackReason:"fallback.reason",errorType:"error.type",toolCallTier:"tool.call_tier",modelSourceFormat:"model.source_format",modelSizeBytes:"model.size_bytes",toolName:"tool.name",toolRound:"tool.round",fallbackProvider:"fallback.provider",assignmentCount:"assignment_count",heartbeatSequence:"heartbeat.sequence",rolloutId:"rollout.id",modelsSynced:"models_synced"};var xs=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"orgId");v(this,"serverDeviceId",null);v(this,"heartbeatTimer",null);v(this,"heartbeatSequence",0);v(this,"deviceContext");v(this,"telemetry");this.serverUrl=(t.serverUrl||"https://api.octomil.com").replace(/\/+$/,""),this.apiKey=t.apiKey,this.orgId=t.orgId,this.deviceContext=t.deviceContext??null,this.serverDeviceId=this.deviceContext?.serverDeviceId??null,this.telemetry=t.telemetry??null}async refresh(){if(!this.serverDeviceId)return{updated:!1,configVersion:"",assignmentsChanged:!1,fetchedAt:new Date().toISOString()};let t={};Object.assign(t,this.resolveAuthHeaders());let e=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/assignments`,{headers:t});if(!e.ok)throw new Pe("NETWORK_UNAVAILABLE",`Refresh assignments failed: ${e.status}`);let r=await e.json();return{updated:r.updated??!0,configVersion:r.config_version??"",assignmentsChanged:r.assignments_changed??!1,fetchedAt:new Date().toISOString()}}async register(t){let e=t||this.deviceContext?.installationId||await this.generateDeviceId(),r={device_identifier:e,installation_id:this.deviceContext?.installationId??e,app_id:this.deviceContext?.appId??void 0,platform:"browser",os_version:typeof navigator<"u"?navigator.userAgent:"unknown",sdk_version:"1.0.0",locale:typeof navigator<"u"?navigator.language:void 0,timezone:typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0,device_info:this.collectDeviceInfo()},o={"Content-Type":"application/json"};Object.assign(o,this.resolveAuthHeaders()),this.deviceContext?.appId&&(o["X-App-Id"]=this.deviceContext.appId);let a=new URL(`${this.serverUrl}/api/v1/devices/register`);this.orgId&&a.searchParams.set("org_id",this.orgId);let h;try{h=await fetch(a.toString(),{method:"POST",headers:o,body:JSON.stringify(r)})}catch(l){throw new Pe("NETWORK_UNAVAILABLE",`Registration request failed: ${String(l)}`,l)}if(!h.ok)throw new Pe("NETWORK_UNAVAILABLE",`Registration failed: ${h.status}`);let u=await h.json();return this.serverDeviceId=u.device_id??u.id??null,this.serverDeviceId&&this.deviceContext&&u.access_token&&u.expires_at&&this.deviceContext._updateRegistered(this.serverDeviceId,u.access_token,new Date(u.expires_at)),{id:this.serverDeviceId??"",deviceIdentifier:e,orgId:this.orgId||"",status:u.status||"active"}}async heartbeat(){if(!this.serverDeviceId)throw new Pe("INVALID_INPUT","Device not registered");let t=this.heartbeatSequence++;this.telemetry?.track({name:ai.octomilControlHeartbeat,timestamp:new Date().toISOString(),attributes:{[bm.heartbeatSequence]:t}});let e={sdk_version:"1.0.0",platform:"browser",os_version:typeof navigator<"u"?navigator.userAgent:"unknown"},r={"Content-Type":"application/json"};Object.assign(r,this.resolveAuthHeaders());let o;try{o=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/heartbeat`,{method:"PUT",headers:r,body:JSON.stringify(e)})}catch(h){throw new Pe("NETWORK_UNAVAILABLE",`Heartbeat request failed: ${String(h)}`,h)}if(!o.ok)throw new Pe("NETWORK_UNAVAILABLE",`Heartbeat failed: ${o.status}`);let a=await o.json();return{status:a.status||"ok",serverTime:a.server_time}}async reportObservedState(t=[]){if(!this.serverDeviceId)throw new Pe("INVALID_INPUT","Device not registered");let e={schemaVersion:"1.4.0",deviceId:this.serverDeviceId,reportedAt:new Date().toISOString(),models:t,active_bindings:t.filter(a=>a.status==="active").map(a=>({binding_key:a.bindingKey??a.useCase??a.modelId,base_model_id:a.modelId,base_version:a.version??"",use_case:a.useCase,deployment_id:a.deploymentId,deployment_key:a.deploymentKey,model_name:a.modelName,model_ref:a.modelRef})),sdkVersion:"1.0.0",osVersion:typeof navigator<"u"?navigator.userAgent:"unknown"},r={"Content-Type":"application/json"};Object.assign(r,this.resolveAuthHeaders());let o;try{o=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/observed-state`,{method:"POST",headers:r,body:JSON.stringify(e)})}catch(a){throw new Pe("NETWORK_UNAVAILABLE",`Report observed state failed: ${String(a)}`,a)}if(!o.ok)throw new Pe("NETWORK_UNAVAILABLE",`Report observed state failed: ${o.status}`)}async fetchDesiredState(){if(!this.serverDeviceId)throw new Pe("INVALID_INPUT","Device not registered");let t={};Object.assign(t,this.resolveAuthHeaders());let e;try{e=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/desired-state`,{headers:t})}catch(r){throw new Pe("NETWORK_UNAVAILABLE",`Fetch desired state failed: ${String(r)}`,r)}if(!e.ok)throw new Pe("NETWORK_UNAVAILABLE",`Fetch desired state failed: ${e.status}`);return await e.json()}async sync(t={}){if(!this.serverDeviceId)throw new Pe("INVALID_INPUT","Device not registered");let e={"Content-Type":"application/json"};Object.assign(e,this.resolveAuthHeaders());let r;try{r=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/sync`,{method:"POST",headers:e,body:JSON.stringify({schemaVersion:t.schemaVersion??"1.12.0",deviceId:this.serverDeviceId,requestedAt:t.requestedAt??new Date().toISOString(),knownStateVersion:t.knownStateVersion,sdkVersion:t.sdkVersion,platform:t.platform??"browser",appId:t.appId,appVersion:t.appVersion,modelInventory:t.modelInventory??[],activeVersions:t.activeVersions??[],availableStorageBytes:t.availableStorageBytes})})}catch(o){throw new Pe("NETWORK_UNAVAILABLE",`Device sync failed: ${String(o)}`,o)}if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Device sync failed: ${r.status}`);return await r.json()}startHeartbeat(t=3e5){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.heartbeat().catch(()=>{})},t)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}get registeredDeviceId(){return this.serverDeviceId}async generateDeviceId(){let t=[typeof navigator<"u"?navigator.userAgent:"unknown",typeof screen<"u"?screen.width:0,typeof screen<"u"?screen.height:0,typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC"].join("|"),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("")}collectDeviceInfo(){return{platform:"browser",user_agent:typeof navigator<"u"?navigator.userAgent:"unknown",screen_width:typeof screen<"u"?screen.width:0,screen_height:typeof screen<"u"?screen.height:0,device_memory_gb:typeof navigator<"u"&&navigator.deviceMemory||0,language:typeof navigator<"u"?navigator.language:"unknown"}}resolveAuthHeaders(){return this.deviceContext?.authHeaders()??this.resolveApiKeyHeaders()}resolveApiKeyHeaders(){return this.apiKey?{Authorization:`Bearer ${this.apiKey}`}:{}}};async function ko(d,t,e,r,o){if(!d)throw new Pe("INVALID_INPUT","serverUrl is required for embed()");if(!t)throw new Pe("INVALID_INPUT","apiKey is required for embed()");let a=`${d.replace(/\/+$/,"")}/api/v1/embeddings`,h;try{h=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model_id:e,input:r}),signal:o})}catch(l){throw new Pe("NETWORK_UNAVAILABLE",`embed() request failed: ${String(l)}`,l)}if(!h.ok)throw new Pe("INFERENCE_FAILED",`embed() failed: HTTP ${h.status}`);let u=await h.json();return{embeddings:u.data.map(l=>l.embedding),model:u.model,usage:{promptTokens:u.usage.prompt_tokens,totalTokens:u.usage.total_tokens}}}var ys=class{constructor(){v(this,"session",null);v(this,"ortModule",null);v(this,"resolvedBackend",null)}async createSession(t,e){let r=await this.loadOrt(),o=await this.resolveProvider(r,e);this.resolvedBackend=o==="webgpu"?"webgpu":"wasm";let a={executionProviders:[o],graphOptimizationLevel:"all"};try{this.session=await r.InferenceSession.create(t,a)}catch(h){if(o==="webgpu")try{this.session=await r.InferenceSession.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.resolvedBackend="wasm"}catch(u){throw new Pe("MODEL_LOAD_FAILED","Failed to create ONNX session with both WebGPU and WASM backends.",u)}else throw new Pe("MODEL_LOAD_FAILED",`Failed to create ONNX session: ${String(h)}`,h)}}async run(t){this.ensureSession();let e=this.ortModule,r=this.session,o={};for(let[w,f]of Object.entries(t))o[w]=new e.Tensor(rf(f.data),f.data,f.dims);let a=performance.now(),h;try{h=await r.run(o)}catch(w){throw new Pe("INFERENCE_FAILED",`Inference run failed: ${String(w)}`,w)}let u=performance.now()-a,l=this.convertOutputs(h),p=this.extractConvenience(l);return{tensors:l,latencyMs:u,...p}}get inputNames(){return this.ensureSession(),this.session.inputNames}get outputNames(){return this.ensureSession(),this.session.outputNames}get activeBackend(){return this.resolvedBackend}dispose(){this.session&&(this.session.release(),this.session=null)}async isAvailable(){try{return await this.loadOrt(),!0}catch{return!1}}async loadOrt(){if(this.ortModule)return this.ortModule;try{return this.ortModule=await Promise.resolve().then(()=>Mm(ii(),1)),this.ortModule}catch(t){throw new Pe("RUNTIME_UNAVAILABLE","Failed to import onnxruntime-web. Make sure the package is installed: npm i onnxruntime-web",t)}}async resolveProvider(t,e){if(e==="wasm")return"wasm";if(e==="webgpu"||e===void 0){if(await this.detectWebGPU())return"webgpu";if(e==="webgpu")throw new Pe("RUNTIME_UNAVAILABLE","WebGPU was explicitly requested but is not available in this browser.")}return"wasm"}async detectWebGPU(){if(typeof navigator>"u")return!1;try{let t=navigator.gpu;return t?await t.requestAdapter()!==null:!1}catch{return!1}}ensureSession(){if(!this.session)throw new Pe("CANCELLED","No active session. Call load() before running inference.")}convertOutputs(t){let e={};for(let r of Object.keys(t)){let o=t[r];e[r]={data:o.data,dims:Array.from(o.dims)}}return e}extractConvenience(t){let e=Object.keys(t);if(e.length===0)return{};let o=t[e[0]].data;if(o.length===0)return{};if(o.length===1)return{label:String(Number(o[0])),score:1};if(!(o instanceof Float32Array))return{};let a=Array.from(o),h=0,u=-1/0;for(let l=0;l<a.length;l++)a[l]>u&&(u=a[l],h=l);return{label:String(h),score:u,scores:a}}};function rf(d){return d instanceof Float32Array?"float32":d instanceof Int32Array?"int32":d instanceof BigInt64Array?"int64":d instanceof Uint8Array?"uint8":"float32"}var ts=3,li=1e3,Es=class{constructor(t,e){v(this,"modelId");v(this,"serverUrl");v(this,"apiKey");v(this,"onProgress");v(this,"cache");this.modelId=t.model,this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.onProgress=t.onProgress,this.cache=e}async load(){let t=await this.resolveModelUrl(),e=await this.cache.get(t);if(e)return e;let r=await this.download(t);return this.validate(r),await this.cache.put(t,r),r}async isCached(){let t=await this.resolveModelUrl();return this.cache.has(t)}async clearCache(){let t=await this.resolveModelUrl();await this.cache.remove(t)}async getCacheInfo(){let t=await this.resolveModelUrl();return this.cache.info(t)}async resolveModelUrl(){if(this.modelId.startsWith("http://")||this.modelId.startsWith("https://"))return this.modelId;if(!this.serverUrl)throw new Pe("MODEL_NOT_FOUND",`Cannot resolve model "${this.modelId}": no serverUrl configured.`);return this.fetchResolverUrl(this.modelId)}async fetchResolverUrl(t){let e=`${this.serverUrl}/api/v1/registry/resolve/${encodeURIComponent(t)}`,r={Accept:"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`);let o;try{o=await fetch(e,{headers:r})}catch(u){throw new Pe("NETWORK_UNAVAILABLE",`Failed to reach model resolver at ${e}`,u)}if(!o.ok)throw o.status===404?new Pe("MODEL_NOT_FOUND",`Model "${t}" not found in registry.`):new Pe("NETWORK_UNAVAILABLE",`Model resolver returned HTTP ${o.status}: ${o.statusText}`);let a=await o.json(),h=a.download_url??a.url;if(!h)throw new Pe("MODEL_LOAD_FAILED",`Model resolver response for "${t}" did not include a download URL`);return h}buildHeaders(t={}){let e={"Accept-Encoding":"gzip, deflate, br",...t};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async download(t){let e=[],r=0,o=0,a=0;for(;a<=ts;){let l=this.buildHeaders(r>0?{Range:`bytes=${r}-`}:{}),p;try{p=await fetch(t,{headers:l})}catch(i){if(a++,a>ts)throw new Pe("NETWORK_UNAVAILABLE",`Failed to download model from ${t} after ${ts} retries`,i);await this.delay(li*a);continue}if(p.status===416){if(e.length=0,r=0,a++,a>ts)throw new Pe("MODEL_LOAD_FAILED",`Model download failed: range request rejected after ${ts} retries`);await this.delay(li*a);continue}if(!p.ok&&p.status!==206)throw new Pe("MODEL_LOAD_FAILED",`Model download failed: HTTP ${p.status} ${p.statusText}`);if(o===0){let i=p.headers.get("Content-Range");if(i){let y=i.match(/\/(\d+)$/);y&&(o=parseInt(y[1],10))}else o=parseInt(p.headers.get("Content-Length")??"0",10)}if(!p.body)return await p.arrayBuffer();let w=p.body.getReader(),f=!1;try{for(;;){let{done:i,value:y}=await w.read();if(i)break;e.push(y),r+=y.byteLength,this.onProgress?.({loaded:r,total:o,percent:o>0?r/o*100:NaN})}}catch(i){if(f=!0,a++,a>ts)throw new Pe("NETWORK_UNAVAILABLE",`Model download interrupted after ${ts} retries`,i);await this.delay(li*a)}finally{w.releaseLock()}if(!f)break}let h=new Uint8Array(r),u=0;for(let l of e)h.set(l,u),u+=l.byteLength;return h.buffer}delay(t){return new Promise(e=>setTimeout(e,t))}validate(t){if(t.byteLength===0)throw new Pe("MODEL_LOAD_FAILED","Downloaded model is empty (0 bytes).");if(new Uint8Array(t,0,Math.min(4,t.byteLength))[0]!==8)throw new Pe("MODEL_LOAD_FAILED","Downloaded file does not appear to be a valid ONNX model.")}};var Cs=class{constructor(t,e,r){this.modelId=t;this.manager=e;this.onLoaded=r;v(this,"downloading",new Set);v(this,"errors",new Map)}async status(t){let e=t??this.modelId;return this.downloading.has(e)?"downloading":this.errors.has(e)?"error":await this.manager.isCached()?"ready":"not_cached"}async load(t){let e=t??this.modelId;this.downloading.add(e),this.errors.delete(e);try{await this.manager.load(),this.downloading.delete(e),this.onLoaded()}catch(r){throw this.downloading.delete(e),this.errors.set(e,String(r)),r}}async unload(t){await this.manager.clearCache()}async list(){let t=await this.manager.getCacheInfo();return t.cached?[{modelRef:this.modelId,cachedAt:t.cachedAt,sizeBytes:t.sizeBytes>0?t.sizeBytes:void 0}]:[]}async clearCache(){await this.manager.clearCache(),this.errors.clear()}getError(t){let e=t??this.modelId;return this.errors.get(e)}};var ks=class{constructor(t={}){v(this,"serverUrl");v(this,"apiKey");v(this,"telemetry");v(this,"deviceContext");v(this,"localRuntime");v(this,"responseCache",new Map);v(this,"MAX_CACHE",100);this.serverUrl=t.serverUrl||"https://api.octomil.com",this.apiKey=t.apiKey,this.telemetry=t.telemetry??null,this.deviceContext=t.deviceContext??null,this.localRuntime=t.localRuntime??null}async create(t){let e=this.resolveLocalRuntime(t.model);if(e)return this.createLocal(t,e);let r=this.buildRequestBody(t,!1),o=`${this.serverUrl}/v1/chat/completions`,a={"Content-Type":"application/json"},h=this.deviceContext?.authHeaders();h?Object.assign(a,h):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),this.telemetry?.reportInferenceStarted(t.model,{target:"cloud",method:"responses.create",locality:"cloud"});let u=performance.now(),l;try{l=await fetch(o,{method:"POST",headers:a,body:JSON.stringify(r)})}catch(i){throw this.telemetry?.reportInferenceFailed(t.model,"network_error",String(i)),new Pe("NETWORK_UNAVAILABLE",`Request failed: ${String(i)}`,i)}if(!l.ok)throw this.telemetry?.reportInferenceFailed(t.model,"http_error",`HTTP ${l.status}`),new Pe("NETWORK_UNAVAILABLE",`HTTP ${l.status}`);let p=await l.json(),w=this.parseResponse(t.model,p),f=performance.now()-u;return this.telemetry?.reportInferenceCompleted(t.model,f,{target:"cloud",method:"responses.create",locality:"cloud"}),this.cacheResponse(w),w}async*stream(t){let e=this.resolveLocalRuntime(t.model);if(e){yield*this.streamLocal(t,e);return}let r=this.buildRequestBody(t,!0),o=`${this.serverUrl}/v1/chat/completions`,a={"Content-Type":"application/json"},h=this.deviceContext?.authHeaders();h?Object.assign(a,h):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),this.telemetry?.reportInferenceStarted(t.model,{target:"cloud",method:"responses.stream",locality:"cloud"});let u=performance.now(),l;try{l=await fetch(o,{method:"POST",headers:a,body:JSON.stringify(r)})}catch(x){throw this.telemetry?.reportInferenceFailed(t.model,"network_error",String(x)),new Pe("NETWORK_UNAVAILABLE",`Request failed: ${String(x)}`,x)}if(!l.ok)throw this.telemetry?.reportInferenceFailed(t.model,"http_error",`HTTP ${l.status}`),new Pe("NETWORK_UNAVAILABLE",`HTTP ${l.status}`);if(!l.body)throw new Pe("NETWORK_UNAVAILABLE","No response body");let p=l.body.getReader(),w=new TextDecoder,f="",i=0,y=[],E=new Map,S;try{for(;;){let{done:x,value:P}=await p.read();if(x)break;f+=w.decode(P,{stream:!0});let D=f.split(`
33
- `);f=D.pop()||"";for(let _ of D){let M=_.trim();if(!M.startsWith("data: "))continue;let I=M.slice(6);if(I!=="[DONE]")try{let O=JSON.parse(I),G=O.choices?.[0];if(!G)continue;let U=G.delta;if(U?.content&&(y.push(U.content),this.telemetry?.reportChunkProduced(t.model,i),i++,yield{type:"text_delta",delta:U.content}),U?.tool_calls)for(let B of U.tool_calls){let Q=E.get(B.index)||{arguments:""};B.id&&(Q.id=B.id),B.function?.name&&(Q.name=B.function.name),B.function?.arguments&&(Q.arguments+=B.function.arguments),E.set(B.index,Q),this.telemetry?.reportChunkProduced(t.model,i),i++,yield{type:"tool_call_delta",index:B.index,id:B.id,name:B.function?.name,argumentsDelta:B.function?.arguments}}O.usage&&(S={promptTokens:O.usage.prompt_tokens,completionTokens:O.usage.completion_tokens,totalTokens:O.usage.total_tokens})}catch{}}}}finally{p.releaseLock()}let z=[],k=y.join("");k&&z.push({type:"text",text:k});for(let[,x]of[...E.entries()].sort((P,D)=>P[0]-D[0]))z.push({type:"tool_call",toolCall:{id:x.id||rs(),name:x.name||"",arguments:x.arguments}});let A={id:rs(),model:t.model,output:z,finishReason:E.size>0?"tool_calls":"stop",usage:S},N=performance.now()-u;this.telemetry?.reportInferenceCompleted(t.model,N,{target:"cloud",method:"responses.stream",locality:"cloud"}),this.cacheResponse(A),yield{type:"done",response:A}}resolveLocalRuntime(t){return this.localRuntime?typeof this.localRuntime=="function"?this.localRuntime(t)??null:this.localRuntime:null}cacheResponse(t){if(this.responseCache.size>=this.MAX_CACHE){let e=this.responseCache.keys().next().value;e&&this.responseCache.delete(e)}this.responseCache.set(t.id,t)}async createLocal(t,e){let r=this.buildEffectiveRequest(t);this.telemetry?.reportInferenceStarted(t.model,{target:"device",method:"responses.create",locality:"local"});let o=performance.now();try{let a=await e.create(r);return this.cacheResponse(a),this.telemetry?.reportInferenceCompleted(t.model,performance.now()-o,{target:"device",method:"responses.create",locality:"local"}),a}catch(a){throw this.telemetry?.reportInferenceFailed(t.model,"local_runtime_error",String(a)),a}}async*streamLocal(t,e){let r=this.buildEffectiveRequest(t);this.telemetry?.reportInferenceStarted(t.model,{target:"device",method:"responses.stream",locality:"local"});let o=performance.now(),a=0;try{for await(let h of e.stream(r))h.type!=="done"?(this.telemetry?.reportChunkProduced(t.model,a),a++):(this.cacheResponse(h.response),this.telemetry?.reportInferenceCompleted(t.model,performance.now()-o,{target:"device",method:"responses.stream",locality:"local"})),yield h}catch(h){throw this.telemetry?.reportInferenceFailed(t.model,"local_runtime_error",String(h)),h}}buildEffectiveRequest(t){let e=this.normalizeInput(t.input);if(t.previousResponseId){let r=this.responseCache.get(t.previousResponseId);r&&e.unshift({role:"assistant",content:r.output})}return t.instructions&&e.unshift({role:"system",content:t.instructions}),{...t,input:e,instructions:void 0,previousResponseId:void 0}}buildRequestBody(t,e){let r=this.buildMessages(this.buildEffectiveRequest(t));return{model:t.model,messages:r,max_tokens:t.maxOutputTokens,temperature:t.temperature,top_p:t.topP,stop:t.stop,stream:e,tools:t.tools?.map(o=>({type:"function",function:o.function}))}}buildMessages(t){return this.normalizeInput(t.input).map(r=>this.inputItemToMessage(r))}normalizeInput(t){return typeof t=="string"?[{role:"user",content:t}]:this.isResponseInputItems(t)?t.map(e=>({...e})):[{role:"user",content:t}]}isResponseInputItems(t){return t.every(e=>"role"in e)}inputItemToMessage(t){switch(t.role){case"system":return{role:"system",content:typeof t.content=="string"?t.content:""};case"user":return{role:"user",content:this.inputContentToMessageContent(t.content)};case"assistant":return this.assistantInputToMessage(t);case"tool":return{role:"tool",content:typeof t.content=="string"?t.content:"",tool_call_id:t.toolCallId};default:return{role:t.role,content:typeof t.content=="string"?t.content:""}}}assistantInputToMessage(t){if(typeof t.content=="string"||t.content==null)return{role:"assistant",content:t.content??""};if(this.isResponseOutputItems(t.content)){let e=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>o.text),r=t.content.filter(o=>o.type==="tool_call"&&!!o.toolCall).map(o=>({id:o.toolCall.id,type:"function",function:{name:o.toolCall.name,arguments:o.toolCall.arguments}}));return{role:"assistant",content:e.join(""),...r.length>0?{tool_calls:r}:{}}}return{role:"assistant",content:this.contentBlocksToParts(t.content)}}isResponseOutputItems(t){return t.every(e=>e.type==="text"||e.type==="tool_call")}inputContentToMessageContent(t){return typeof t=="string"||t==null?t??"":this.isResponseOutputItems(t)?t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):this.contentBlocksToParts(t)}contentBlocksToParts(t){return t.map(e=>this.contentBlockToPart(e))}contentBlockToPart(t){switch(t.type){case"text":return{type:"text",text:t.text??""};case"image":return t.imageUrl?{type:"image_url",image_url:{url:t.imageUrl}}:t.data?{type:"image_url",image_url:{url:`data:${t.mediaType??"image/png"};base64,${t.data}`}}:{type:"text",text:t.text??"[image]"};case"audio":if(t.data){let r=(t.mediaType??"audio/wav").split("/")[1]??"wav";return{type:"input_audio",input_audio:{data:t.data,format:r}}}return{type:"text",text:t.text??"[audio]"};case"video":return t.data?{type:"image_url",image_url:{url:`data:${t.mediaType??"video/mp4"};base64,${t.data}`}}:{type:"text",text:t.text??"[video]"};case"file":{let e=t.mediaType??"";if(t.data&&e.startsWith("image/"))return{type:"image_url",image_url:{url:`data:${e};base64,${t.data}`}};if(t.data&&e.startsWith("audio/")){let r=e.split("/")[1]??"wav";return{type:"input_audio",input_audio:{data:t.data,format:r}}}return t.data&&e.startsWith("video/")?{type:"image_url",image_url:{url:`data:${e};base64,${t.data}`}}:{type:"text",text:t.text??`[file: ${e||"unknown"}]`}}default:return{type:"text",text:t.text??""}}}parseResponse(t,e){let o=e.choices?.[0],a=[],h=o?.message;if(h?.content&&a.push({type:"text",text:h.content}),h?.tool_calls)for(let l of h.tool_calls){let p=l.function;a.push({type:"tool_call",toolCall:{id:l.id,name:p.name,arguments:p.arguments}})}let u=e.usage;return{id:e.id||rs(),model:t,output:a,finishReason:o?.finish_reason||"stop",usage:u?{promptTokens:u.prompt_tokens,completionTokens:u.completion_tokens,totalTokens:u.total_tokens}:void 0}}};function rs(){return`resp_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}var sf=3e5,ci="octomil_routing_cache",Fs=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"cacheTtlMs");v(this,"prefer");v(this,"cache",new Map);v(this,"lastRouteWasOffline",!1);this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.apiKey=t.apiKey,this.cacheTtlMs=t.cacheTtlMs??sf,this.prefer=t.prefer??"fastest"}async route(t,e,r,o){this.lastRouteWasOffline=!1;let a=this.cache.get(t);if(a&&a.expiresAt>Date.now())return a.decision;let h={model_id:t,model_params:e,model_size_mb:r,device_capabilities:o,prefer:this.prefer},u;try{u=await fetch(`${this.serverUrl}/api/v1/route`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(h)})}catch{return this.offlineFallback(t)}if(!u.ok)return this.offlineFallback(t);let l=await u.json();return this.cache.set(t,{decision:l,expiresAt:Date.now()+this.cacheTtlMs}),this.persistToStorage(t,l),l}async cloudInfer(t,e,r={}){let o={model_id:t,input_data:e,parameters:r},a;try{a=await fetch(`${this.serverUrl}/api/v1/inference`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(o)})}catch(h){throw new Pe("NETWORK_UNAVAILABLE",`Cloud inference request failed: ${String(h)}`,h)}if(!a.ok)throw new Pe("INFERENCE_FAILED",`Cloud inference failed: HTTP ${a.status}`);return await a.json()}clearCache(){this.cache.clear();try{localStorage.removeItem(ci)}catch{}}invalidate(t){this.cache.delete(t);let e=this.loadPersistentCache();delete e[t],this.savePersistentCache(e)}offlineFallback(t){this.lastRouteWasOffline=!0;let r=this.loadPersistentCache()[t];return r?{...r,cached:!0,offline:!1}:{id:`offline-${t}`,target:"device",format:"onnx",engine:"ort-wasm",fallback_target:null,cached:!1,offline:!0}}persistToStorage(t,e){let r=this.loadPersistentCache();r[t]=e,this.savePersistentCache(r)}loadPersistentCache(){try{let t=localStorage.getItem(ci);return t?JSON.parse(t):{}}catch{return{}}}savePersistentCache(t){try{localStorage.setItem(ci,JSON.stringify(t))}catch{}}};async function Fo(){let d=await of(),t=navigator.deviceMemory,e=t?Math.round(t*1024):0,r=["wasm"];return d&&r.push("webgpu"),{platform:"web",model:navigator.userAgent,total_memory_mb:e,gpu_available:d,npu_available:!1,supported_runtimes:r}}async function of(){if(typeof navigator>"u")return!1;try{let d=navigator.gpu;return d?await d.requestAdapter()!==null:!1}catch{return!1}}var Er={inferenceStarted:"inference.started",inferenceCompleted:"inference.completed",inferenceFailed:"inference.failed",inferenceChunkProduced:"inference.chunk_produced",deployStarted:"deploy.started",deployCompleted:"deploy.completed"},di={"inference.started":["model.id"],"inference.completed":["model.id","inference.duration_ms"],"inference.failed":["model.id","error.type","error.message"],"inference.chunk_produced":["model.id","inference.chunk_index"],"deploy.started":["model.id","model.version"],"deploy.completed":["model.id","deploy.duration_ms"]};var Ws={serviceName:"service.name",serviceVersion:"service.version",telemetrySdkName:"telemetry.sdk.name",telemetrySdkLanguage:"telemetry.sdk.language",telemetrySdkVersion:"telemetry.sdk.version",octomilOrgId:"octomil.org.id",octomilDeviceId:"octomil.device.id",octomilPlatform:"octomil.platform",octomilSdkSurface:"octomil.sdk.surface",octomilInstallId:"octomil.install.id",octomilDeviceClass:"octomil.device.class",octomilAvailableRuntimes:"octomil.available_runtimes",octomilAccelerators:"octomil.accelerators"};var ym="octomil_install_id",Gs=null;function Ao(){if(Gs!==null)return Gs;try{let t=localStorage.getItem(ym);if(t)return Gs=t,t}catch{}let d=crypto.randomUUID();try{localStorage.setItem(ym,d)}catch{}return Gs=d,d}function Em(){Gs=null}var nf=3e4,af=50,lf="https://api.octomil.com/v2/telemetry/events",_i="browser",cf="1.0.0",os=class{constructor(t={}){v(this,"url");v(this,"flushIntervalMs");v(this,"maxBatchSize");v(this,"apiKey");v(this,"authHeadersProvider");v(this,"resource");v(this,"queue",[]);v(this,"timerId",null);v(this,"disposed",!1);this.url=t.url??lf,this.flushIntervalMs=t.flushIntervalMs??nf,this.maxBatchSize=t.maxBatchSize??af,this.apiKey=t.apiKey,this.authHeadersProvider=t.authHeadersProvider,this.resource={sdk:_i,sdk_version:t.sdkVersion??cf,device_id:t.deviceId??df(),platform:_i,org_id:t.orgId??""},this.startAutoFlush()}updateResource(t){for(let[e,r]of Object.entries(t))e==="device.id"?this.resource.device_id=r:e==="org.id"?this.resource.org_id=r:e==="platform"&&(this.resource.platform=r)}track(t){this.disposed||(this.queue.push(t),this.queue.length>=this.maxBatchSize&&this.flush())}async flush(){if(this.queue.length===0)return;let t=this.queue.splice(0,this.maxBatchSize);await this.send(t)}async batch(t){t.length!==0&&await this.send(t)}close(){if(!this.disposed&&(this.disposed=!0,this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.queue.length>0)){let t=this.queue.splice(0),e=this.buildEnvelope(t);this.sendBeaconPayload(e)||this.send(t)}}reportInferenceStarted(t,e){this.track(this.makeEvent(Er.inferenceStarted,{"model.id":t,...e}))}reportInferenceCompleted(t,e,r){this.track(this.makeEvent(Er.inferenceCompleted,{"model.id":t,"inference.duration_ms":e,...r}))}reportInferenceFailed(t,e,r){this.track(this.makeEvent(Er.inferenceFailed,{"model.id":t,"error.type":e,"error.message":r}))}reportInferenceChunk(t,e){this.track(this.makeEvent(Er.inferenceChunkProduced,{"model.id":t,...e}))}reportChunkProduced(t,e,r){this.track(this.makeEvent(Er.inferenceChunkProduced,{"model.id":t,"inference.chunk_index":e,...r}))}reportTrainingStarted(t,e){this.track(this.makeEvent("training.started",{modelId:t,version:e}))}reportTrainingCompleted(t,e,r){this.track(this.makeEvent("training.completed",{modelId:t,version:e,durationMs:r}))}reportTrainingFailed(t,e,r){this.track(this.makeEvent("training.failed",{modelId:t,version:e,errorType:r}))}reportWeightUpload(t,e,r){this.track(this.makeEvent("training.weight_upload",{modelId:t,roundId:e,sampleCount:r}))}reportDeployStarted(t,e){this.track(this.makeEvent("deploy.started",{modelId:t,version:e}))}reportDeployCompleted(t,e,r){this.track(this.makeEvent("deploy.completed",{modelId:t,version:e,durationMs:r}))}reportDeployRollback(t,e,r,o){this.track(this.makeEvent("deploy.rollback",{modelId:t,fromVersion:e,toVersion:r,reason:o}))}reportExperimentAssigned(t,e,r){this.track(this.makeEvent("experiment.assigned",{modelId:t,experimentId:e,variant:r}))}reportExperimentMetric(t,e,r){this.track(this.makeEvent("experiment.metric",{experimentId:t,metricName:e,metricValue:r}))}makeEvent(t,e){return{name:t,timestamp:new Date().toISOString(),traceId:ui(16),spanId:ui(8),attributes:e}}startAutoFlush(){typeof setInterval>"u"||(this.timerId=setInterval(()=>{this.flush()},this.flushIntervalMs))}buildEnvelope(t){let e=this.resourceToOtlpAttributes(),r=t.map(o=>this.eventToLogRecord(o));return{resourceLogs:[{resource:{attributes:e},scopeLogs:[{scope:{name:`@octomil/${_i}`,version:this.resource.sdk_version},logRecords:r}]}]}}resourceToOtlpAttributes(){let t=[{key:"sdk",value:{stringValue:this.resource.sdk}},{key:"sdk_version",value:{stringValue:this.resource.sdk_version}},{key:"device_id",value:{stringValue:this.resource.device_id}},{key:"platform",value:{stringValue:this.resource.platform}},{key:"org_id",value:{stringValue:this.resource.org_id}}],e=Ao();return e&&t.push({key:Ws.octomilInstallId,value:{stringValue:e}}),t}eventToLogRecord(t){let e=Object.entries(t.attributes).map(([r,o])=>({key:r,value:this.toOtlpValue(o)}));return{timeUnixNano:String(new Date(t.timestamp).getTime()*1e6),severityNumber:9,severityText:"INFO",body:{stringValue:t.name},attributes:e,traceId:t.traceId,spanId:t.spanId}}toOtlpValue(t){return typeof t=="string"?{stringValue:t}:typeof t=="boolean"?{boolValue:t}:Number.isInteger(t)?{intValue:String(t)}:{doubleValue:t}}async send(t){let e=this.buildEnvelope(t),r=JSON.stringify(e),o=this.authHeadersProvider?.()??null;try{if(!o&&this.sendBeaconPayload(e))return;let a={"Content-Type":"application/json"};o?Object.assign(a,o):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),await fetch(this.url,{method:"POST",headers:a,body:r,keepalive:!0})}catch{}}sendBeaconPayload(t){if(typeof navigator>"u"||!navigator.sendBeacon)return!1;try{let e=new Blob([JSON.stringify(t)],{type:"application/json"});return navigator.sendBeacon(this.url,e)}catch{return!1}}};function ui(d){let t=new Uint8Array(d);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let e=0;e<d;e++)t[e]=Math.floor(Math.random()*256);return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function df(){return`dev_${ui(8)}`}var ss=null;function Cm(d={}){return ss&&ss.close(),ss=new os(d),ss}function km(){return ss}function Fm(){ss?.close(),ss=null}var Ks=class{constructor(t){this.runPrediction=t}async create(t){return{output:await this.runPrediction({text:t.input})}}},As=class{constructor(t){v(this,"predictions");this.predictions=new Ks(t)}async predict(t){return this.predictions.create({input:t}).then(e=>e.output)}};var Io=class{constructor(t){v(this,"options");v(this,"cache");v(this,"loader");v(this,"engine");v(this,"inferenceEngine");v(this,"routingClient",null);v(this,"deviceContext");v(this,"telemetry",null);v(this,"deviceCaps",null);v(this,"_responses",null);v(this,"_chat",null);v(this,"_control",null);v(this,"_capabilities",null);v(this,"_models",null);v(this,"_audio",null);v(this,"_text",null);v(this,"loaded",!1);v(this,"closed",!1);v(this,"_warmedUp",!1);let e=t.auth,r=e?.serverUrl,o=e?.type==="org_api_key"?e.apiKey:e?.type==="device_token"?e.bootstrapToken:void 0,a=e?.type==="org_api_key"?e.orgId:zs()?.orgId??void 0;this.deviceContext=zs(),this.options={telemetry:!1,cacheStrategy:"cache-api",...t,serverUrl:r,apiKey:o},this.cache=yo(this.options.cacheStrategy),this.loader=new Es(this.options,this.cache);let h=t.runtime?null:new ys;this.engine=t.runtime??h,this.inferenceEngine=h,r&&o&&this.options.routing&&(this.routingClient=new Fs({serverUrl:r,apiKey:o,cacheTtlMs:this.options.routing.cacheTtlMs,prefer:this.options.routing.prefer})),this.options.telemetry&&(this.telemetry=new os({url:this.options.telemetryUrl,apiKey:o,authHeadersProvider:()=>this.deviceContext?.authHeaders()??null,orgId:a,deviceId:this.deviceContext?.installationId}),this.deviceContext&&this.telemetry.updateResource(this.deviceContext.telemetryResource()))}async load(){this.ensureNotClosed();let t=performance.now(),e=await this.loader.load();await this.engine.createSession(e,this.options.backend),this.loaded=!0;let r=performance.now()-t;this.telemetry?.reportDeployStarted(this.options.model,"latest"),this.telemetry?.reportDeployCompleted(this.options.model,"latest",r)}async warmup(){if(this.ensureReady(),this._warmedUp)return;let t=this.inferenceEngine?this.inferenceEngine.inputNames[0]:void 0;if(t){let e={[t]:{data:new Float32Array([0]),dims:[1,1]}};try{await this.engine.run(e)}catch{}}this._warmedUp=!0}get isWarmedUp(){return this._warmedUp}async predict(t){if(this.ensureReady(),this.routingClient){let o=await this.tryCloudInference(t);if(o)return o}let e=this.prepareTensors(t);this.telemetry?.reportInferenceStarted(this.options.model,{target:"device"});let r=await this.engine.run(e);return this.telemetry?.reportInferenceCompleted(this.options.model,r.latencyMs,{backend:this.inferenceEngine?.activeBackend??"unknown",target:"device"}),r}async predictBatch(t){this.ensureReady();let e=performance.now(),r=[];for(let a of t){let h=this.prepareTensors(a),u=await this.engine.run(h);r.push(u)}let o=performance.now()-e;return this.telemetry?.reportInferenceCompleted(this.options.model,o,{backend:this.inferenceEngine?.activeBackend??"unknown",batchSize:t.length}),r}async createChat(t,e={}){return this.chat.create(t,e)}async*createChatStream(t,e={}){yield*this.chat.stream(t,e)}async*predictStream(t,e,r,o){if(!this.options.serverUrl||!this.options.apiKey)throw new Pe("INFERENCE_FAILED","predictStream() requires serverUrl and apiKey to be configured.");let a=`${this.options.serverUrl.replace(/\/+$/,"")}/api/v1/inference/stream`,h={model_id:t};typeof e=="string"?h.input_data=e:h.messages=e,r&&(h.parameters=r);let u={"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.options.apiKey}`},l;try{l=await fetch(a,{method:"POST",headers:u,body:JSON.stringify(h),signal:o})}catch(y){throw new Pe("NETWORK_UNAVAILABLE",`predictStream request failed: ${String(y)}`,y)}if(!l.ok)throw new Pe("INFERENCE_FAILED",`predictStream failed: HTTP ${l.status}`);if(!l.body)throw new Pe("INFERENCE_FAILED","Server did not return a streaming body.");let p=l.body.getReader(),w=new TextDecoder,f="",i=0;try{for(;;){let{done:y,value:E}=await p.read();if(y)break;f+=w.decode(E,{stream:!0});let S=f.split(`
34
- `);f=S.pop()??"";for(let z of S){if(!z.startsWith("data:"))continue;let k=z.slice(5).trim();if(!k)continue;let A;try{A=JSON.parse(k)}catch{continue}this.telemetry?.reportChunkProduced(t,i),i++,yield{token:A.token??"",done:A.done??!1,provider:A.provider,latencyMs:A.latency_ms,sessionId:A.session_id}}}}finally{p.releaseLock()}}async embed(t,e,r){if(!this.options.serverUrl||!this.options.apiKey)throw new Pe("NETWORK_UNAVAILABLE","embed() requires serverUrl and apiKey to be configured.");return ko(this.options.serverUrl,this.options.apiKey,t,e,r)}async isCached(){return this.ensureNotClosed(),this.loader.isCached()}async clearCache(){return this.ensureNotClosed(),this.loader.clearCache()}async cacheInfo(){return this.ensureNotClosed(),this.loader.getCacheInfo()}get activeBackend(){return this.inferenceEngine?.activeBackend??null}get inputNames(){if(this.ensureReady(),!this.inferenceEngine)throw new Pe("INVALID_INPUT","inputNames not available with custom runtime");return this.inferenceEngine.inputNames}get outputNames(){if(this.ensureReady(),!this.inferenceEngine)throw new Pe("INVALID_INPUT","outputNames not available with custom runtime");return this.inferenceEngine.outputNames}get isLoaded(){return this.loaded}get chat(){return this._chat||(this._chat=new bs({model:this.options.model,serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,getResponses:()=>this.responses,ensureReady:()=>this.ensureReady()})),this._chat}get responses(){return this._responses||(this._responses=new ks({serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,telemetry:this.telemetry,deviceContext:this.deviceContext,localRuntime:this.options.responsesRuntime})),this._responses}get control(){return this._control||(this._control=new xs({serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,orgId:this.options.auth?.type==="org_api_key"?this.options.auth.orgId:void 0,deviceContext:this.deviceContext,telemetry:this.telemetry})),this._control}get capabilities(){return this._capabilities||(this._capabilities=new Ps),this._capabilities}get models(){return this._models||(this._models=new Cs(this.options.model,this.loader,()=>{})),this._models}get audio(){if(!this._audio){if(!this.options.serverUrl||!this.options.apiKey)throw new Pe("INVALID_INPUT","audio requires serverUrl and apiKey to be configured.");this._audio=new vs(this.options.serverUrl,this.options.apiKey)}return this._audio}get text(){return this._text||(this._text=new As(t=>this.predict(t))),this._text}close(){this.closed||(this.closed=!0,this.loaded=!1,this.engine.dispose(),this.telemetry?.close(),this.telemetry=null,this._responses=null,this._chat=null,this._control?.stopHeartbeat(),this._control=null,this._capabilities=null,this._models=null,this._audio=null,this._text=null,this._warmedUp=!1)}ensureNotClosed(){if(this.closed)throw new Pe("CANCELLED","This OctomilClient instance has been closed. Create a new one.")}ensureReady(){if(this.ensureNotClosed(),!this.loaded)throw new Pe("MODEL_LOAD_FAILED","Model not loaded. Call load() before predict() or chat().")}prepareTensors(t){if(this.isNamedTensors(t))return t;if("raw"in t&&"dims"in t){let e=this.inferenceEngine.inputNames[0];if(!e)throw new Pe("INVALID_INPUT","Model has no input tensors defined.");return{[e]:{data:t.raw,dims:t.dims}}}if("text"in t){let e=this.inferenceEngine.inputNames[0];if(!e)throw new Pe("INVALID_INPUT","Model has no input tensors defined.");let r=new Int32Array(Array.from(t.text).map(o=>o.codePointAt(0)??0));return{[e]:{data:r,dims:[1,r.length]}}}if("image"in t)return this.imageToTensors(t.image);throw new Pe("INVALID_INPUT","Unrecognised PredictInput format. Provide named tensors, { text }, { image }, or { raw, dims }.")}isNamedTensors(t){if("text"in t||"image"in t||"raw"in t)return!1;let e=Object.values(t)[0];return e!==void 0&&typeof e=="object"&&"data"in e&&"dims"in e}imageToTensors(t){let e;if(t instanceof ImageData)e=t;else{let p=t instanceof HTMLCanvasElement?t:(()=>{let f=document.createElement("canvas");return f.width=t.naturalWidth||t.width,f.height=t.naturalHeight||t.height,f.getContext("2d").drawImage(t,0,0),f})(),w=p.getContext("2d");if(!w)throw new Pe("INVALID_INPUT","Could not get 2D context from canvas.");e=w.getImageData(0,0,p.width,p.height)}let{width:r,height:o,data:a}=e,h=r*o,u=new Float32Array(3*h);for(let p=0;p<h;p++)u[p]=a[p*4]/255,u[h+p]=a[p*4+1]/255,u[2*h+p]=a[p*4+2]/255;let l=this.inferenceEngine?.inputNames[0];if(!l)throw new Pe("INVALID_INPUT","Model has no input tensors defined.");return{[l]:{data:u,dims:[1,3,o,r]}}}async tryCloudInference(t){try{this.deviceCaps||(this.deviceCaps=await Fo());let e=this.options.routing,r=await this.routingClient.route(this.options.model,e.modelParams??0,e.modelSizeMb??0,this.deviceCaps);if(!r||r.target!=="cloud")return null;let o=performance.now(),a=await this.routingClient.cloudInfer(this.options.model,t),h=performance.now()-o;return this.telemetry?.reportInferenceCompleted(this.options.model,h,{target:"cloud",provider:a.provider,routingId:r.id}),{tensors:{},latencyMs:h,...typeof a.output=="object"&&a.output!==null?a.output:{label:String(a.output)}}}catch{return null}}};var So=class extends _r{constructor(t={}){super(t)}async getAlertRule(t,e){return this.requestJson(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"GET"},{org_id:e??this.orgId})}async updateAlertRule(t,e,r){return this.requestJson(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)},{org_id:r??this.orgId})}async deleteAlertRule(t,e){await this.requestVoid(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"DELETE"},{org_id:e??this.orgId})}};var Do=class extends _r{constructor(t={}){super(t)}async createCheckoutSession(t,e){return this.requestJson("/api/v1/settings/billing/checkout",{method:"POST",body:JSON.stringify(t)},{org_id:e??this.orgId})}async createPortalSession(t,e){return this.requestJson("/api/v1/settings/billing/portal",{method:"POST",body:JSON.stringify(t)},{org_id:e??this.orgId})}async updateBilling(t,e){return this.requestJson("/api/v1/settings/billing",{method:"PATCH",body:JSON.stringify(t)},{org_id:e??this.orgId})}async getUsageLimits(t){return this.requestJson("/api/v1/settings/usage-limits",{method:"GET"},{org_id:t??this.orgId})}async updateUsageLimits(t,e){return this.requestJson("/api/v1/settings/usage-limits",{method:"PUT",body:JSON.stringify(t)},{org_id:e??this.orgId})}async getIntegration(t,e){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"GET"},{org_id:e??this.orgId})}async updateIntegration(t,e,r){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)},{org_id:r??this.orgId})}async deleteIntegration(t,e){await this.requestVoid(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"DELETE"},{org_id:e??this.orgId})}async validateIntegration(t,e){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify({})},{org_id:e??this.orgId})}};var Lo=class extends _r{constructor(e){super(e);v(this,"getDeviceId");this.getDeviceId=e.getDeviceId}async createJob(e){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs`,{method:"POST",body:JSON.stringify(e)})}async jobStatus(e,r){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs/${encodeURIComponent(e)}/status`,{method:"POST",body:JSON.stringify(r)})}async jobComplete(e,r){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs/${encodeURIComponent(e)}/complete`,{method:"POST",body:JSON.stringify(r)})}requireDeviceId(){let e=this.getDeviceId();if(!e)throw new Pe("DEVICE_NOT_REGISTERED","This operation requires a registered device ID.");return e}};var Oo=class{constructor(t){this.control=t}async desiredState(){return this.control.fetchDesiredState()}async observedState(t=[]){await this.control.reportObservedState(t)}async sync(t={}){return this.control.sync(t)}};async function $s(d){let t=await crypto.subtle.digest("SHA-256",d),e=new Uint8Array(t);return Array.from(e).map(r=>r.toString(16).padStart(2,"0")).join("")}async function pi(d,t){return await $s(d)===t.toLowerCase()}async function Am(d,t){if(!await pi(d,t))throw new Pe("MODEL_LOAD_FAILED","Model integrity check failed: SHA-256 hash mismatch. The downloaded model may be corrupted or tampered with.")}var _f="octomil-sync-meta",Ro="models",uf=1,mi=class{constructor(){v(this,"dbPromise",null)}openDB(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,e)=>{let r=indexedDB.open(_f,uf);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(Ro)||o.createObjectStore(Ro,{keyPath:"modelId"})},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error)}),this.dbPromise)}async tx(t){return(await this.openDB()).transaction(Ro,t).objectStore(Ro)}async get(t){let e=await this.tx("readonly");return new Promise((r,o)=>{let a=e.get(t);a.onsuccess=()=>r(a.result??null),a.onerror=()=>o(a.error)})}async put(t){let e=await this.tx("readwrite");return new Promise((r,o)=>{let a=e.put(t);a.onsuccess=()=>r(),a.onerror=()=>o(a.error)})}async getAll(){let t=await this.tx("readonly");return new Promise((e,r)=>{let o=t.getAll();o.onsuccess=()=>e(o.result),o.onerror=()=>r(o.error)})}async remove(t){let e=await this.tx("readwrite");return new Promise((r,o)=>{let a=e.delete(t);a.onsuccess=()=>r(),a.onerror=()=>o(a.error)})}},Bo=class{constructor(t){v(this,"control");v(this,"cache");v(this,"intervalMs");v(this,"onEvent");v(this,"meta");v(this,"timer",null);v(this,"syncing",!1);this.control=t.control,this.cache=t.cache,this.intervalMs=t.intervalMs??3e5,this.onEvent=t.onEvent,this.meta=new mi}start(){this.stop(),this.sync(),this.intervalMs>0&&(this.timer=setInterval(()=>{this.sync()},this.intervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}get isRunning(){return this.timer!==null}async sync(){if(this.syncing)return;this.syncing=!0;let t=0,e=0,r=0;try{this.emit({type:"sync_start"});let o=await this.control.fetchDesiredState(),a=this.parseDesiredEntries(o);for(let h of a)try{let u=await this.reconcileEntry(h);u.downloaded&&t++,u.activated&&e++}catch(u){r++,this.emit({type:"download_error",modelId:h.modelId,error:String(u)})}await this.garbageCollect(o,a),await this.reportState(),this.emit({type:"sync_complete",downloaded:t,activated:e,errors:r})}catch(o){this.emit({type:"error",error:String(o)})}finally{this.syncing=!1}}async getLocalModels(){return this.meta.getAll()}async getModelMeta(t){return this.meta.get(t)}async activate(t){let e=await this.meta.get(t);if(!e)throw new Pe("MODEL_NOT_FOUND",`No local model found for ${t}`);e.status!=="active"&&(e.status="active",await this.meta.put(e),this.emit({type:"activate",modelId:t,version:e.modelVersion}))}parseDesiredEntries(t){return t.models}async reconcileEntry(t){let e=await this.meta.get(t.modelId);if(e&&e.modelVersion===t.desiredVersion&&e.status==="active")return{downloaded:!1,activated:!1};if(e&&e.modelVersion===t.desiredVersion&&e.status==="staged")return this.shouldActivate(t.activationPolicy)?(e.status="active",await this.meta.put(e),this.emit({type:"activate",modelId:t.modelId,version:t.desiredVersion}),{downloaded:!1,activated:!0}):{downloaded:!1,activated:!1};if(!t.artifactManifest?.downloadUrl)return{downloaded:!1,activated:!1};this.emit({type:"download_start",modelId:t.modelId});let r=await this.downloadArtifact(t.artifactManifest.downloadUrl);if(t.artifactManifest.sha256){let u=await $s(r);if(u!==t.artifactManifest.sha256.toLowerCase())throw new Pe("MODEL_LOAD_FAILED",`Integrity check failed for ${t.modelId}: expected ${t.artifactManifest.sha256}, got ${u}`)}let o=t.artifactManifest.downloadUrl;await this.cache.put(o,r),this.emit({type:"download_complete",modelId:t.modelId,sizeBytes:r.byteLength});let a=this.shouldActivate(t.activationPolicy),h={modelId:t.modelId,modelVersion:t.desiredVersion,bindingKey:t.bindingKey,useCase:t.useCase,deploymentId:t.deploymentId,deploymentKey:t.deploymentKey,modelName:t.modelName,modelRef:t.modelRef,artifactUrl:o,sha256:t.artifactManifest.sha256,installedAt:new Date().toISOString(),status:a?"active":"staged",sizeBytes:r.byteLength};return await this.meta.put(h),a&&this.emit({type:"activate",modelId:t.modelId,version:t.desiredVersion}),{downloaded:!0,activated:a}}shouldActivate(t){switch(t){case"immediate":case void 0:return!0;case"manual":return!1;case"next_launch":return!1;case"when_idle":return!0;default:return!0}}async downloadArtifact(t){let e;try{e=await fetch(t)}catch(r){throw new Pe("NETWORK_UNAVAILABLE",`Failed to download artifact from ${t}: ${String(r)}`,r)}if(!e.ok)throw new Pe("MODEL_LOAD_FAILED",`Artifact download failed: HTTP ${e.status}`);return e.arrayBuffer()}async garbageCollect(t,e){let r=new Set(t.gcEligibleArtifactIds??[]),o=new Set(e.map(h=>h.modelId)),a=await this.meta.getAll();for(let h of a)(r.has(h.modelId)||!o.has(h.modelId))&&(await this.cache.remove(h.artifactUrl),await this.meta.remove(h.modelId))}async reportState(){let e=(await this.meta.getAll()).map(r=>({modelId:r.modelId,status:r.status,version:r.modelVersion,bindingKey:r.bindingKey,useCase:r.useCase,deploymentId:r.deploymentId,deploymentKey:r.deploymentKey,modelName:r.modelName,modelRef:r.modelRef}));try{await this.control.reportObservedState(e)}catch{}}emit(t){this.onEvent?.(t)}};var Im=3e4,No=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"token",null);v(this,"deviceId",null);v(this,"refreshTimer",null);v(this,"disposed",!1);this.serverUrl=t.serverUrl,this.apiKey=t.apiKey}async bootstrap(t){this.ensureNotDisposed(),this.deviceId=await this.generateDeviceId();let e=this.collectDeviceInfo(),r=await this.request("/api/v1/devices/register",{method:"POST",body:JSON.stringify({org_id:t,device_id:this.deviceId,platform:"browser",info:e})});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Device registration failed: HTTP ${r.status}`);let o=await r.json();this.token={accessToken:o.token,refreshToken:o.refresh_token,expiresAt:new Date(o.expires_at).getTime()},this.scheduleRefresh()}async getToken(){if(this.ensureNotDisposed(),!this.token)throw new Pe("NETWORK_UNAVAILABLE","Not authenticated. Call bootstrap() first.");return this.isTokenExpiringSoon()&&await this.refreshToken(),this.token.accessToken}async refreshToken(){if(this.ensureNotDisposed(),!this.token)throw new Pe("NETWORK_UNAVAILABLE","No token to refresh. Call bootstrap() first.");let t=await this.request("/api/v1/auth/refresh",{method:"POST",body:JSON.stringify({refresh_token:this.token.refreshToken,device_id:this.deviceId})});if(!t.ok)throw this.token=null,new Pe("NETWORK_UNAVAILABLE",`Token refresh failed: HTTP ${t.status}`);let e=await t.json();this.token={accessToken:e.token,refreshToken:e.refresh_token,expiresAt:new Date(e.expires_at).getTime()},this.scheduleRefresh()}async revokeToken(){if(this.ensureNotDisposed(),!!this.token)try{await this.request("/api/v1/auth/revoke",{method:"POST",body:JSON.stringify({token:this.token.accessToken,device_id:this.deviceId})})}finally{this.clearState()}}get isAuthenticated(){return this.token!==null&&!this.isTokenExpired()}get currentDeviceId(){return this.deviceId}dispose(){this.disposed||(this.disposed=!0,this.clearRefreshTimer())}async request(t,e){let r={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return fetch(`${this.serverUrl}${t}`,{...e,headers:{...r,...e.headers}})}isTokenExpired(){return this.token?Date.now()>=this.token.expiresAt:!0}isTokenExpiringSoon(){return this.token?Date.now()>=this.token.expiresAt-Im:!0}scheduleRefresh(){if(this.clearRefreshTimer(),!this.token)return;let t=Math.max(0,this.token.expiresAt-Date.now()-Im);this.refreshTimer=setTimeout(()=>{this.refreshToken().catch(()=>{})},t)}clearRefreshTimer(){this.refreshTimer!==null&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}clearState(){this.token=null,this.clearRefreshTimer()}async generateDeviceId(){let t=[typeof navigator<"u"?navigator.userAgent:"unknown",typeof screen<"u"?`${screen.width}x${screen.height}`:"0x0",typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",typeof navigator<"u"?navigator.language:"en"].join("|"),e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e),o=new Uint8Array(r);return Array.from(o).map(a=>a.toString(16).padStart(2,"0")).join("")}collectDeviceInfo(){return{userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",language:typeof navigator<"u"?navigator.language:"en",screenWidth:typeof screen<"u"?screen.width:0,screenHeight:typeof screen<"u"?screen.height:0,timezone:typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",webgpu:typeof navigator<"u"&&"gpu"in navigator}}ensureNotDisposed(){if(this.disposed)throw new Pe("CANCELLED","DeviceAuth has been disposed.")}};var jo=class extends _r{constructor(t={}){super(t)}async manifest(t){return this.requestJson(`/api/v1/artifacts/${encodeURIComponent(t)}/manifest`,{method:"GET"})}async downloadUrls(t,e){return this.requestJson(`/api/v1/artifacts/${encodeURIComponent(t)}/download-urls`,{method:"POST",body:JSON.stringify(e)})}};function pf(d){return d.filter(t=>t.type==="tool_call"&&!!t.toolCall).map(t=>t.toolCall)}function mf(d){return{role:"assistant",content:d.map(t=>({type:"tool_call",toolCall:t}))}}var Vo=class{constructor(t,e,r=10){v(this,"responses");v(this,"executor");v(this,"maxIterations");this.responses=t,this.executor=e,this.maxIterations=r}async run(t){let e=this.normalizeInput(t.input);for(let r=0;r<this.maxIterations;r++){let o=await this.responses.create({...t,input:e}),a=pf(o.output);if(a.length===0)return o;e.push(mf(a));for(let h of a){let u;try{u=await this.executor.execute(h)}catch(l){u={toolCallId:h.id,content:l instanceof Error?`Error: ${l.message}`:"Error",isError:!0}}e.push({role:"tool",toolCallId:u.toolCallId,content:u.content})}}return this.responses.create({...t,input:e,tools:[]})}normalizeInput(t){return typeof t=="string"?[{role:"user",content:t}]:t.every(e=>"role"in e)?t.map(e=>({...e})):[{role:"user",content:t}]}};var pS="Qwen/Qwen3-0.6B",mS="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.2/dist/",uh=new Map;function mh(d={}){let t=hS(d);return{async create(e){let r=await gS(e,t);return CS(e,t.model,r)},async*stream(e){let r=await this.create(e),o=r.output[0];o?.type==="tool_call"?yield{type:"tool_call_delta",index:0,id:o.toolCall?.id,name:o.toolCall?.name,argumentsDelta:o.toolCall?.arguments}:o?.type==="text"&&o.text&&(yield{type:"text_delta",delta:o.text}),yield{type:"done",response:r}}}}function hS(d={}){let t=d.model??pS,e=d.runtimeModel??fS(t);return{model:t,runtimeModel:e,device:d.device??"auto",dtype:d.dtype??"q4",maxNewTokens:d.maxNewTokens??128,maxInputChars:d.maxInputChars??4e3,temperature:d.temperature??0,topP:d.topP??.95,repetitionPenalty:d.repetitionPenalty??1.05,ortWasmBaseUrl:vS(d.ortWasmBaseUrl)??mS,useBrowserCache:d.useBrowserCache??!1}}function fS(d){return d.startsWith("onnx-community/")?d:`onnx-community/${d.replace(/^Qwen\//,"")}-ONNX`}async function gS(d,t){let e=await MS(t),r=PS(d,t.maxInputChars),o=TS(e,r),a=await e(o,{max_new_tokens:d.maxOutputTokens??t.maxNewTokens,temperature:d.temperature??t.temperature,top_p:d.topP??t.topP,repetition_penalty:t.repetitionPenalty,do_sample:(d.temperature??t.temperature)>0,return_full_text:!1});return ES(a)}async function MS(d){let t=JSON.stringify([d.runtimeModel,ph(d.device),d.dtype]),e=uh.get(t);return e||(e=(async()=>{let{pipeline:r}=await wS(d);return r("text-generation",d.runtimeModel,{device:ph(d.device),dtype:d.dtype})})(),uh.set(t,e)),e}async function wS(d){let t=await Promise.resolve().then(()=>(_h(),dh));t.env&&(t.env.useBrowserCache=d.useBrowserCache);let e=t.env?.backends?.onnx?.wasm;return e&&(e.wasmPaths=d.ortWasmBaseUrl,e.proxy=!1),t}function ph(d){return d==="webgpu"||d==="wasm"?d:typeof navigator<"u"&&"gpu"in navigator?"webgpu":"wasm"}function TS(d,t){let e=d.tokenizer?.apply_chat_template;return e?e.call(d.tokenizer,t,{tokenize:!1,add_generation_prompt:!0,enable_thinking:!1}):t}function vS(d){if(d)return d.endsWith("/")?d:`${d}/`}function PS(d,t){let e=bS(d.tools),o=FS(d.input).flatMap(a=>xS(a)).filter(a=>a!==null);return o[0]?.role==="system"?o[0]={role:"system",content:`${e}
35
-
36
- ${o[0].content}`.trim()}:o.unshift({role:"system",content:e}),AS(o,t)}function bS(d){let t=["You are Octomil's local browser agent runtime.","Do not reveal chain-of-thought or emit <think> tags.","Answer directly when no tool is needed."];return!d||d.length===0?t.join(`
37
- `):[...t,"When a tool is required, respond with exactly one XML block in this form and no extra prose:",'<tool_call>{"name":"tool_name","arguments":{}}</tool_call>',"Use one of these tools:",...d.map(e=>`- ${e.function.name}: ${e.function.description??"No description provided"}; parameters=${JSON.stringify(e.function.parameters??{})}`)].join(`
38
- `)}function xS(d){if(!d||typeof d!="object"||!("role"in d))return[];switch(d.role){case"system":return[{role:"system",content:vi(d.content)}];case"user":return[{role:"user",content:vi(d.content)}];case"assistant":return[{role:"assistant",content:yS(d.content)}];case"tool":return[{role:"user",content:`Tool result for ${d.toolCallId??"tool"}:
39
- ${vi(d.content)}`}];default:return[]}}function yS(d){return typeof d=="string"?d:Array.isArray(d)?d.map(t=>!t||typeof t!="object"||!("type"in t)?"":t.type==="text"?typeof t.text=="string"?t.text:"":t.type==="tool_call"&&t.toolCall?`<tool_call>${JSON.stringify({name:t.toolCall.name,arguments:hh(t.toolCall.arguments)??t.toolCall.arguments})}</tool_call>`:"").filter(Boolean).join(`
40
- `):""}function vi(d){return typeof d=="string"?d:Array.isArray(d)?d.map(t=>!t||typeof t!="object"||!("type"in t)?"":t.type==="text"?t.text??"":t.type==="image"?"[image omitted]":t.type==="audio"?"[audio omitted]":t.type==="video"?"[video omitted]":t.type==="file"?"[file omitted]":"").filter(Boolean).join(`
41
- `):""}function ES(d){let t=Array.isArray(d)?d[0]:d,e=t?.generated_text??t;if(typeof e=="string")return e;if(Array.isArray(e)){let r=e.at(-1);if(typeof r=="string")return r;if(r&&typeof r=="object"&&"content"in r)return typeof r.content=="string"?r.content:""}return e&&typeof e=="object"&&"content"in e?typeof e.content=="string"?e.content:"":String(e??"")}function CS(d,t,e){let r=DS(e).trim(),o=kS(r,d.tools),a=o?[{type:"tool_call",toolCall:{id:LS(),name:o.name,arguments:JSON.stringify(o.arguments)}}]:[{type:"text",text:r}];return{id:rs(),model:t,output:a,finishReason:o?"tool_calls":"stop"}}function kS(d,t){if(!t||t.length===0)return null;let e=new Set(t.map(o=>o.function.name)),r=[...d.matchAll(/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/gi),...d.matchAll(/```json\s*([\s\S]*?)\s*```/gi)].map(o=>o[1]?.trim()).filter(Boolean);for(let o of r){let a=hh(o);if(!SS(a))continue;let h=typeof a.name=="string"?a.name:null;if(!h||!e.has(h))continue;let u=a.arguments&&typeof a.arguments=="object"?a.arguments:{};return{name:h,arguments:u}}return null}function hh(d){try{return JSON.parse(d)}catch{return null}}function FS(d){return typeof d=="string"?[{role:"user",content:d}]:Array.isArray(d)&&d.every(t=>t&&typeof t=="object"&&"role"in t)?d:[{role:"user",content:d}]}function AS(d,t){if(d.length<=1||t<=0)return d;let e=d[0]?.role==="system"?d[0]:null,r=Math.max(t-(e?.content.length??0),512),o=e?d.slice(1):d.slice(),a=[],h=0;for(let u=o.length-1;u>=0;u-=1){let l=o[u];if(!l)continue;let p=l.content.length;if(h+p<=r){a.unshift(l),h+=p;continue}a.length===0&&a.unshift({role:l.role,content:IS(l.content,r)});break}return e?[e,...a]:a}function IS(d,t){return d.length<=t?d:`[truncated]
42
- ${d.slice(-Math.max(t-32,0)).trim()}`.trim()}function SS(d){return!!d&&typeof d=="object"}function DS(d){return d.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<think>[\s\S]*$/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/<thinking>[\s\S]*$/gi,"").trim()}function LS(){return`call_${Math.random().toString(36).slice(2,10)}`}var Qo=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"telemetry");this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.telemetry=t.telemetry}async*stream(t,e,r={}){let o=new AbortController,a=r.signal?this.combineSignals(r.signal,o.signal):o.signal,h=`${this.serverUrl}/api/v1/models/${encodeURIComponent(t)}/stream`,u={"Content-Type":"application/json",Accept:"text/event-stream"};this.apiKey&&(u.Authorization=`Bearer ${this.apiKey}`);let l=performance.now(),p=null,w=0,f=0;this.telemetry?.reportInferenceStarted(t,{modality:r.modality??"text"});let i;try{i=await fetch(h,{method:"POST",headers:u,body:JSON.stringify({input:e,modality:r.modality??"text",...r.params}),signal:a})}catch(k){throw this.telemetry?.reportInferenceFailed(t,"network_error",String(k)),new Pe("NETWORK_UNAVAILABLE",`Streaming request failed: ${String(k)}`,k)}if(!i.ok)throw new Pe("INFERENCE_FAILED",`Streaming inference failed: HTTP ${i.status}`);if(!i.body)throw new Pe("INFERENCE_FAILED","Server did not return a streaming body.");let y=i.body.getReader(),E=new TextDecoder,S="";try{for(;;){let{done:k,value:A}=await y.read();if(k)break;S+=E.decode(A,{stream:!0});let N=S.split(`
43
- `);S=N.pop()??"";for(let x of N){if(!x.startsWith("data: "))continue;let P=x.slice(6).trim();if(P==="[DONE]")break;let D;try{D=JSON.parse(P)}catch{continue}w++,f+=P.length,p===null&&(p=performance.now()-l,this.telemetry?.reportInferenceChunk(t,{chunkIndex:0,ttfc:!0,durationMs:p})),this.telemetry?.reportChunkProduced(t,w-1),yield D}}}finally{y.releaseLock()}let z=performance.now()-l;return this.telemetry?.reportInferenceCompleted(t,z,{chunkCount:w,totalBytes:f,ttfcMs:p??z}),{totalChunks:w,totalBytes:f,durationMs:z,ttfcMs:p??z}}combineSignals(...t){let e=new AbortController;for(let r of t){if(r.aborted)return e.abort(r.reason),e.signal;r.addEventListener("abort",()=>e.abort(r.reason),{once:!0})}return e.signal}};var Qs=class{constructor(){v(this,"plugins",new Map)}register(t){this.plugins.set(t.name,t)}remove(t){return this.plugins.delete(t)}get(t){return this.plugins.get(t)}get engines(){return[...this.plugins.keys()]}reset(){this.plugins.clear()}async detectAll(t){let e=[];for(let r of this.sortedPlugins()){let o=await r.detect(),a=t?r.supportsModel(t):!0,h=o?await r.detectInfo():"";e.push({engine:r.name,available:o&&a,info:h})}return e}async benchmarkAll(t,e){let o=(await this.detectAll(t)).filter(h=>h.available),a=[];for(let h of o){let l=await this.plugins.get(h.engine).benchmark(t,e);a.push({engine:h.engine,result:l})}return a.sort((h,u)=>u.result.tokens_per_second-h.result.tokens_per_second),a}selectBest(t){return t.find(e=>e.result.error==null)??null}async autoSelect(t,e){let r=await this.benchmarkAll(t,e);return this.selectBest(r)}sortedPlugins(){return[...this.plugins.values()].sort((t,e)=>t.priority-e.priority)}};var Xs=class{static computeDelta(t,e){let r={};for(let o of Object.keys(t)){let a=t[o],h=e[o];if(!a||!h||a.length!==h.length)throw new Pe("INVALID_INPUT",`Weight dimension mismatch for "${o}".`);let u=new Float32Array(a.length);for(let l=0;l<a.length;l++)u[l]=h[l]-a[l];r[o]=u}return r}static applyDelta(t,e){let r={};for(let o of Object.keys(t)){let a=t[o],h=e[o];if(!a)continue;if(!h||a.length!==h.length){r[o]=new Float32Array(a);continue}let u=new Float32Array(a.length);for(let l=0;l<a.length;l++)u[l]=a[l]+h[l];r[o]=u}return r}static l2Norm(t){let e=0;for(let r of Object.values(t))if(r)for(let o=0;o<r.length;o++)e+=r[o]*r[o];return Math.sqrt(e)}},Xo=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"deviceId");v(this,"telemetry");this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.deviceId=t.deviceId,this.telemetry=t.telemetry}async getTrainingRound(t){let e=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/current`);if(!e.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to fetch training round: HTTP ${e.status}`);return await e.json()}async joinRound(t,e){let r=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/${encodeURIComponent(e)}/join`,{method:"POST",body:JSON.stringify({device_id:this.deviceId})});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to join round: HTTP ${r.status}`)}async offers(){let t=await this.request(`/api/v1/federation/rounds/offers?deviceId=${encodeURIComponent(this.deviceId)}`,{method:"GET"});if(!t.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to fetch round offers: HTTP ${t.status}`);return await t.json()}async join(t,e={}){let r=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({deviceId:this.deviceId,...e})});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to join federation round: HTTP ${r.status}`);return await r.json()}async plan(t){let e=await this.request(`/api/v1/federation/plans/${encodeURIComponent(t)}`,{method:"GET"});if(!e.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to fetch federation plan: HTTP ${e.status}`);return await e.json()}async heartbeat(t,e={}){let r=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/heartbeat`,{method:"POST",body:JSON.stringify({deviceId:this.deviceId,...e})});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to send federation heartbeat: HTTP ${r.status}`);return await r.json()}async uploadInitiate(t,e){let r=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/updates/initiate`,{method:"POST",body:JSON.stringify(e)});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to initiate upload: HTTP ${r.status}`);return await r.json()}async uploadComplete(t,e,r){let o=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/updates/${encodeURIComponent(e)}/complete`,{method:"POST",body:JSON.stringify(r)});if(!o.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to complete upload: HTTP ${o.status}`);return await o.json()}async train(t,e){let r=performance.now(),o=this.cloneWeights(t);for(let l=0;l<e.epochs;l++)o=(await e.onTrainStep(o,{epoch:l,batchSize:e.batchSize,learningRate:e.learningRate})).weights;let a=Xs.computeDelta(t,o),h=performance.now()-r,u=e.modelId??"unknown";return this.telemetry?.reportTrainingStarted(u,"local"),this.telemetry?.reportTrainingCompleted(u,"local",h),{finalWeights:o,delta:a}}async submitUpdate(t,e,r,o){let a={};for(let[u,l]of Object.entries(r))l&&(a[u]={data:Array.from(l),shape:[l.length]});let h=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/${encodeURIComponent(e)}/submit`,{method:"POST",body:JSON.stringify({device_id:this.deviceId,delta:a,metrics:o})});if(!h.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to submit update: HTTP ${h.status}`)}async request(t,e){let r={"Content-Type":"application/json"};return this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),fetch(`${this.serverUrl}${t}`,{...e,headers:{...r,...e?.headers}})}cloneWeights(t){let e={};for(let[r,o]of Object.entries(t))o&&(e[r]=new Float32Array(o));return e}};var qo=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.apiKey=t.apiKey}async descriptive(t){return this.post("/api/v1/analytics/descriptive",{variable:t.variable,group_by:t.groupBy??"device_group",group_ids:t.groupIds??null,include_percentiles:t.includePercentiles??!0,filters:t.filters?Jo(t.filters):null})}async tTest(t){return this.post("/api/v1/analytics/t-test",{variable:t.variable,group_a:t.groupA,group_b:t.groupB,confidence_level:t.confidenceLevel??.95,filters:t.filters?Jo(t.filters):null})}async chiSquare(t){return this.post("/api/v1/analytics/chi-square",{variable_1:t.variable1,variable_2:t.variable2,group_ids:t.groupIds??null,confidence_level:t.confidenceLevel??.95,filters:t.filters?Jo(t.filters):null})}async anova(t){return this.post("/api/v1/analytics/anova",{variable:t.variable,group_by:t.groupBy??"device_group",group_ids:t.groupIds??null,confidence_level:t.confidenceLevel??.95,post_hoc:t.postHoc??!0,filters:t.filters?Jo(t.filters):null})}async listQueries(t=50,e=0){let r=new URLSearchParams({limit:String(t),offset:String(e)});return this.get(`/api/v1/analytics/queries?${r.toString()}`)}async getQuery(t){return this.get(`/api/v1/analytics/queries/${encodeURIComponent(t)}`)}buildHeaders(){let t={Accept:"application/json","Content-Type":"application/json"};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async post(t,e){let r=`${this.serverUrl}${t}`,o=await fetch(r,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(e)});if(!o.ok)throw new Pe("NETWORK_UNAVAILABLE",`Analytics request failed: HTTP ${o.status}`);return await o.json()}async get(t){let e=`${this.serverUrl}${t}`,r=await fetch(e,{method:"GET",headers:this.buildHeaders()});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Analytics request failed: HTTP ${r.status}`);return await r.json()}};function Jo(d){return{start_time:d.startTime??null,end_time:d.endTime??null,device_platform:d.devicePlatform??null,min_sample_count:d.minSampleCount??null}}var Js=class{constructor(){v(this,"keyPair",null)}async generateKeyPair(){return this.keyPair=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),{publicKey:await crypto.subtle.exportKey("jwk",this.keyPair.publicKey)}}async deriveSharedSecret(t){if(!this.keyPair)throw new Pe("INVALID_INPUT","Call generateKeyPair() first.");let e=await crypto.subtle.importKey("jwk",t,{name:"ECDH",namedCurve:"P-256"},!1,[]);return crypto.subtle.deriveBits({name:"ECDH",public:e},this.keyPair.privateKey,256)}async createMask(t,e){let r=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveBits"]),o=e*4*8,a=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:new TextEncoder().encode("octomil-secagg-mask")},r,Math.min(o,8160)),h=new Float32Array(e),u=new Float32Array(a);for(let l=0;l<e;l++)h[l]=u[l%u.length];return h}maskUpdate(t,e){let r={};for(let[o,a]of Object.entries(t)){if(!a)continue;let h=new Float32Array(a),u=e.get(o);if(u)for(let l=0;l<h.length;l++)h[l]=h[l]+(u[l]??0);r[o]=h}return r}unmask(t,e){let r={};for(let[o,a]of Object.entries(t)){if(!a)continue;let h=new Float32Array(a),u=e.get(o);if(u)for(let l=0;l<h.length;l++)h[l]=h[l]-(u[l]??0);r[o]=h}return r}},ur=2147483647;function fh(d,t,e){let r=1;for(d=d%e;t>0;)t%2===1&&(r=Number(BigInt(r)*BigInt(d)%BigInt(e))),t=Math.floor(t/2),d=Number(BigInt(d)*BigInt(d)%BigInt(e));return r}function OS(d,t){return fh(d,t-2,t)}function Pi(d,t,e){let r=[d%ur];for(let a=1;a<t;a++){let h=new Uint32Array(1);crypto.getRandomValues(h),r.push(h[0]%ur)}let o=[];for(let a=1;a<=e;a++){let h=0;for(let u=0;u<r.length;u++)h=Number((BigInt(h)+BigInt(r[u])*BigInt(fh(a,u,ur)))%BigInt(ur));o.push({x:a,y:h})}return o}function bi(d){let t=0,e=d.length;for(let r=0;r<e;r++){let o=1,a=1;for(let u=0;u<e;u++)r!==u&&(o=Number(BigInt(o)*BigInt(ur-d[u].x)%BigInt(ur)),a=Number(BigInt(a)*BigInt((d[r].x-d[u].x+ur)%ur)%BigInt(ur)));let h=Number(BigInt(o)*BigInt(OS(a,ur))%BigInt(ur));t=Number((BigInt(t)+BigInt(d[r].y)*BigInt(h))%BigInt(ur))}return t}var Yo=class extends Js{constructor(e){super();v(this,"threshold");this.threshold=e}splitSecret(e,r){return Pi(e,this.threshold,r)}reconstructSecret(e){if(e.length<this.threshold)throw new Pe("INVALID_INPUT",`Need at least ${this.threshold} shares, got ${e.length}.`);return bi(e.slice(0,this.threshold))}};function gh(d,t){let e=0;for(let h of Object.values(d))if(h)for(let u=0;u<h.length;u++)e+=h[u]*h[u];let r=Math.sqrt(e);if(r<=t)return d;let o=t/r,a={};for(let[h,u]of Object.entries(d)){if(!u)continue;let l=new Float32Array(u.length);for(let p=0;p<u.length;p++)l[p]=u[p]*o;a[h]=l}return a}function Mh(d,t,e,r){let o=e*Math.sqrt(2*Math.log(1.25/r))/t,a={};for(let[h,u]of Object.entries(d)){if(!u)continue;let l=new Float32Array(u.length);for(let p=0;p<u.length;p++)l[p]=u[p]+RS()*o;a[h]=l}return a}function RS(){let d,t;do d=Math.random(),t=Math.random();while(d===0);return Math.sqrt(-2*Math.log(d))*Math.cos(2*Math.PI*t)}function wh(d,t=8){let e=t===8?127:32767,r={};for(let[o,a]of Object.entries(d)){if(!a)continue;let h=0;for(let p=0;p<a.length;p++){let w=Math.abs(a[p]);w>h&&(h=w)}let u=h>0?h/e:1,l=t===8?new Int8Array(a.length):new Int16Array(a.length);for(let p=0;p<a.length;p++)l[p]=Math.round(a[p]/u);r[o]={data:l,scale:u,zeroPoint:0}}return r}function Th(d){let t={};for(let[e,r]of Object.entries(d)){if(!r)continue;let o=new Float32Array(r.data.length);for(let a=0;a<r.data.length;a++)o[a]=(r.data[a]-r.zeroPoint)*r.scale;t[e]=o}return t}var BS="octomil-gradients",Vr="gradients";var Zo=class{constructor(){v(this,"dbPromise",null)}openDb(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,e)=>{let r=indexedDB.open(BS,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(Vr)||o.createObjectStore(Vr,{keyPath:"roundId"}).createIndex("submitted","submitted",{unique:!1})},r.onsuccess=()=>t(r.result),r.onerror=()=>e(r.error)}),this.dbPromise)}async store(t){let e=await this.openDb();return new Promise((r,o)=>{let a=e.transaction(Vr,"readwrite");a.objectStore(Vr).put(t),a.oncomplete=()=>r(),a.onerror=()=>o(a.error)})}async get(t){let e=await this.openDb();return new Promise((r,o)=>{let h=e.transaction(Vr,"readonly").objectStore(Vr).get(t);h.onsuccess=()=>r(h.result??null),h.onerror=()=>o(h.error)})}async listPending(){let t=await this.openDb();return new Promise((e,r)=>{let h=t.transaction(Vr,"readonly").objectStore(Vr).index("submitted").getAll(IDBKeyRange.only(!1));h.onsuccess=()=>e(h.result),h.onerror=()=>r(h.error)})}async markSubmitted(t){let e=await this.get(t);e&&(e.submitted=!0,await this.store(e))}};var en=class{constructor(t){v(this,"serverUrl");v(this,"apiKey");v(this,"cacheTtlMs");v(this,"telemetry");v(this,"experimentsCache",null);this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.cacheTtlMs=t.cacheTtlMs??5*60*1e3,this.telemetry=t.telemetry}async getActiveExperiments(){if(this.experimentsCache&&Date.now()-this.experimentsCache.fetchedAt<this.cacheTtlMs)return this.experimentsCache.experiments;let t=`${this.serverUrl}/api/v1/experiments?status=active`,e={Accept:"application/json"};this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`);let r=await fetch(t,{headers:e});if(!r.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to fetch experiments: HTTP ${r.status}`);let o=await r.json();return this.experimentsCache={experiments:o.experiments,fetchedAt:Date.now()},o.experiments}async getExperimentConfig(t){let e=`${this.serverUrl}/api/v1/experiments/${encodeURIComponent(t)}`,r={Accept:"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`);let o=await fetch(e,{headers:r});if(!o.ok)throw new Pe("NETWORK_UNAVAILABLE",`Failed to fetch experiment: HTTP ${o.status}`);return await o.json()}getVariant(t,e){if(t.variants.length===0)return null;let r=NS(e+t.id),o=0;for(let a of t.variants)if(o+=a.trafficPercentage,r<o)return a;return t.variants[t.variants.length-1]??null}isEnrolled(t,e){return this.getVariant(t,e)!==null}async resolveModelExperiment(t,e){let r=await this.getActiveExperiments();for(let o of r){if(!o.variants.some(u=>u.modelId===t))continue;let h=this.getVariant(o,e);if(h)return{experiment:o,variant:h}}return null}async trackMetric(t,e,r,o){let a=`${this.serverUrl}/api/v1/experiments/${encodeURIComponent(t)}/metrics`,h={"Content-Type":"application/json"};this.apiKey&&(h.Authorization=`Bearer ${this.apiKey}`),await fetch(a,{method:"POST",headers:h,body:JSON.stringify({metric_name:e,value:r,device_id:o,timestamp:Date.now()})}),this.telemetry?.reportExperimentMetric(t,e,r)}clearCache(){this.experimentsCache=null}};function NS(d){let t=5381;for(let e=0;e<d.length;e++)t=(t<<5)+t+d.charCodeAt(e)|0;return Math.abs(t)%100}var tn=(o=>(o.NotCached="not_cached",o.Downloading="downloading",o.Ready="ready",o.Error="error",o))(tn||{});var rn=(o=>(o.Flagship="flagship",o.High="high",o.Mid="mid",o.Low="low",o))(rn||{});var sn=(o=>(o.Stop="stop",o.ToolCalls="tool_calls",o.Length="length",o.ContentFilter="content_filter",o))(sn||{});var on=(o=>(o.Stable="stable",o.Beta="beta",o.Experimental="experimental",o.Compatibility="compatibility",o))(on||{});function jS(d){return d.error==null}return Jh(VS);})();
1
+ "use strict";var __Octomil_ns=(()=>{var eO=Object.create;var Ss=Object.defineProperty;var tO=Object.getOwnPropertyDescriptor;var rO=Object.getOwnPropertyNames;var nO=Object.getPrototypeOf,sO=Object.prototype.hasOwnProperty;var ug=e=>{throw TypeError(e)};var aO=(e,t,r)=>t in e?Ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var $r=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var oO=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Au=(e,t)=>{for(var r in t)Ss(e,r,{get:t[r],enumerable:!0})},dg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rO(t))!sO.call(e,s)&&s!==r&&Ss(e,s,{get:()=>t[s],enumerable:!(n=tO(t,s))||n.enumerable});return e};var iO=(e,t,r)=>(r=e!=null?eO(nO(e)):{},dg(t||!e||!e.__esModule?Ss(r,"default",{value:e,enumerable:!0}):r,e)),lO=e=>dg(Ss({},"__esModule",{value:!0}),e);var w=(e,t,r)=>aO(e,typeof t!="symbol"?t+"":t,r),pg=(e,t,r)=>t.has(e)||ug("Cannot "+r);var ut=(e,t,r)=>(pg(e,t,"read from private field"),r?r.call(e):t.get(e)),so=(e,t,r)=>t.has(e)?ug("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ao=(e,t,r,n)=>(pg(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var yg=oO((C3,wg)=>{wg.exports=globalThis.ort});var Id={};Au(Id,{InferenceSession:()=>md,TRACE:()=>Oo,TRACE_EVENT_BEGIN:()=>Ir,TRACE_EVENT_END:()=>Pr,TRACE_FUNC_BEGIN:()=>Zr,TRACE_FUNC_END:()=>en,Tensor:()=>Gt,default:()=>eL,env:()=>De,registerBackend:()=>Yr});async function Ag(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(d,h)=>{d.startsWith("./")&&(d=d.substring(2)),(t.Uc||(t.Uc=new Map)).set(d,h)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let d=h=>(..._)=>{let g=er;return _=h(..._),er!=g?new Promise((b,k)=>{uu={resolve:b,reject:k}}):_};(()=>{for(let h of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[h]=d(t[h])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,i,l=(d,h)=>{throw h},c=Vt.url,u="";if(r||n){try{u=new URL(".",c).href}catch{}n&&(i=d=>{var h=new XMLHttpRequest;return h.open("GET",d,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),o=async d=>{if(O(d))return new Promise((_,g)=>{var b=new XMLHttpRequest;b.open("GET",d,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?_(b.response):g(b.status)},b.onerror=g,b.send(null)});var h=await fetch(d,{credentials:"same-origin"});if(h.ok)return h.arrayBuffer();throw Error(h.status+" : "+h.url)}}var p,f,m,y,v,x,M=console.log.bind(console),T=console.error.bind(console),A=M,C=T,S=!1,O=d=>d.startsWith("file://");function E(){Tr.buffer!=V.buffer&&fe()}if(s){let d=function(h){try{var _=h.data,g=_.Oc;if(g==="load"){let b=[];self.onmessage=k=>b.push(k),x=()=>{postMessage({Oc:"loaded"});for(let k of b)d(k);self.onmessage=d};for(let k of _.de)t[k]&&!t[k].proxy||(t[k]=(...P)=>{postMessage({Oc:"callHandler",ce:k,args:P})},k=="print"&&(A=t[k]),k=="printErr"&&(C=t[k]));Tr=_.je,fe(),f=_.ke,nt(),no()}else if(g==="run"){(function(b){var k=(E(),R)[b+52>>>2>>>0];b=(E(),R)[b+56>>>2>>>0],v_(k,k-b),ne(k)})(_.Nc),Mu(_.Nc,0,0,1,0,0),im(),iu(_.Nc),$||(r_(),$=!0);try{eP(_.he,_.Wc)}catch(b){if(b!="unwind")throw b}}else _.target!=="setimmediate"&&(g==="checkMailbox"?$&&Qa():g&&(C(`worker: received unknown command ${g}`),C(_)))}catch(b){throw m_(),b}};var K=d,$=!1;self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=d}var V,Q,G,W,D,R,re,ie,F,N,z,Y=!1;function fe(){var d=Tr.buffer;t.HEAP8=V=new Int8Array(d),G=new Int16Array(d),t.HEAPU8=Q=new Uint8Array(d),W=new Uint16Array(d),t.HEAP32=D=new Int32Array(d),t.HEAPU32=R=new Uint32Array(d),re=new Float32Array(d),ie=new Float64Array(d),F=new BigInt64Array(d),N=new BigUint64Array(d)}function H(){Y=!0,s?x():hr._b()}function Ne(d){throw C(d="Aborted("+d+")"),S=!0,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),v?.(d),d}function Xe(){return{a:{f:tP,J:rP,k:nP,p:sP,l:aP,ta:oP,b:iP,ca:lP,Ka:hm,s:cP,da:gm,_a:wm,Ga:ym,Ia:vm,$a:bm,Ya:Mm,Ra:xm,Xa:Tm,pa:Em,Ha:km,Yb:Cm,Za:Am,Fa:Sm,eb:uP,Da:pP,Tb:hP,Rb:mP,Ca:gP,M:wP,I:yP,Sb:vP,ka:CP,Ub:AP,Ua:SP,Wb:PP,La:RP,Pb:OP,la:LP,Ta:iu,bb:FP,U:UP,n:jP,c:au,sb:qP,w:WP,L:HP,z:KP,j:QP,o:Dm,tb:JP,G:XP,T:YP,h:ZP,u:e2,m:t2,i:r2,Oa:n2,Pa:s2,Qa:a2,Ma:$m,Na:Vm,Qb:Gm,fb:i2,db:u2,Y:d2,rb:p2,ma:h2,cb:l2,gb:f2,ab:m2,Xb:_2,N:o2,hb:g2,X:w2,Vb:y2,ob:A2,C:S2,sa:I2,ra:P2,qb:R2,W:O2,v:L2,nb:F2,mb:N2,lb:D2,pb:B2,kb:U2,jb:z2,ib:$2,Va:Qm,Wa:Jm,Ja:eu,ea:Xm,oa:Ym,Sa:Zm,na:e_,Db:XR,xa:GR,Eb:JR,ya:VR,F:RR,e:yR,r:gR,x:_R,D:SR,Ib:UR,ba:DR,B:bR,za:zR,$:jR,ha:BR,Fb:KR,Gb:HR,Ba:OR,Aa:NR,Jb:LR,wa:QR,aa:$R,d:vR,A:MR,q:wR,Cb:YR,t:TR,y:IR,H:xR,E:ER,K:PR,S:qR,ja:AR,_:WR,Kb:CR,Lb:kR,P:FR,g:G2,a:Tr,Ob:An,Hb:j2,ia:q2,O:W2,qa:H2,Mb:K2,Q:Q2,zb:J2,Ab:X2,ua:Y2,fa:Z2,R:eR,Ea:tR,va:rR,Z:nR,xb:sR,Zb:aR,V:oR,Bb:iR,ub:lR,vb:uR,wb:dR,ga:pR,yb:hR,Nb:fR}}}async function nt(){function d(g,b){var k=hr=g.exports;g={};for(let[P,L]of Object.entries(k))typeof L=="function"?(k=NP(L),g[P]=k):g[P]=L;return hr=g,hr=function(){var P=hr,L=X=>ve=>X(ve)>>>0,j=X=>()=>X()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=j(P.Cc),P.Ec=L(P.Ec),P.rd=(X=>(ve,xe)=>X(ve,xe)>>>0)(P.rd),P.wd=L(P.wd),P.xd=j(P.xd),P.Bd=L(P.Bd),P}(),am.push(hr.id),t_=(g=hr).$b,r_=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,_u=t._OrtGetWebGpuDevice=g.Bc,to=g.Cc,$t=t._free=g.Dc,On=t._malloc=g.Ec,n_=t._wgpuBufferRelease=g.Fc,s_=t._wgpuCreateInstance=g.Gc,a_=g.Hc,o_=g.Ic,i_=g.Jc,l_=g.Kc,c_=g.Lc,u_=g.Pc,d_=g.Zc,p_=g._c,h_=g.$c,gu=g.bd,wu=g.cd,yu=g.dd,vu=g.ed,Cs=g.fd,bu=g.gd,f_=g.hd,Mu=g.kd,m_=g.ld,__=g.md,g_=g.nd,xu=g.od,w_=g.pd,y_=g.qd,Tu=g.rd,he=g.sd,As=g.td,v_=g.ud,ne=g.vd,ro=g.wd,se=g.xd,b_=g.yd,Eu=g.zd,M_=g.Ad,x_=g.Bd,T_=g.Cd,ku=g.Dd,E_=g.Ed,k_=g.Fd,C_=g.Gd,A_=g.Hd,S_=g.Id,I_=g.Jd,P_=g.Kd,R_=g.Ld,O_=g.Md,L_=g.Nd,F_=g.Od,N_=g.Pd,D_=g.Qd,B_=g.Rd,U_=g.Td,z_=g.Ud,$_=g.Vd,V_=g.Wd,G_=g.Yd,j_=g.Zd,q_=g._d,W_=g.$d,H_=g.ae,K_=g.be,Q_=g.pe,J_=g.qe,X_=g.re,Y_=g.se,Z_=g.te,eg=g.ue,tg=g.ve,rg=g.we,ng=g.xe,sg=g.ye,ag=g.ze,og=g.Xe,ig=g.Ye,lg=g.Ze,cg=g._e,f=b,hr}var h,_=Xe();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(_,(b,k)=>{g(d(b,k))})}):s?d(new WebAssembly.Instance(f,Xe()),f):(z??(z=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",Vt.url).href),h=await async function(g){var b=z;if(!p&&!O(b))try{var k=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(k,g)}catch(P){C(`wasm streaming compile failed: ${P}`),C("falling back to ArrayBuffer instantiation")}return async function(P,L){try{var j=await async function(X){if(!p)try{var ve=await o(X);return new Uint8Array(ve)}catch{}if(X==z&&p)X=new Uint8Array(p);else{if(!i)throw"both async and sync fetching of the wasm failed";X=i(X)}return X}(P);return await WebAssembly.instantiate(j,L)}catch(X){C(`failed to asynchronously prepare wasm: ${X}`),Ne(X)}}(b,g)}(_),d(h.instance,h.module))}class qe{constructor(h){w(this,"name","ExitStatus");this.message=`Program terminated with exit(${h})`,this.status=h}}var gt=d=>{d.terminate(),d.onmessage=()=>{}},Pe=[],ye=0,We=null,Yt=d=>{xr.length==0&&(cm(),lm(xr[0]));var h=xr.pop();if(!h)return 6;Ts.push(h),Br[d.Nc]=h,h.Nc=d.Nc;var _={Oc:"run",he:d.ge,Wc:d.Wc,Nc:d.Nc};return h.postMessage(_,d.Yc),0},ke=0,Ie=(d,h,..._)=>{var g,b=16*_.length,k=se(),P=ro(b),L=P>>>3;for(g of _)typeof g=="bigint"?((E(),F)[L++>>>0]=1n,(E(),F)[L++>>>0]=g):((E(),F)[L++>>>0]=0n,(E(),ie)[L++>>>0]=g);return d=__(d,0,b,P,h),ne(k),d};function An(d){if(s)return Ie(0,1,d);if(m=d,!(0<ke)){for(var h of Ts)gt(h);for(h of xr)gt(h);xr=[],Ts=[],Br={},S=!0}l(0,new qe(d))}function xs(d){if(s)return Ie(1,0,d);eu(d)}var eu=d=>{if(m=d,s)throw xs(d),"unwind";An(d)},xr=[],Ts=[],am=[],Br={},om=d=>{var h=d.Nc;delete Br[h],xr.push(d),Ts.splice(Ts.indexOf(d),1),d.Nc=0,g_(h)};function im(){am.forEach(d=>d())}var lm=d=>new Promise(h=>{d.onmessage=b=>{var k=b.data;if(b=k.Oc,k.Vc&&k.Vc!=to()){var P=Br[k.Vc];P?P.postMessage(k,k.Yc):C(`Internal error! Worker sent a message "${b}" to target pthread ${k.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?Qa():b==="spawnThread"?Yt(k):b==="cleanupThread"?yt(()=>{om(Br[k.ie])}):b==="loaded"?(d.loaded=!0,h(d)):k.target==="setimmediate"?d.postMessage(k):b==="uncaughtException"?d.onerror(k.error):b==="callHandler"?t[k.ce](...k.args):b&&C(`worker sent an unknown command ${b}`)},d.onerror=b=>{throw C(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var _,g=[];for(_ of[])t.propertyIsEnumerable(_)&&g.push(_);d.postMessage({Oc:"load",de:g,je:Tr,ke:f})});function cm(){var d=new Worker((()=>{let h=URL;return Vt.url>"file:"&&Vt.url<"file;"?new h("ort.webgpu.bundle.min.mjs",Vt.url):new URL(Vt.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});xr.push(d)}var Tr,eP=(d,h)=>{ke=0,d=ku(d,h),0<ke?m=d:xu(d)},Ha=[],Ka=0,wt=d=>-9007199254740992>d||9007199254740992<d?NaN:Number(d);function tP(d){var h=new tu(d>>>=0);return(E(),V)[h.Qc+12>>>0]==0&&(um(h,!0),Ka--),dm(h,!1),Ha.push(h),x_(d)}var Sn=0,rP=()=>{he(0,0);var d=Ha.pop();b_(d.Xc),Sn=0};function um(d,h){h=h?1:0,(E(),V)[d.Qc+12>>>0]=h}function dm(d,h){h=h?1:0,(E(),V)[d.Qc+13>>>0]=h}class tu{constructor(h){this.Xc=h,this.Qc=h-24}}var ru=d=>{var h=Sn;if(!h)return As(0),0;var _=new tu(h);(E(),R)[_.Qc+16>>>2>>>0]=h;var g=(E(),R)[_.Qc+4>>>2>>>0];if(!g)return As(0),h;for(var b of d){if(b===0||b===g)break;if(M_(b,g,_.Qc+16))return As(b),h}return As(g),h};function nP(){return ru([])}function sP(d){return ru([d>>>0])}function aP(d,h,_,g){return ru([d>>>0,h>>>0,_>>>0,g>>>0])}var oP=()=>{var d=Ha.pop();d||Ne("no exception to throw");var h=d.Xc;throw(E(),V)[d.Qc+13>>>0]==0&&(Ha.push(d),dm(d,!0),um(d,!1),Ka++),Eu(h),Sn=h};function iP(d,h,_){var g=new tu(d>>>=0);throw h>>>=0,_>>>=0,(E(),R)[g.Qc+16>>>2>>>0]=0,(E(),R)[g.Qc+4>>>2>>>0]=h,(E(),R)[g.Qc+8>>>2>>>0]=_,Eu(d),Ka++,Sn=d}var lP=()=>Ka;function pm(d,h,_,g){return s?Ie(2,1,d,h,_,g):hm(d,h,_,g)}function hm(d,h,_,g){if(d>>>=0,h>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return s&&b.length===0?pm(d,h,_,g):(d={ge:_,Nc:d,Wc:g,Yc:b},s?(d.Oc="spawnThread",postMessage(d,b),0):Yt(d))}function cP(d){throw Sn||(Sn=d>>>0),Sn}var fm=globalThis.TextDecoder&&new TextDecoder,mm=(d,h,_,g)=>{if(_=h+_,g)return _;for(;d[h]&&!(h>=_);)++h;return h},_m=(d,h=0,_,g)=>{if(16<(_=mm(d,h>>>=0,_,g))-h&&d.buffer&&fm)return fm.decode(d.buffer instanceof ArrayBuffer?d.subarray(h,_):d.slice(h,_));for(g="";h<_;){var b=d[h++];if(128&b){var k=63&d[h++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|k);else{var P=63&d[h++];65536>(b=(240&b)==224?(15&b)<<12|k<<6|P:(7&b)<<18|k<<12|P<<6|63&d[h++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},In=(d,h,_)=>(d>>>=0)?_m((E(),Q),d,h,_):"";function gm(d,h,_){return s?Ie(3,1,d,h,_):0}function wm(d,h){if(s)return Ie(4,1,d,h)}function ym(d,h){if(s)return Ie(5,1,d,h)}function vm(d,h,_){if(s)return Ie(6,1,d,h,_)}function bm(d,h,_){return s?Ie(7,1,d,h,_):0}function Mm(d,h){if(s)return Ie(8,1,d,h)}function xm(d,h,_){if(s)return Ie(9,1,d,h,_)}function Tm(d,h,_,g){if(s)return Ie(10,1,d,h,_,g)}function Em(d,h,_,g){if(s)return Ie(11,1,d,h,_,g)}function km(d,h,_,g){if(s)return Ie(12,1,d,h,_,g)}function Cm(d){if(s)return Ie(13,1,d)}function Am(d,h){if(s)return Ie(14,1,d,h)}function Sm(d,h,_){if(s)return Ie(15,1,d,h,_)}var uP=()=>Ne(""),Zt=d=>{d>>>=0;for(var h="";;){var _=(E(),Q)[d++>>>0];if(!_)return h;h+=String.fromCharCode(_)}},nu={},su={},dP={},Pn=class extends Error{constructor(d){super(d),this.name="BindingError"}};function lr(d,h,_={}){return function(g,b,k={}){var P=b.name;if(!g)throw new Pn(`type "${P}" must have a positive integer typeid pointer`);if(su.hasOwnProperty(g)){if(k.ee)return;throw new Pn(`Cannot register type '${P}' twice`)}su[g]=b,delete dP[g],nu.hasOwnProperty(g)&&(b=nu[g],delete nu[g],b.forEach(L=>L()))}(d,h,_)}var Im=(d,h,_)=>{switch(h){case 1:return _?g=>(E(),V)[g>>>0]:g=>(E(),Q)[g>>>0];case 2:return _?g=>(E(),G)[g>>>1>>>0]:g=>(E(),W)[g>>>1>>>0];case 4:return _?g=>(E(),D)[g>>>2>>>0]:g=>(E(),R)[g>>>2>>>0];case 8:return _?g=>(E(),F)[g>>>3>>>0]:g=>(E(),N)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${h}): ${d}`)}};function pP(d,h,_,g,b){d>>>=0,_>>>=0,h=Zt(h>>>0);let k=P=>P;if(g=g===0n){let P=8*_;k=L=>BigInt.asUintN(P,L),b=k(b)}lr(d,{name:h,Mc:k,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:Im(h,_,!g),Tc:null})}function hP(d,h,_,g){lr(d>>>=0,{name:h=Zt(h>>>0),Mc:function(b){return!!b},Sc:function(b,k){return k?_:g},Rc:function(b){return this.Mc((E(),Q)[b>>>0])},Tc:null})}var Pm=[],Ur=[0,1,,1,null,1,!0,1,!1,1];function au(d){9<(d>>>=0)&&--Ur[d+1]==0&&(Ur[d]=void 0,Pm.push(d))}var It=d=>{if(!d)throw new Pn(`Cannot use deleted val. handle = ${d}`);return Ur[d]},zt=d=>{switch(d){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=Pm.pop()||Ur.length;return Ur[h]=d,Ur[h+1]=1,h}};function ou(d){return this.Mc((E(),R)[d>>>2>>>0])}var fP={name:"emscripten::val",Mc:d=>{var h=It(d);return au(d),h},Sc:(d,h)=>zt(h),Rc:ou,Tc:null};function mP(d){return lr(d>>>0,fP)}var _P=(d,h)=>{switch(h){case 4:return function(_){return this.Mc((E(),re)[_>>>2>>>0])};case 8:return function(_){return this.Mc((E(),ie)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${d}`)}};function gP(d,h,_){_>>>=0,lr(d>>>=0,{name:h=Zt(h>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:_P(h,_),Tc:null})}function wP(d,h,_,g,b){d>>>=0,_>>>=0,h=Zt(h>>>0);let k=L=>L;if(g===0){var P=32-8*_;k=L=>L<<P>>>P,b=k(b)}lr(d,{name:h,Mc:k,Sc:(L,j)=>j,Rc:Im(h,_,g!==0),Tc:null})}function yP(d,h,_){function g(k){var P=(E(),R)[k>>>2>>>0];return k=(E(),R)[k+4>>>2>>>0],new b((E(),V).buffer,k,P)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];lr(d>>>=0,{name:_=Zt(_>>>0),Mc:g,Rc:g},{ee:!0})}var cr=(d,h,_)=>{var g=(E(),Q);if(h>>>=0,0<_){var b=h;_=h+_-1;for(var k=0;k<d.length;++k){var P=d.codePointAt(k);if(127>=P){if(h>=_)break;g[h++>>>0]=P}else if(2047>=P){if(h+1>=_)break;g[h++>>>0]=192|P>>6,g[h++>>>0]=128|63&P}else if(65535>=P){if(h+2>=_)break;g[h++>>>0]=224|P>>12,g[h++>>>0]=128|P>>6&63,g[h++>>>0]=128|63&P}else{if(h+3>=_)break;g[h++>>>0]=240|P>>18,g[h++>>>0]=128|P>>12&63,g[h++>>>0]=128|P>>6&63,g[h++>>>0]=128|63&P,k++}}g[h>>>0]=0,d=h-b}else d=0;return d},ur=d=>{for(var h=0,_=0;_<d.length;++_){var g=d.charCodeAt(_);127>=g?h++:2047>=g?h+=2:55296<=g&&57343>=g?(h+=4,++_):h+=3}return h};function vP(d,h){lr(d>>>=0,{name:h=Zt(h>>>0),Mc(_){var g=(E(),R)[_>>>2>>>0];return g=In(_+4,g,!0),$t(_),g},Sc(_,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Pn("Cannot pass non-string to std::string");var k=b?ur(g):g.length,P=On(4+k+1),L=P+4;return(E(),R)[P>>>2>>>0]=k,b?cr(g,L,k+1):(E(),Q).set(g,L>>>0),_!==null&&_.push($t,P),P},Rc:ou,Tc(_){$t(_)}})}var Rm=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,bP=(d,h,_)=>{if(d>>>=1,16<(h=mm((E(),W),d,h/2,_))-d&&Rm)return Rm.decode((E(),W).slice(d,h));for(_="";d<h;++d){var g=(E(),W)[d>>>0];_+=String.fromCharCode(g)}return _},MP=(d,h,_)=>{if(_??(_=2147483647),2>_)return 0;var g=h;_=(_-=2)<2*d.length?_/2:d.length;for(var b=0;b<_;++b){var k=d.charCodeAt(b);(E(),G)[h>>>1>>>0]=k,h+=2}return(E(),G)[h>>>1>>>0]=0,h-g},xP=d=>2*d.length,TP=(d,h,_)=>{var g="";d>>>=2;for(var b=0;!(b>=h/4);b++){var k=(E(),R)[d+b>>>0];if(!k&&!_)break;g+=String.fromCodePoint(k)}return g},EP=(d,h,_)=>{if(h>>>=0,_??(_=2147483647),4>_)return 0;var g=h;_=g+_-4;for(var b=0;b<d.length;++b){var k=d.codePointAt(b);if(65535<k&&b++,(E(),D)[h>>>2>>>0]=k,(h+=4)+4>_)break}return(E(),D)[h>>>2>>>0]=0,h-g},kP=d=>{for(var h=0,_=0;_<d.length;++_)65535<d.codePointAt(_)&&_++,h+=4;return h};function CP(d,h,_){if(d>>>=0,h>>>=0,_=Zt(_>>>=0),h===2)var g=bP,b=MP,k=xP;else g=TP,b=EP,k=kP;lr(d,{name:_,Mc:P=>{var L=(E(),R)[P>>>2>>>0];return L=g(P+4,L*h,!0),$t(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Pn(`Cannot pass non-string to C++ string type ${_}`);var j=k(L),X=On(4+j+h);return(E(),R)[X>>>2>>>0]=j/h,b(L,X+4,j+h),P!==null&&P.push($t,X),X},Rc:ou,Tc(P){$t(P)}})}function AP(d,h){lr(d>>>=0,{fe:!0,name:h=Zt(h>>>0),Mc:()=>{},Sc:()=>{}})}function SP(d){Mu(d>>>0,!n,1,!r,131072,!1),im()}var yt=d=>{if(!S)try{if(d(),!(0<ke))try{s?to()&&xu(m):eu(m)}catch(h){h instanceof qe||h=="unwind"||l(0,h)}}catch(h){h instanceof qe||h=="unwind"||l(0,h)}},IP=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function iu(d){d>>>=0,IP||(Atomics.waitAsync((E(),D),d>>>2,d).value.then(Qa),d+=128,Atomics.store((E(),D),d>>>2,1))}var Qa=()=>yt(()=>{var d=to();d&&(iu(d),y_())});function PP(d,h){(d>>>=0)==h>>>0?setTimeout(Qa):s?postMessage({Vc:d,Oc:"checkMailbox"}):(d=Br[d])&&d.postMessage({Oc:"checkMailbox"})}var lu=[];function RP(d,h,_,g,b){for(h>>>=0,b>>>=0,lu.length=0,_=b>>>3,g=b+g>>>3;_<g;){var k;k=(E(),F)[_++>>>0]?(E(),F)[_++>>>0]:(E(),ie)[_++>>>0],lu.push(k)}return(h?Cu[h]:mR[d])(...lu)}var OP=()=>{ke=0};function LP(d){d>>>=0,s?postMessage({Oc:"cleanupThread",ie:d}):om(Br[d])}function FP(d){}var Ja=d=>{try{d()}catch(h){Ne(h)}};function NP(d){var h=(..._)=>{Xa.push(d);try{return d(..._)}finally{S||(Xa.pop(),er&&Er===1&&Xa.length===0&&(Er=0,ke+=1,Ja(ig),typeof Fibers<"u"&&Fibers.De()))}};return Fm.set(d,h),h}var Er=0,er=null,Om=0,Xa=[],cu=new Map,Lm=new Map,Fm=new Map,DP=0,uu=null,BP=[],Nm=d=>function(h){if(!S){if(Er===0){var _=!1,g=!1;h((b=0)=>{if(!S&&(Om=b,_=!0,g)){Er=2,Ja(()=>lg(er)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var k=function(){var j=(E(),D)[er+8>>>2>>>0];return j=Lm.get(j),j=Fm.get(j),--ke,j()}()}catch(j){k=j,b=!0}var P=!1;if(!er){var L=uu;L&&(uu=null,(b?L.reject:L.resolve)(k),P=!0)}if(b&&!P)throw k}}),g=!0,_||(Er=1,er=function(){var b=On(65548),k=b+12;if((E(),R)[b>>>2>>>0]=k,(E(),R)[b+4>>>2>>>0]=k+65536,k=Xa[0],!cu.has(k)){var P=DP++;cu.set(k,P),Lm.set(P,k)}return k=cu.get(k),(E(),D)[b+8>>>2>>>0]=k,b}(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ja(()=>og(er)))}else Er===2?(Er=0,Ja(cg),$t(er),er=null,BP.forEach(yt)):Ne(`invalid state: ${Er}`);return Om}}(h=>{d().then(h)});function UP(d){return d>>>=0,Nm(async()=>{var h=await It(d);return zt(h)})}var du=[],zP=d=>{var h=du.length;return du.push(d),h},$P=(d,h)=>{for(var _=Array(d),g=0;g<d;++g){var b=g,k=(E(),R)[h+4*g>>>2>>>0],P=su[k];if(P===void 0)throw d=`parameter ${g}`,k=t_(k),h=Zt(k),$t(k),new Pn(`${d} has unknown type ${h}`);_[b]=P}return _},VP=(d,h,_)=>{var g=[];return d=d(g,_),g.length&&((E(),R)[h>>>2>>>0]=zt(g)),d},GP={},Ya=d=>{var h=GP[d];return h===void 0?Zt(d):h};function jP(d,h,_){var[g,...b]=$P(d,h>>>0);h=g.Sc.bind(g);var k=b.map(j=>j.Rc.bind(j));d--;var P={toValue:It};switch(d=k.map((j,X)=>{var ve=`argFromPtr${X}`;return P[ve]=j,`${ve}(args${X?"+"+8*X:""})`}),_){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ya,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${d})`,g.fe||(P.toReturnWire=h,P.emval_returnValue=VP,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) {
2
+ ${L}
3
+ }`,_=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${b.map(j=>j.name)}) => ${g.name}>`,zP(Object.defineProperty(_,"name",{value:L}))}function qP(d,h){return h>>>=0,(d=It(d>>>0))==It(h)}function WP(d){return(d>>>=0)?(d=Ya(d),zt(globalThis[d])):zt(globalThis)}function HP(d){return d=Ya(d>>>0),zt(t[d])}function KP(d,h){return h>>>=0,d=It(d>>>0),h=It(h),zt(d[h])}function QP(d){9<(d>>>=0)&&(Ur[d+1]+=1)}function Dm(d,h,_,g,b){return du[d>>>0](h>>>0,_>>>0,g>>>0,b>>>0)}function JP(d,h,_,g,b){return Dm(d>>>0,h>>>0,_>>>0,g>>>0,b>>>0)}function XP(){return zt([])}function YP(d){d=It(d>>>0);for(var h=Array(d.length),_=0;_<d.length;_++)h[_]=d[_];return zt(h)}function ZP(d){return zt(Ya(d>>>0))}function e2(){return zt({})}function t2(d){for(var h=It(d>>>=0);h.length;){var _=h.pop();h.pop()(_)}au(d)}function r2(d,h,_){h>>>=0,_>>>=0,d=It(d>>>0),h=It(h),_=It(_),d[h]=_}function n2(d,h){d=wt(d),h>>>=0,d=new Date(1e3*d),(E(),D)[h>>>2>>>0]=d.getUTCSeconds(),(E(),D)[h+4>>>2>>>0]=d.getUTCMinutes(),(E(),D)[h+8>>>2>>>0]=d.getUTCHours(),(E(),D)[h+12>>>2>>>0]=d.getUTCDate(),(E(),D)[h+16>>>2>>>0]=d.getUTCMonth(),(E(),D)[h+20>>>2>>>0]=d.getUTCFullYear()-1900,(E(),D)[h+24>>>2>>>0]=d.getUTCDay(),d=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(E(),D)[h+28>>>2>>>0]=d}var Bm=d=>d%4==0&&(d%100!=0||d%400==0),Um=[0,31,60,91,121,152,182,213,244,274,305,335],zm=[0,31,59,90,120,151,181,212,243,273,304,334];function s2(d,h){d=wt(d),h>>>=0,d=new Date(1e3*d),(E(),D)[h>>>2>>>0]=d.getSeconds(),(E(),D)[h+4>>>2>>>0]=d.getMinutes(),(E(),D)[h+8>>>2>>>0]=d.getHours(),(E(),D)[h+12>>>2>>>0]=d.getDate(),(E(),D)[h+16>>>2>>>0]=d.getMonth(),(E(),D)[h+20>>>2>>>0]=d.getFullYear()-1900,(E(),D)[h+24>>>2>>>0]=d.getDay();var _=(Bm(d.getFullYear())?Um:zm)[d.getMonth()]+d.getDate()-1|0;(E(),D)[h+28>>>2>>>0]=_,(E(),D)[h+36>>>2>>>0]=-60*d.getTimezoneOffset(),_=new Date(d.getFullYear(),6,1).getTimezoneOffset();var g=new Date(d.getFullYear(),0,1).getTimezoneOffset();d=0|(_!=g&&d.getTimezoneOffset()==Math.min(g,_)),(E(),D)[h+32>>>2>>>0]=d}function a2(d){d>>>=0;var h=new Date((E(),D)[d+20>>>2>>>0]+1900,(E(),D)[d+16>>>2>>>0],(E(),D)[d+12>>>2>>>0],(E(),D)[d+8>>>2>>>0],(E(),D)[d+4>>>2>>>0],(E(),D)[d>>>2>>>0],0),_=(E(),D)[d+32>>>2>>>0],g=h.getTimezoneOffset(),b=new Date(h.getFullYear(),6,1).getTimezoneOffset(),k=new Date(h.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(k,b);return 0>_?(E(),D)[d+32>>>2>>>0]=+(b!=k&&P==g):0<_!=(P==g)&&(b=Math.max(k,b),h.setTime(h.getTime()+6e4*((0<_?P:b)-g))),(E(),D)[d+24>>>2>>>0]=h.getDay(),_=(Bm(h.getFullYear())?Um:zm)[h.getMonth()]+h.getDate()-1|0,(E(),D)[d+28>>>2>>>0]=_,(E(),D)[d>>>2>>>0]=h.getSeconds(),(E(),D)[d+4>>>2>>>0]=h.getMinutes(),(E(),D)[d+8>>>2>>>0]=h.getHours(),(E(),D)[d+12>>>2>>>0]=h.getDate(),(E(),D)[d+16>>>2>>>0]=h.getMonth(),(E(),D)[d+20>>>2>>>0]=h.getYear(),d=h.getTime(),BigInt(isNaN(d)?-1:d/1e3)}function $m(d,h,_,g,b,k,P){return s?Ie(16,1,d,h,_,g,b,k,P):-52}function Vm(d,h,_,g,b,k){if(s)return Ie(17,1,d,h,_,g,b,k)}var Es={},o2=()=>performance.timeOrigin+performance.now();function Gm(d,h){if(s)return Ie(18,1,d,h);if(Es[d]&&(clearTimeout(Es[d].id),delete Es[d]),!h)return 0;var _=setTimeout(()=>{delete Es[d],yt(()=>w_(d,performance.timeOrigin+performance.now()))},h);return Es[d]={id:_,Ce:h},0}function i2(d,h,_,g){d>>>=0,h>>>=0,_>>>=0,g>>>=0;var b=new Date().getFullYear(),k=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var P=Math.max(k,b);(E(),R)[d>>>2>>>0]=60*P,(E(),D)[h>>>2>>>0]=+(k!=b),d=(h=L=>{var j=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(k),h=h(b),b<k?(cr(d,_,17),cr(h,g,17)):(cr(d,g,17),cr(h,_,17))}var l2=()=>Date.now(),c2=1;function u2(d,h,_){if(_>>>=0,!(0<=d&&3>=d))return 28;if(d===0)d=Date.now();else{if(!c2)return 52;d=performance.timeOrigin+performance.now()}return d=Math.round(1e6*d),(E(),F)[_>>>3>>>0]=BigInt(d),0}var pu=[],jm=(d,h)=>{pu.length=0;for(var _;_=(E(),Q)[d++>>>0];){var g=_!=105;h+=(g&=_!=112)&&h%8?4:0,pu.push(_==112?(E(),R)[h>>>2>>>0]:_==106?(E(),F)[h>>>3>>>0]:_==105?(E(),D)[h>>>2>>>0]:(E(),ie)[h>>>3>>>0]),h+=g?8:4}return pu};function d2(d,h,_){return d>>>=0,h=jm(h>>>0,_>>>0),Cu[d](...h)}function p2(d,h,_){return d>>>=0,h=jm(h>>>0,_>>>0),Cu[d](...h)}var h2=()=>{};function f2(d,h){return C(In(d>>>0,h>>>0))}var m2=()=>{throw ke+=1,"unwind"};function _2(){return 4294901760}var g2=()=>1,w2=()=>navigator.hardwareConcurrency;function y2(d){d>>>=0;var h=(E(),Q).length;if(d<=h||4294901760<d)return!1;for(var _=1;4>=_;_*=2){var g=h*(1+.2/_);g=Math.min(g,d+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(d,g)/65536))-Tr.buffer.byteLength+65535)/65536|0;try{Tr.grow(g),fe();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var tr=d=>{var h=ur(d)+1,_=ro(h);return cr(d,_,h),_},hu=(d,h)=>{(E(),R)[d>>>2>>>0]=h;var _=(E(),R)[d>>>2>>>0];(E(),R)[d+4>>>2>>>0]=(h-_)/4294967296},ks=d=>(E(),R)[d>>>2>>>0]+4294967296*(E(),D)[d+4>>>2>>>0],st=[],v2=(d,h)=>{st[d>>>0]=h},dr=[],Za=[],Rn=(d,h)=>{Za[d]=new Promise(_=>h.finally(()=>_(d)))},ee=d=>{if(d)return st[d>>>0]},b2=(d,h)=>{for(d=(E(),R)[d>>>2>>>0];d;d=(E(),R)[d>>>2>>>0])h[(E(),D)[d+4>>>2>>>0]](d)},eo=(d,h,_)=>{(E(),R)[d>>>2>>>0]=h,(E(),R)[d+4>>>2>>>0]=_},qm=d=>{var h=(E(),R)[d>>>2>>>0];return d=(E(),R)[d+4>>>2>>>0],In(h,d)},pr=d=>{var h=(E(),R)[d>>>2>>>0];return d=(E(),R)[d+4>>>2>>>0],h?In(h,d):d===0?"":void 0},M2=d=>{var h=pr(d+4),_=(_=(E(),R)[d+12>>>2>>>0])?ee(_):"auto";if(d+=16){var g=ee((E(),R)[d+4>>>2>>>0]),b=(E(),R)[d+16>>>2>>>0],k=(E(),R)[d+20>>>2>>>0];if(b){for(var P={},L=0;L<b;++L){var j=k+24*L;P[qm(j+4)]=(E(),ie)[j+16>>>3>>>0]}b=P}else b=void 0;d={module:g,constants:b,entryPoint:pr(d+8)}}else d=void 0;return{label:h,layout:_,compute:d}},Wm=(d,h)=>{function _(g,b){g=d[g],(E(),R)[h+b>>>2>>>0]=g}_("maxTextureDimension1D",4),_("maxTextureDimension2D",8),_("maxTextureDimension3D",12),_("maxTextureArrayLayers",16),_("maxBindGroups",20),_("maxBindGroupsPlusVertexBuffers",24),_("maxBindingsPerBindGroup",28),_("maxDynamicUniformBuffersPerPipelineLayout",32),_("maxDynamicStorageBuffersPerPipelineLayout",36),_("maxSampledTexturesPerShaderStage",40),_("maxSamplersPerShaderStage",44),_("maxStorageBuffersPerShaderStage",48),_("maxStorageTexturesPerShaderStage",52),_("maxUniformBuffersPerShaderStage",56),_("minUniformBufferOffsetAlignment",80),_("minStorageBufferOffsetAlignment",84),hu(h+64,d.maxUniformBufferBindingSize),hu(h+72,d.maxStorageBufferBindingSize),_("maxVertexBuffers",88),hu(h+96,d.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),d.Ae!==void 0&&_("maxImmediateSize",148)},x2=[,"validation","out-of-memory","internal"],T2=[,"compatibility","core"],Hm={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},E2=[,"low-power","high-performance"],k2=[,"occlusion","timestamp"],C2={undefined:1,unknown:1,destroyed:2};function A2(d,h,_,g,b,k){h=wt(h),_=wt(_),g>>>=0,b>>>=0,k>>>=0;var P=ee(d>>>0);if(d={},k){var L=(E(),R)[k+12>>>2>>>0];if(L){var j=(E(),R)[k+16>>>2>>>0];d.requiredFeatures=Array.from((E(),R).subarray(j>>>2>>>0,j+4*L>>>2>>>0),te=>Hm[te])}var X=(E(),R)[k+20>>>2>>>0];if(X){let te=function(vt,Ze,zr=!1){Ze=X+Ze,(Ze=(E(),R)[Ze>>>2>>>0])==4294967295||zr&&Ze==0||(Re[vt]=Ze)},Ye=function(vt,Ze){Ze=X+Ze;var zr=(E(),R)[Ze>>>2>>>0],ZR=(E(),R)[Ze+4>>>2>>>0];zr==4294967295&&ZR==4294967295||(Re[vt]=ks(Ze))};var ve=te,xe=Ye,Re={};te("maxTextureDimension1D",4),te("maxTextureDimension2D",8),te("maxTextureDimension3D",12),te("maxTextureArrayLayers",16),te("maxBindGroups",20),te("maxBindGroupsPlusVertexBuffers",24),te("maxDynamicUniformBuffersPerPipelineLayout",32),te("maxDynamicStorageBuffersPerPipelineLayout",36),te("maxSampledTexturesPerShaderStage",40),te("maxSamplersPerShaderStage",44),te("maxStorageBuffersPerShaderStage",48),te("maxStorageTexturesPerShaderStage",52),te("maxUniformBuffersPerShaderStage",56),te("minUniformBufferOffsetAlignment",80),te("minStorageBufferOffsetAlignment",84),Ye("maxUniformBufferBindingSize",64),Ye("maxStorageBufferBindingSize",72),te("maxVertexBuffers",88),Ye("maxBufferSize",96),te("maxVertexAttributes",104),te("maxVertexBufferArrayStride",108),te("maxInterStageShaderVariables",112),te("maxColorAttachments",116),te("maxColorAttachmentBytesPerSample",120),te("maxComputeWorkgroupStorageSize",124),te("maxComputeInvocationsPerWorkgroup",128),te("maxComputeWorkgroupSizeX",132),te("maxComputeWorkgroupSizeY",136),te("maxComputeWorkgroupSizeZ",140),te("maxComputeWorkgroupsPerDimension",144),te("maxImmediateSize",148,!0),d.requiredLimits=Re}(L=(E(),R)[k+24>>>2>>>0])&&(L={label:pr(L+4)},d.defaultQueue=L),d.label=pr(k+4)}ke+=1,Rn(h,P.requestDevice(d).then(te=>{--ke,yt(()=>{st[b>>>0]=te.queue,st[g>>>0]=te,Rn(_,te.lost.then(Ye=>{yt(()=>{te.onuncapturederror=()=>{};var vt=se(),Ze=tr(Ye.message);wu(_,C2[Ye.reason],Ze),ne(vt)})})),te.onuncapturederror=Ye=>{var vt=5;Ye.error instanceof GPUValidationError?vt=2:Ye.error instanceof GPUOutOfMemoryError?vt=3:Ye.error instanceof GPUInternalError&&(vt=4);var Ze=se();Ye=tr(Ye.error.message),f_(g,vt,Ye),ne(Ze)},"adapterInfo"in te||(te.adapterInfo=P.info),bu(h,1,g,0)})},te=>{--ke,yt(()=>{var Ye=se(),vt=tr(te.message);bu(h,3,g,vt),_&&wu(_,4,vt),ne(Ye)})}))}function S2(d){var h=ee(d>>>=0),_=dr[d];if(_){for(var g=0;g<_.length;++g)_[g]();delete dr[d]}h.destroy()}function I2(d,h,_){_>>>=0;var g=ee(d>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(h>>>0,_)}catch{return 0}var k=Tu(16,b.byteLength);return(E(),Q).set(new Uint8Array(b),k>>>0),dr[d].push(()=>$t(k)),k}function P2(d,h,_){_>>>=0;var g=ee(d>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(h>>>0,_)}catch{return 0}var k=Tu(16,b.byteLength);return(E(),Q).fill(0,k,b.byteLength),dr[d].push(()=>{new Uint8Array(b).set((E(),Q).subarray(k>>>0,k+b.byteLength>>>0)),$t(k)}),k}function R2(d,h,_,g,b){d>>>=0,h=wt(h),_=wt(_),b>>>=0;var k=ee(d);dr[d]=[],b==4294967295&&(b=void 0),ke+=1,Rn(h,k.mapAsync(_,g>>>0,b).then(()=>{--ke,yt(()=>{yu(h,1,0)})},P=>{--ke,yt(()=>{se();var L=tr(P.message);yu(h,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete dr[d]})}))}function O2(d){var h=ee(d>>>=0),_=dr[d];if(_){for(var g=0;g<_.length;++g)_[g]();delete dr[d],h.unmap()}}function L2(d){delete st[d>>>0]}function F2(d,h,_){d>>>=0,h>>>=0,_>>>=0;var g=!!(E(),R)[h+32>>>2>>>0];h={label:pr(h+4),usage:(E(),R)[h+16>>>2>>>0],size:ks(h+24),mappedAtCreation:g},d=ee(d);try{var b=d.createBuffer(h)}catch{return!1}return st[_>>>0]=b,g&&(dr[_]=[]),!0}function N2(d,h,_,g){d>>>=0,h=wt(h),g>>>=0,_=M2(_>>>0),d=ee(d),ke+=1,Rn(h,d.createComputePipelineAsync(_).then(b=>{--ke,yt(()=>{st[g>>>0]=b,gu(h,1,g,0)})},b=>{--ke,yt(()=>{var k=se(),P=tr(b.message);gu(h,b.reason==="validation"?3:b.reason==="internal"?4:0,g,P),ne(k)})}))}function D2(d,h,_){d>>>=0,h>>>=0,_>>>=0;var g=(E(),R)[h>>>2>>>0],b=(E(),D)[g+4>>>2>>>0];h={label:pr(h+4),code:""},b===2&&(h.code=qm(g+8)),d=ee(d).createShaderModule(h),st[_>>>0]=d}var B2=d=>{(d=ee(d)).onuncapturederror=null,d.destroy()};function U2(d,h){h=wt(h),d=ee(d>>>0),ke+=1,Rn(h,d.popErrorScope().then(_=>{--ke,yt(()=>{var g=5;_?_ instanceof GPUValidationError?g=2:_ instanceof GPUOutOfMemoryError?g=3:_ instanceof GPUInternalError&&(g=4):g=1;var b=se(),k=_?tr(_.message):0;vu(h,1,g,k),ne(b)})},_=>{--ke,yt(()=>{var g=se(),b=tr(_.message);vu(h,1,5,b),ne(g)})}))}function z2(d,h,_,g){if(h=wt(h),g>>>=0,_>>>=0){var b={featureLevel:T2[(E(),D)[_+4>>>2>>>0]],powerPreference:E2[(E(),D)[_+8>>>2>>>0]],forceFallbackAdapter:!!(E(),R)[_+12>>>2>>>0]};(d=(E(),R)[_>>>2>>>0])!==0&&(E(),b.Fe=!!(E(),R)[d+8>>>2>>>0])}"gpu"in navigator?(ke+=1,Rn(h,navigator.gpu.requestAdapter(b).then(k=>{--ke,yt(()=>{if(k)st[g>>>0]=k,Cs(h,1,g,0);else{var P=se(),L=tr("WebGPU not available on this browser (requestAdapter returned null)");Cs(h,3,g,L),ne(P)}})},k=>{--ke,yt(()=>{var P=se(),L=tr(k.message);Cs(h,4,g,L),ne(P)})}))):(b=se(),d=tr("WebGPU not available on this browser (navigator.gpu is not available)"),Cs(h,3,g,d),ne(b))}function $2(d,h,_){return d>>>=0,h>>>=0,_>>>=0,Nm(async()=>{var g=[];if(_){var b=(E(),D)[_>>>2>>>0];g.length=h+1,g[h]=new Promise(L=>setTimeout(L,b,0))}else g.length=h;for(var k=0;k<h;++k){var P=ks(d+8*k);if(!(P in Za))return P;g[k]=Za[P]}return g=await Promise.race(g),delete Za[g],g})}var fu,mu={},Km=()=>{if(!fu){var d,h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(d in mu)mu[d]===void 0?delete h[d]:h[d]=mu[d];var _=[];for(d in h)_.push(`${d}=${h[d]}`);fu=_}return fu};function Qm(d,h){if(s)return Ie(19,1,d,h);d>>>=0,h>>>=0;var _,g=0,b=0;for(_ of Km()){var k=h+g;(E(),R)[d+b>>>2>>>0]=k,g+=cr(_,k,1/0)+1,b+=4}return 0}function Jm(d,h){if(s)return Ie(20,1,d,h);d>>>=0,h>>>=0;var _=Km();for(var g of((E(),R)[d>>>2>>>0]=_.length,d=0,_))d+=ur(g)+1;return(E(),R)[h>>>2>>>0]=d,0}function Xm(d){return s?Ie(21,1,d):52}function Ym(d,h,_,g){return s?Ie(22,1,d,h,_,g):52}function Zm(d,h,_,g){return s?Ie(23,1,d,h,_,g):70}var V2=[null,[],[]];function e_(d,h,_,g){if(s)return Ie(24,1,d,h,_,g);h>>>=0,_>>>=0,g>>>=0;for(var b=0,k=0;k<_;k++){var P=(E(),R)[h>>>2>>>0],L=(E(),R)[h+4>>>2>>>0];h+=8;for(var j=0;j<L;j++){var X=d,ve=(E(),Q)[P+j>>>0],xe=V2[X];ve===0||ve===10?((X===1?A:C)(_m(xe)),xe.length=0):xe.push(ve)}b+=L}return(E(),R)[g>>>2>>>0]=b,0}function G2(d){return d>>>0}function j2(d,h){return Wm(ee(d>>>0).limits,h>>>0),1}function q2(d,h){return ee(d>>>0).features.has(Hm[h])}function W2(d){return BigInt(ee(d>>>0).size)}function H2(d){return BigInt(ee(d>>>0).usage)}function K2(d,h){if(d>>>=0,h>>>=0){var _=pr(h+4);_={label:_,timestampWrites:h=(h=(E(),R)[h+12>>>2>>>0])!==0?{querySet:ee((E(),R)[h+4>>>2>>>0]),beginningOfPassWriteIndex:(E(),R)[h+8>>>2>>>0],endOfPassWriteIndex:(E(),R)[h+12>>>2>>>0]}:void 0}}return h=ee(d),d=c_(0),_=h.beginComputePass(_),st[d>>>0]=_,d}function Q2(d,h,_,g,b,k){_=wt(_),b=wt(b),k=wt(k),ee(d>>>0).copyBufferToBuffer(ee(h>>>0),_,ee(g>>>0),b,k)}function J2(d){var h=ee(d>>>0);return d=i_(0),h=h.finish(),st[d>>>0]=h,d}function X2(d,h,_,g,b,k){k=wt(k),ee(d>>>0).resolveQuerySet(ee(h>>>0),_,g,ee(b>>>0),k)}function Y2(d,h,_,g){ee(d>>>0).dispatchWorkgroups(h,_,g)}function Z2(d,h,_){_=wt(_),ee(d>>>0).dispatchWorkgroupsIndirect(ee(h>>>0),_)}function eR(d){ee(d>>>0).end()}function tR(d,h,_,g,b){g>>>=0,b>>>=0,d=ee(d>>>0),_=ee(_>>>0),g==0?d.setBindGroup(h,_):d.setBindGroup(h,_,(E(),R),b>>>2,g)}function rR(d,h){ee(d>>>0).setPipeline(ee(h>>>0))}function nR(d,h,_){ee(d>>>0).Ee(ee(h>>>0),_)}function sR(d,h){var _=ee(d>>>0);return d=o_(0),h=_.getBindGroupLayout(h),st[d>>>0]=h,d}function aR(d,h){function _(b){var k=(E(),R)[b+8>>>2>>>0],P=(E(),R)[b+32>>>2>>>0],L=(E(),R)[b+36>>>2>>>0],j=0;return b2(b,{327681:X=>{j=(E(),R)[X+8>>>2>>>0]}}),k?((P=ks(b+24))==-1&&(P=void 0),k={buffer:ee(k),offset:ks(b+16),size:P}):k=ee(P||L||j),{binding:(E(),R)[b+4>>>2>>>0],resource:k}}d>>>=0,h={label:pr(4+(h>>>=0)),layout:ee((E(),R)[h+12>>>2>>>0]),entries:function(b,k){for(var P=[],L=0;L<b;++L)P.push(_(k+40*L));return P}((E(),R)[h+16>>>2>>>0],(E(),R)[h+20>>>2>>>0])},d=ee(d);var g=a_(0);return v2(g,d.createBindGroup(h)),g}function oR(d,h){var _;return d>>>=0,(h>>>=0)&&(_={label:pr(h+4)}),h=ee(d),d=l_(0),_=h.createCommandEncoder(_),st[d>>>0]=_,d}function iR(d,h){d>>>=0,h>>>=0,h={type:k2[(E(),D)[h+12>>>2>>>0]],count:(E(),R)[h+16>>>2>>>0]};var _=ee(d);return d=u_(0),h=_.createQuerySet(h),st[d>>>0]=h,d}function lR(d,h){d=ee(d>>>0).adapterInfo,h>>>=0,(E(),R)[h+52>>>2>>>0]=d.subgroupMinSize,(E(),R)[h+56>>>2>>>0]=d.subgroupMaxSize;var _=d.vendor+d.architecture+d.device+d.description,g=ur(_)+1,b=On(g);return b&&cr(_,b,g),_=b,g=ur(d.vendor),eo(h+4,_,g),_+=g,g=ur(d.architecture),eo(h+12,_,g),_+=g,g=ur(d.device),eo(h+20,_,g),eo(h+28,_+g,ur(d.description)),(E(),D)[h+36>>>2>>>0]=2,d=d.isFallbackAdapter?3:4,(E(),D)[h+40>>>2>>>0]=d,(E(),R)[h+44>>>2>>>0]=0,(E(),R)[h+48>>>2>>>0]=0,1}var cR={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function uR(d,h){h>>>=0;var _=ee(d>>>0);d=On(4*_.features.size);var g=0,b=0;for(let k of _.features)0<=(_=cR[k])&&((E(),D)[d+g>>>2>>>0]=_,g+=4,b++);(E(),R)[h+4>>>2>>>0]=d,(E(),R)[h>>>2>>>0]=b}function dR(d,h){return Wm(ee(d>>>0).limits,h>>>0),1}function pR(d,h){ee(d>>>0).pushErrorScope(x2[h])}function hR(d,h,_){h>>>=0,_>>>=0,d=ee(d>>>0),h=Array.from((E(),D).subarray(_>>>2>>>0,_+4*h>>>2>>>0),g=>ee(g)),d.submit(h)}function fR(d,h,_,g,b){_=wt(_),g>>>=0,b>>>=0,d=ee(d>>>0),h=ee(h>>>0),g=(E(),Q).subarray(g>>>0,g+b>>>0),d.writeBuffer(h,_,g,0,b)}s||function(){for(var d=t.numThreads-1;d--;)cm();Pe.push(async()=>{var h=async function(){if(!s)return Promise.all(xr.map(lm))}();ye++,await h,--ye==0&&We&&(h=We,We=null,h())})}(),s||(Tr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),fe()),t.wasmBinary&&(p=t.wasmBinary),t.stackSave=()=>se(),t.stackRestore=d=>ne(d),t.stackAlloc=d=>ro(d),t.setValue=function(d,h,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(E(),V)[d>>>0]=h;break;case"i16":(E(),G)[d>>>1>>>0]=h;break;case"i32":(E(),D)[d>>>2>>>0]=h;break;case"i64":(E(),F)[d>>>3>>>0]=BigInt(h);break;case"float":(E(),re)[d>>>2>>>0]=h;break;case"double":(E(),ie)[d>>>3>>>0]=h;break;case"*":(E(),R)[d>>>2>>>0]=h;break;default:Ne(`invalid type for setValue: ${_}`)}},t.getValue=function(d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":return(E(),V)[d>>>0];case"i16":return(E(),G)[d>>>1>>>0];case"i32":return(E(),D)[d>>>2>>>0];case"i64":return(E(),F)[d>>>3>>>0];case"float":return(E(),re)[d>>>2>>>0];case"double":return(E(),ie)[d>>>3>>>0];case"*":return(E(),R)[d>>>2>>>0];default:Ne(`invalid type for getValue: ${h}`)}},t.UTF8ToString=In,t.stringToUTF8=cr,t.lengthBytesUTF8=ur;var t_,r_,_u,to,$t,On,n_,s_,a_,o_,i_,l_,c_,u_,d_,p_,h_,gu,wu,yu,vu,Cs,bu,f_,Mu,m_,__,g_,xu,w_,y_,Tu,he,As,v_,ne,ro,se,b_,Eu,M_,x_,T_,ku,E_,k_,C_,A_,S_,I_,P_,R_,O_,L_,F_,N_,D_,B_,U_,z_,$_,V_,G_,j_,q_,W_,H_,K_,Q_,J_,X_,Y_,Z_,eg,tg,rg,ng,sg,ag,og,ig,lg,cg,hr,mR=[An,xs,pm,gm,wm,ym,vm,bm,Mm,xm,Tm,Em,km,Cm,Am,Sm,$m,Vm,Gm,Qm,Jm,Xm,Ym,Zm,e_],Cu={925676:(d,h,_,g,b)=>{if(t===void 0||!t.Uc)return 1;if((d=In(Number(d>>>0))).startsWith("./")&&(d=d.substring(2)),!(d=t.Uc.get(d)))return 2;if(h=Number(h>>>0),_=Number(_>>>0),g=Number(g>>>0),h+_>d.byteLength)return 3;try{let k=d.subarray(h,h+_);switch(b){case 0:(E(),Q).set(k,g>>>0);break;case 1:t.ad?t.ad(g,k):t.oe(g,k);break;default:return 4}return 0}catch{return 4}},926500:(d,h,_)=>{t.Sd(d,(E(),Q).subarray(h>>>0,h+_>>>0))},926564:()=>t.me(),926606:d=>{t.jd(d)},926643:()=>typeof wasmOffsetConverter<"u"};function _R(d,h,_,g){var b=se();try{return R_(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function gR(d,h,_){var g=se();try{return S_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;he(1,0)}}function wR(d,h,_){var g=se();try{T_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;he(1,0)}}function yR(d,h){var _=se();try{return ku(d,h)}catch(g){if(ne(_),g!==g+0)throw g;he(1,0)}}function vR(d){var h=se();try{E_(d)}catch(_){if(ne(h),_!==_+0)throw _;he(1,0)}}function bR(d,h,_,g,b,k,P){var L=se();try{return A_(d,h,_,g,b,k,P)}catch(j){if(ne(L),j!==j+0)throw j;he(1,0)}}function MR(d,h){var _=se();try{O_(d,h)}catch(g){if(ne(_),g!==g+0)throw g;he(1,0)}}function xR(d,h,_,g,b,k){var P=se();try{k_(d,h,_,g,b,k)}catch(L){if(ne(P),L!==L+0)throw L;he(1,0)}}function TR(d,h,_,g){var b=se();try{P_(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function ER(d,h,_,g,b,k,P){var L=se();try{F_(d,h,_,g,b,k,P)}catch(j){if(ne(L),j!==j+0)throw j;he(1,0)}}function kR(d,h,_,g,b,k,P){var L=se();try{N_(d,h,_,g,b,k,P)}catch(j){if(ne(L),j!==j+0)throw j;he(1,0)}}function CR(d,h,_,g,b,k,P,L){var j=se();try{q_(d,h,_,g,b,k,P,L)}catch(X){if(ne(j),X!==X+0)throw X;he(1,0)}}function AR(d,h,_,g,b,k,P,L,j,X,ve,xe){var Re=se();try{D_(d,h,_,g,b,k,P,L,j,X,ve,xe)}catch(te){if(ne(Re),te!==te+0)throw te;he(1,0)}}function SR(d,h,_,g,b){var k=se();try{return L_(d,h,_,g,b)}catch(P){if(ne(k),P!==P+0)throw P;he(1,0)}}function IR(d,h,_,g,b){var k=se();try{C_(d,h,_,g,b)}catch(P){if(ne(k),P!==P+0)throw P;he(1,0)}}function PR(d,h,_,g,b,k,P,L){var j=se();try{I_(d,h,_,g,b,k,P,L)}catch(X){if(ne(j),X!==X+0)throw X;he(1,0)}}function RR(d){var h=se();try{return W_(d)}catch(_){if(ne(h),_!==_+0)throw _;he(1,0)}}function OR(d,h,_){var g=se();try{return H_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;he(1,0)}}function LR(d,h){var _=se();try{return ag(d,h)}catch(g){if(ne(_),g!==g+0)throw g;return he(1,0),0n}}function FR(d,h,_,g,b){var k=se();try{K_(d,h,_,g,b)}catch(P){if(ne(k),P!==P+0)throw P;he(1,0)}}function NR(d){var h=se();try{return B_(d)}catch(_){if(ne(h),_!==_+0)throw _;return he(1,0),0n}}function DR(d,h,_,g,b,k){var P=se();try{return G_(d,h,_,g,b,k)}catch(L){if(ne(P),L!==L+0)throw L;he(1,0)}}function BR(d,h,_,g,b,k){var P=se();try{return Q_(d,h,_,g,b,k)}catch(L){if(ne(P),L!==L+0)throw L;he(1,0)}}function UR(d,h,_,g,b,k){var P=se();try{return J_(d,h,_,g,b,k)}catch(L){if(ne(P),L!==L+0)throw L;he(1,0)}}function zR(d,h,_,g,b,k,P,L){var j=se();try{return j_(d,h,_,g,b,k,P,L)}catch(X){if(ne(j),X!==X+0)throw X;he(1,0)}}function $R(d,h,_,g,b){var k=se();try{return X_(d,h,_,g,b)}catch(P){if(ne(k),P!==P+0)throw P;return he(1,0),0n}}function VR(d,h,_,g){var b=se();try{return Y_(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function GR(d,h,_,g){var b=se();try{return Z_(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function jR(d,h,_,g,b,k,P,L,j,X,ve,xe){var Re=se();try{return eg(d,h,_,g,b,k,P,L,j,X,ve,xe)}catch(te){if(ne(Re),te!==te+0)throw te;he(1,0)}}function qR(d,h,_,g,b,k,P,L,j,X,ve){var xe=se();try{tg(d,h,_,g,b,k,P,L,j,X,ve)}catch(Re){if(ne(xe),Re!==Re+0)throw Re;he(1,0)}}function WR(d,h,_,g,b,k,P,L,j,X,ve,xe,Re,te,Ye,vt){var Ze=se();try{rg(d,h,_,g,b,k,P,L,j,X,ve,xe,Re,te,Ye,vt)}catch(zr){if(ne(Ze),zr!==zr+0)throw zr;he(1,0)}}function HR(d,h,_,g){var b=se();try{return ng(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function KR(d,h,_,g,b){var k=se();try{return sg(d,h,_,g,b)}catch(P){if(ne(k),P!==P+0)throw P;he(1,0)}}function QR(d,h,_){var g=se();try{return z_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;return he(1,0),0n}}function JR(d,h,_){var g=se();try{return U_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;he(1,0)}}function XR(d,h,_){var g=se();try{return $_(d,h,_)}catch(b){if(ne(g),b!==b+0)throw b;he(1,0)}}function YR(d,h,_,g){var b=se();try{V_(d,h,_,g)}catch(k){if(ne(b),k!==k+0)throw k;he(1,0)}}function no(){if(0<ye)We=no;else if(s)y?.(t),H();else{for(var d=Pe;0<d.length;)d.shift()(t);0<ye?We=no:(t.calledRun=!0,S||(H(),y?.(t)))}}return s||(hr=await nt(),no()),t.PTR_SIZE=4,t.webgpuInit=d=>{let h=new WeakMap,_,g,b=1;t.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var j=h.get(L);if(!j){let X=((ve,xe=0)=>{var Re=h_(xe);return xe=p_(xe,Re),st[Re>>>0]=ve.queue,st[xe>>>0]=ve,xe})(L,j=s_(0));j=[b++,j,X],h.set(L,j)}return _=L,g=j[0],j}_=void 0,g=0};let k=new Map;t.webgpuOnCreateSession=L=>{if(g!==void 0){var j=g;if(g=void 0,L){let X=_u(j);k.set(L,X),j===0&&d(_??ee(X))}_=void 0}},t.webgpuOnReleaseSession=L=>{k.delete(L)};let P=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(L,j,X)=>{if(X)return L[P]=[X,NaN],X;if(X=L[P])return X[1]++,X[0];if((j=k.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((ve,xe=0)=>(ve.mapState==="unmapped"||Ne(),xe=d_(xe),st[xe>>>0]=ve,xe))(L,j),L[P]=[j,1],j},t.webgpuUnregisterBuffer=L=>{let j=L[P];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(n_(j[0]),delete L[P])},t.webgpuGetBuffer=L=>ee(L),t.webgpuCreateDownloader=(L,j,X)=>{if((X=k.get(X))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ve=ee(X),xe=16*Math.ceil(Number(j)/16);return async()=>{let Re=ve.createBuffer({size:xe,usage:9});try{let te=ve.createCommandEncoder();return te.copyBufferToBuffer(L,0,Re,0,xe),ve.queue.submit([te.finish()]),await Re.mapAsync(GPUMapMode.READ),Re.getMappedRange().slice(0,j)}finally{Re.destroy()}}},t.ad=(L,j)=>{var X=j.buffer;let ve=j.byteOffset,xe=j.byteLength;if(j=16*Math.ceil(Number(xe)/16),L=ee(L),!_){var Re=_u(g);_=ee(Re)}let te=(Re=_.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(te).set(new Uint8Array(X,ve,xe)),Re.unmap(),(X=_.createCommandEncoder()).copyBufferToBuffer(Re,0,L,0,j),_.queue.submit([X.finish()]),Re.destroy()}},t.webnnInit=d=>{let h=d[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=d.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=_=>h.onRunStart(_),t.webnnOnRunEnd=h.onRunEnd.bind(h),t.webnnOnReleaseSession=_=>{h.onReleaseSession(_)},t.webnnCreateMLTensorDownloader=(_,g)=>h.createMLTensorDownloader(_,g),t.webnnRegisterMLTensor=(_,g,b,k)=>h.registerMLTensor(_,g,b,k),t.webnnCreateMLContext=_=>h.createMLContext(_),t.webnnRegisterMLConstant=(_,g,b,k,P,L)=>h.registerMLConstant(_,g,b,k,P,t.Uc,L),t.webnnRegisterGraphInput=h.registerGraphInput.bind(h),t.webnnIsGraphInput=h.isGraphInput.bind(h),t.webnnRegisterGraphOutput=h.registerGraphOutput.bind(h),t.webnnIsGraphOutput=h.isGraphOutput.bind(h),t.webnnCreateTemporaryTensor=h.createTemporaryTensor.bind(h),t.webnnIsGraphInputOutputTypeSupported=h.isGraphInputOutputTypeSupported.bind(h)},Y?t:new Promise((d,h)=>{y=d,v=h})}var Vt,hd,kO,CO,AO,SO,me,Ks,IO,Ro,$s,kr,Yr,Cg,ew,tw,PO,rw,RO,$u,et,nw,De,OO,sw,aw,LO,Eo,ow,iw,lw,cw,uw,FO,Jr,Ws,Vu,dw,NO,pw,hw,DO,kt,fd,Gt,fw,Oo,Gu,Zr,en,Ir,Pr,mw,_w,BO,md,UO,zO,$O,VO,GO,ww,tn,_d,yw,ju,qu,vw,jO,bw,Mw,Sg,qO,Wu,ld,Ig,Tt,xw,ko,Pg,Rg,Hu,Og,Ku,Tw,Qu,Ew,gd,Ju,Co,Vs,Xu,Lg,Fg,Ng,wd,Ce,rn,Et,Lo,Me,yd,kw,WO,Dg,Bg,Ug,Ao,Cr,zg,Cw,HO,Xr,Po,Hn,Hs,Fo,vd,bd,cd,Kn,Md,Aw,Sw,KO,$g,Vg,Gg,jg,Iw,qg,pt,Pw,Yu,ud,Zu,Wg,ed,Hg,td,rd,nd,Kg,Rw,QO,Ow,Gs,Qg,Lw,JO,Jg,xd,Td,Ar,Xg,sd,No,Ed,kd,ad,Cd,Ad,Sd,Fw,Sr,Rt,Wn,js,qs,So,od,Io,Kr,Qr,Yg,Nw,Dw,Bw,Uw,zw,$w,Vw,Gw,id,Zg,jw,XO,qw,dd,pd,Ww,YO,ZO,eL,Hw=Ve(()=>{Vt={};hd=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,CO=Object.getOwnPropertyNames,AO=Object.prototype.hasOwnProperty,SO=(e=>typeof $r<"u"?$r:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof $r<"u"?$r:t)[r]}):e)(function(e){if(typeof $r<"u")return $r.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),me=(e,t)=>()=>(e&&(t=e(e=0)),t),Ks=(e,t)=>{for(var r in t)hd(e,r,{get:t[r],enumerable:!0})},IO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of CO(t))!AO.call(e,s)&&s!==r&&hd(e,s,{get:()=>t[s],enumerable:!(n=kO(t,s))||n.enumerable});return e},Ro=e=>IO(hd({},"__esModule",{value:!0}),e),tw=me(()=>{"use strict";$s=new Map,kr=[],Yr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=$s.get(e);if(n===void 0)$s.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=kr.indexOf(e);s!==-1&&kr.splice(s,1);for(let a=0;a<kr.length;a++)if($s.get(kr[a]).priority<=r){kr.splice(a,0,e);return}kr.push(e)}return}throw new TypeError("not a valid backend")},Cg=async e=>{let t=$s.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ew=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?kr:r,s,a=[],o=new Set;for(let l of n){let c=await Cg(l);typeof c=="string"?a.push({name:l,err:c}):(s||(s=c),s===c&&o.add(l))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),PO=me(()=>{"use strict";tw()}),RO=me(()=>{"use strict";rw="1.24.0-dev.20251116-b39e144322"}),nw=me(()=>{"use strict";RO(),$u="warning",et={wasm:{},webgl:{},webgpu:{},versions:{common:rw},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}`);$u=e}},get logLevel(){return $u}},Object.defineProperty(et,"logLevel",{enumerable:!0})}),OO=me(()=>{"use strict";nw(),De=et}),LO=me(()=>{"use strict";sw=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=a*s,p=0,f=u,m=u*2,y=-1;o==="RGBA"?(p=0,f=u,m=u*2,y=u*3):o==="RGB"?(p=0,f=u,m=u*2):o==="RBG"&&(p=0,m=u,f=u*2);for(let v=0;v<a;v++)for(let x=0;x<s;x++){let M=(e.data[p++]-c[0])*l[0],T=(e.data[f++]-c[1])*l[1],A=(e.data[m++]-c[2])*l[2],C=y===-1?255:(e.data[y++]-c[3])*l[3];n.fillStyle="rgba("+M+","+T+","+A+","+C+")",n.fillRect(x,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},aw=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,u;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?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let p=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,m=0,y=1,v=2,x=3,M=0,T=p,A=p*2,C=-1;i==="RGBA"?(M=0,T=p,A=p*2,C=p*3):i==="RGB"?(M=0,T=p,A=p*2):i==="RBG"&&(M=0,A=p,T=p*2),n=r.createImageData(s,a);for(let S=0;S<a*s;m+=f,y+=f,v+=f,x+=f,S++)n.data[m]=(e.data[M++]-u[0])*c[0],n.data[y]=(e.data[T++]-u[1])*c[1],n.data[v]=(e.data[A++]-u[2])*c[2],n.data[x]=C===-1?255:(e.data[C++]-u[3])*c[3]}else throw new Error("Can not access image data");return n}}),FO=me(()=>{"use strict";fd(),Eo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),p=4,f=0,m=1,y=2,v=3,x=0,M=c,T=c*2,A=-1;i==="RGB"&&(p=3,f=0,m=1,y=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(x=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,x=c*2);for(let C=0;C<c;C++,f+=p,y+=p,m+=p,v+=p)u[x++]=(e[f]+o[0])/a[0],u[M++]=(e[m]+o[1])/a[1],u[T++]=(e[y]+o[2])/a[2],A!==-1&&v!==-1&&(u[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new kt("float32",u,[1,4,r,n]):new kt("float32",u,[1,3,r,n])},ow=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=e.width,u.height=e.height;let p=c(u);if(p!=null){let f=e.height,m=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,m=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=f,i.width=m}else i.tensorFormat="RGBA",i.height=f,i.width=m;p.drawImage(e,0,0),o=p.getImageData(0,0,m,f).data}else throw new Error("Can not access image data")}else if(n){let u,p;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(u=t.resizedHeight,p=t.resizedWidth):(u=e.height,p=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=u,i.width=p,t!==void 0){let f=l();f.width=p,f.height=u;let m=c(f);if(m!=null)m.putImageData(e,0,0),o=m.getImageData(0,0,p,u).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=e.width,u.height=e.height;let p=c(u);if(p!=null){let f=e.height,m=e.width;return p.drawImage(e,0,0,m,f),o=p.getImageData(0,0,m,f).data,i.height=f,i.width=m,Eo(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((u,p)=>{let f=l(),m=c(f);if(!e||!m)return p();let y=new Image;y.crossOrigin="Anonymous",y.src=e,y.onload=()=>{f.width=y.width,f.height=y.height,m.drawImage(y,0,0,f.width,f.height);let v=m.getImageData(0,0,f.width,f.height);i.height=f.height,i.width=f.width,u(Eo(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Eo(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},iw=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new kt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},lw=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new kt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},cw=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new kt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},uw=(e,t,r)=>new kt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),NO=me(()=>{"use strict";Jr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ws=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Vu=!1,dw=()=>{if(!Vu){Vu=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Jr.set("int64",BigInt64Array),Ws.set(BigInt64Array,"int64")),t&&(Jr.set("uint64",BigUint64Array),Ws.set(BigUint64Array,"uint64")),n?(Jr.set("float16",r),Ws.set(r,"float16")):Jr.set("float16",Uint16Array)}}}),DO=me(()=>{"use strict";fd(),pw=e=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},hw=(e,t)=>{switch(e.location){case"cpu":return new kt(e.type,e.data,t);case"cpu-pinned":return new kt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new kt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new kt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new kt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),fd=me(()=>{"use strict";LO(),FO(),NO(),DO(),kt=class{constructor(e,t,r){dw();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let o=Jr.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e=="string")if(n=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Jr.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",o=e;else if(l==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let l=Ws.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");s=i,this.cpuData=o,this.dataLocation="cpu"}let a=pw(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return ow(e,t)}static fromTexture(e,t){return iw(e,t)}static fromGpuBuffer(e,t){return lw(e,t)}static fromMLTensor(e,t){return cw(e,t)}static fromPinnedBuffer(e,t,r){return uw(e,t,r)}toDataURL(e){return sw(this,e)}toImageData(e){return aw(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 hw(this,e)}}}),fw=me(()=>{"use strict";fd(),Gt=kt}),mw=me(()=>{"use strict";nw(),Oo=(e,t)=>{(typeof et.trace>"u"?!et.wasm.trace:!et.trace)||console.timeStamp(`${e}::ORT::${t}`)},Gu=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s<r.length;s++){if(n&&!r[s].includes("TRACE_FUNC")){let a=`FUNC_${e}::${r[s].trim().split(" ")[1]}`;t&&(a+=`::${t}`),Oo("CPU",a);return}r[s].includes("TRACE_FUNC")&&(n=!0)}},Zr=e=>{(typeof et.trace>"u"?!et.wasm.trace:!et.trace)||Gu("BEGIN",e)},en=e=>{(typeof et.trace>"u"?!et.wasm.trace:!et.trace)||Gu("END",e)},Ir=e=>{(typeof et.trace>"u"?!et.wasm.trace:!et.trace)||console.time(`ORT::${e}`)},Pr=e=>{(typeof et.trace>"u"?!et.wasm.trace:!et.trace)||console.timeEnd(`ORT::${e}`)}}),BO=me(()=>{"use strict";tw(),fw(),mw(),_w=class gw{constructor(t){this.handler=t}async run(t,r,n){Zr(),Ir("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Gt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Gt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let p of this.outputNames)if(u.indexOf(p)!==-1){let f=r[p];(f===null||f instanceof Gt)&&(c=!0,o=!1,s[p]=f)}if(c){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)s[c]=null;let i=await this.handler.run(t,s,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof Gt?l[c]=u:l[c]=new Gt(u.type,u.data,u.dims)}return Pr("InferenceSession.run"),en(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Zr(),Ir("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let u=t,p=0,f=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(p=r,!Number.isSafeInteger(p))throw new RangeError("'byteOffset' must be an integer.");if(p<0||p>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(f=t.byteLength-p,typeof n=="number"){if(f=n,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||p+f>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-p}].`);if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(u,p,f)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await ew(o),c=await i.createInferenceSessionHandler(a,l);return Pr("InferenceSession.create"),en(),new gw(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}}}),UO=me(()=>{"use strict";BO(),md=_w}),zO=me(()=>{"use strict"}),$O=me(()=>{"use strict"}),VO=me(()=>{"use strict"}),GO=me(()=>{"use strict"}),ww={};Ks(ww,{InferenceSession:()=>md,TRACE:()=>Oo,TRACE_EVENT_BEGIN:()=>Ir,TRACE_EVENT_END:()=>Pr,TRACE_FUNC_BEGIN:()=>Zr,TRACE_FUNC_END:()=>en,Tensor:()=>Gt,env:()=>De,registerBackend:()=>Yr});tn=me(()=>{"use strict";PO(),OO(),UO(),fw(),zO(),$O(),mw(),VO(),GO()}),_d=me(()=>{"use strict"}),yw={};Ks(yw,{default:()=>vw});jO=me(()=>{"use strict";Fw(),rn(),gd(),ju="ort-wasm-proxy-worker",qu=globalThis.self?.name===ju,qu&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":wd(r.wasm).then(()=>{xd(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;Td(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=No(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;Ed(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":kd(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;Cd(n,s,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},Sd([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":Ad(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),vw=qu?null:e=>new Worker(e??Tt,{type:"module",name:ju})}),bw={};Ks(bw,{default:()=>Mw});qO=me(()=>{"use strict";Mw=Ag,Sg=globalThis.self?.name?.startsWith("em-pthread"),Sg&&Ag()}),gd=me(()=>{"use strict";_d(),Wu=typeof location>"u"?void 0:location.origin,ld=Vt.url>"file:"&&Vt.url<"file;",Ig=()=>{if(ld){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",Vt.url).href,Wu).href}return Vt.url},Tt=Ig(),xw=()=>{if(Tt&&!Tt.startsWith("blob:"))return Tt.substring(0,Tt.lastIndexOf("/")+1)},ko=(e,t)=>{try{let r=t??Tt;return(r?new URL(e,r):new URL(e)).origin===Wu}catch{return!1}},Pg=(e,t)=>{let r=t??Tt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Rg=(e,t)=>`${t??"./"}${e}`,Hu=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Og=async e=>(await import(e)).default,Ku=(jO(),Ro(yw)).default,Tw=async()=>{if(!Tt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ko(Tt))return[void 0,Ku()];let e=await Hu(Tt);return[e,Ku(e)]},Qu=(qO(),Ro(bw)).default,Ew=async(e,t,r,n)=>{let s=Qu&&!(e||t);if(s)if(Tt)s=ko(Tt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,Qu];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Pg(a,t),i=r&&o&&!ko(o,t),l=i?await Hu(o):o??Rg(a,t);return[i?l:void 0,await Og(l)]}}}),rn=me(()=>{"use strict";gd(),Co=!1,Vs=!1,Xu=!1,Lg=()=>{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}},Fg=()=>{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}},Ng=()=>{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}},wd=async e=>{if(Co)return Promise.resolve();if(Vs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Xu)throw new Error("previous call to 'initializeWebAssembly()' failed.");Vs=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Ng())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Fg())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Lg();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,o=s?.mjs,i=o?.href??o,l=s?.wasm,c=l?.href??l,u=e.wasmBinary,[p,f]=await Ew(i,a,r>1,!!u||!!c),m=!1,y=[];if(t>0&&y.push(new Promise(v=>{setTimeout(()=>{m=!0,v()},t)})),y.push(new Promise((v,x)=>{let M={numThreads:r};if(u)M.wasmBinary=u,M.locateFile=T=>T;else if(c||a)M.locateFile=T=>c??a+T;else if(i&&i.indexOf("blob:")!==0)M.locateFile=T=>new URL(T,i).href;else if(p){let T=xw();T&&(M.locateFile=A=>T+A)}f(M).then(T=>{Vs=!1,Co=!0,Ju=T,v(),p&&URL.revokeObjectURL(p)},T=>{Vs=!1,Xu=!0,x(T)})})),await Promise.race(y),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Co&&Ju)return Ju;throw new Error("WebAssembly is not initialized yet.")}}),yd=me(()=>{"use strict";rn(),Et=(e,t)=>{let r=Ce(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Lo=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let o=t?t+s:s;if(typeof a=="object")Lo(a,o+".",r,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Me=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),o=t.getValue(s+n,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),WO=me(()=>{"use strict";rn(),yd(),kw=e=>{let t=Ce(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let a=0;return e?.tag!==void 0&&(a=Et(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Me("Can't create run options."),e?.extra!==void 0&&Lo(e.extra,"",new WeakSet,(o,i)=>{let l=Et(o,n),c=Et(i,n);t._OrtAddRunConfigEntry(r,l,c)!==0&&Me(`Can't set a run config entry: ${o} - ${i}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),a}}}),HO=me(()=>{"use strict";rn(),yd(),Dg=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}`)}},Bg=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ug=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ao=(e,t,r,n)=>{let s=Et(t,n),a=Et(r,n);Ce()._OrtAddSessionConfigEntry(e,s,a)!==0&&Me(`Can't set a session config entry: ${t} - ${r}.`)},Cr=(e,t,r,n)=>{let s=Et(t,n),a=Et(r,n);e.push([s,a])},zg=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let p=s?.deviceType;p&&Ao(e,"deviceType",p,r)}break;case"webgpu":{a="WebGPU";let p;if(typeof s!="string"){let m=s;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)p=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:y}=t;if(typeof y=="boolean"&&y&&Cr(o,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&Cr(o,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let v=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];Cr(o,"forceCpuNodeNames",v.join(`
4
+ `),r)}m.validationMode&&Cr(o,"validationMode",m.validationMode,r)}let f=Ce().webgpuRegisterDevice(p);if(f){let[m,y,v]=f;Cr(o,"deviceId",m.toString(),r),Cr(o,"webgpuInstance",y.toString(),r),Cr(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=Et(a,r),l=o.length,c=0,u=0;if(l>0){c=Ce()._malloc(l*Ce().PTR_SIZE),r.push(c),u=Ce()._malloc(l*Ce().PTR_SIZE),r.push(u);for(let p=0;p<l;p++)Ce().setValue(c+p*Ce().PTR_SIZE,o[p][0],"*"),Ce().setValue(u+p*Ce().PTR_SIZE,o[p][1],"*")}await Ce()._OrtAppendExecutionProvider(e,i,c,u,l)!==0&&Me(`Can't append execution provider: ${a}.`)}},Cw=async e=>{let t=Ce(),r=0,n=[],s=e||{};Ug(s);try{let a=Dg(s.graphOptimizationLevel??"all"),o=Bg(s.executionMode??"sequential"),i=typeof s.logId=="string"?Et(s.logId,n):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=s.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let u=typeof s.optimizedModelFilePath=="string"?Et(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,c,u),r===0&&Me("Can't create session options."),s.executionProviders&&await zg(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Ao(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[p,f]of Object.entries(s.freeDimensionOverrides)){if(typeof p!="string")throw new Error(`free dimension override name must be a string: ${p}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let m=Et(p,n);t._OrtAddFreeDimensionOverride(r,m,f)!==0&&Me(`Can't set a free dimension override: ${p} - ${f}.`)}return s.extra!==void 0&&Lo(s.extra,"",new WeakSet,(p,f)=>{Ao(r,p,f,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Me("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Kn=me(()=>{"use strict";Xr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Po=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Hn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},Hs=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Fo=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}`)}},vd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",bd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",cd=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}`)}}}),Aw=me(()=>{"use strict";_d(),Md=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(i){if(i instanceof RangeError){let l=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),KO=me(()=>{"use strict";Kn(),Sw=(e,t)=>new(Hs(t))(e)}),Pw=me(()=>{"use strict";Kn(),$g=["V","I","W","E","F"],Vg=(e,t)=>{console.log(`[${$g[e]},${new Date().toISOString()}]${t}`)},Iw=(e,t)=>{Gg=e,jg=t},qg=(e,t)=>{let r=Fo(e),n=Fo(Gg);r>=n&&Vg(r,typeof t=="function"?t():t)},pt=(...e)=>{jg&&qg(...e)}}),QO=me(()=>{"use strict";Kn(),Pw(),Yu=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ud=(e,t)=>{if(t==="int32")return e;let r=Yu.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let n=r/8;if(e.byteLength%n!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(Hs(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i<s;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Zu=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Wg=1,ed=()=>Wg++,Hg=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),td=(e,t)=>{let r=Yu.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},rd=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return td(this.dataType,this.tensorShape)}destroy(){pt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Zu(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},nd=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Hg.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);pt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==td(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=ud(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 pt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Zu(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()}},Kg=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=ed();return this.tensorTrackersById.set(e,new nd(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n,s){pt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){pt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let s=this.getMLContext(e),a=ed(),o=new rd({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new nd(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,t,r)){pt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let p=this.freeTensors.splice(c,1)[0];return p.sessionId=e,p}pt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new rd({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Rw=(...e)=>new Kg(...e)}),Ow={};Ks(Ow,{WebNNBackend:()=>Lw});JO=me(()=>{"use strict";Kn(),rn(),KO(),QO(),Pw(),Gs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Qg=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},Lw=class{constructor(e){this.tensorManager=Rw(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,Iw(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){pt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){pt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)pt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>Qg(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){pt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=Gs.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){pt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=Gs.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!Ce().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");pt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return Sw(r,t)}}registerMLTensor(e,t,r,n){let s=Gs.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return pt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(t,t+r).buffer,u;switch(s.dataType){case"float32":u=new Float32Array(c);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":u=new Int32Array(c);break;case"uint32":u=new Uint32Array(c);break;case"int64":if(o){let p=ud(new Uint8Array(c),"int64");u=new Int32Array(p.buffer),s.dataType="int32"}else u=new BigInt64Array(c);break;case"uint64":u=new BigUint64Array(c);break;case"int8":u=new Int8Array(c);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return pt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=Gs.get(Xr(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),Fw=me(()=>{"use strict";tn(),WO(),HO(),Kn(),rn(),yd(),Aw(),Jg=(e,t)=>{Ce()._OrtInit(e,t)!==0&&Me("Can't initialize onnxruntime.")},xd=async e=>{Jg(e.wasm.numThreads,Fo(e.logLevel))},Td=async(e,t)=>{Ce().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Ce().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(JO(),Ro(Ow)).WebNNBackend(e);Ce().webnnInit([n,()=>n.reserveTensorId(),s=>n.releaseTensorId(s),async(s,a,o,i,l)=>n.ensureTensor(s,a,o,i,l),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},Ar=new Map,Xg=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&Me("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},sd=(e,t)=>{let r=Ce(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&Me("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));s=Number(r.getValue(o+a,"*"));let l=r.HEAP32[s/4];if(l===0)return[i,0];let c=r.HEAPU32[s/4+1],u=[];for(let p=0;p<c;p++){let f=Number(r.getValue(s+8+p*a,"*"));u.push(f!==0?r.UTF8ToString(f):Number(r.getValue(s+8+(p+c)*a,"*")))}return[i,l,u]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},No=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Ed=async(e,t)=>{let r,n,s=Ce();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=No(e);let a=0,o=0,i=0,l=[],c=[],u=[];try{if([o,l]=await Cw(t),t?.externalData&&s.mountExternalData){let C=[];for(let S of t.externalData){let O=typeof S=="string"?S:S.path;C.push(Md(typeof S=="string"?S:S.data).then(E=>{s.mountExternalData(O,E)}))}await Promise.all(C)}for(let C of t?.executionProviders??[])if((typeof C=="string"?C:C.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof C!="string"){let S=C,O=S?.context,E=S?.gpuDevice,K=S?.deviceType,$=S?.powerPreference;O?s.currentContext=O:E?s.currentContext=await s.webnnCreateMLContext(E):s.currentContext=await s.webnnCreateMLContext({deviceType:K,powerPreference:$})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&Me("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[p,f]=Xg(a),m=!!t?.enableGraphCapture,y=[],v=[],x=[],M=[],T=[];for(let C=0;C<p;C++){let[S,O,E]=sd(a,C);S===0&&Me("Can't get an input name."),c.push(S);let K=s.UTF8ToString(S);y.push(K),x.push(O===0?{name:K,isTensor:!1}:{name:K,isTensor:!0,type:Po(O),shape:E})}for(let C=0;C<f;C++){let[S,O,E]=sd(a,C+p);S===0&&Me("Can't get an output name."),u.push(S);let K=s.UTF8ToString(S);v.push(K),M.push(O===0?{name:K,isTensor:!1}:{name:K,isTensor:!0,type:Po(O),shape:E});{if(m&&t?.preferredOutputLocation===void 0){T.push("gpu-buffer");continue}let $=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[K]??"cpu",V=s.webnnIsGraphOutput;if($==="cpu"&&V&&V(a,K)){T.push("ml-tensor-cpu-output");continue}if($!=="cpu"&&$!=="cpu-pinned"&&$!=="gpu-buffer"&&$!=="ml-tensor")throw new Error(`Not supported preferred output location: ${$}.`);if(m&&$!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${$}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);T.push($)}}let A=null;return T.some(C=>C==="gpu-buffer"||C==="ml-tensor"||C==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&Me("Can't create IO binding."),A={handle:i,outputPreferredLocations:T,outputPreferredLocationsEncoded:T.map(C=>C==="ml-tensor-cpu-output"?"ml-tensor":C).map(C=>cd(C))}),Ar.set(a,[a,c,u,A,m,!1]),[a,y,v,x,M]}catch(p){throw c.forEach(f=>s._OrtFree(f)),u.forEach(f=>s._OrtFree(f)),i!==0&&s._OrtReleaseBinding(i)!==0&&Me("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&Me("Can't release session."),p}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&Me("Can't release session options."),l.forEach(p=>s._free(p)),s.unmountExternalData?.()}},kd=e=>{let t=Ce(),r=Ar.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&Me("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&Me("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(n)!==0&&Me("Can't release session."),Ar.delete(e)},ad=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Ce(),l=i.PTR_SIZE,c=e[0],u=e[1],p=e[3],f=p,m,y;if(c==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let M=e[2].gpuBuffer;y=Hn(Xr(c),u);{let T=i.webgpuRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=T(M,n)}}else if(p==="ml-tensor"){let M=e[2].mlTensor;y=Hn(Xr(c),u);let T=i.webnnRegisterMLTensor;if(!T)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=T(n,M,Xr(c),u)}else{let M=e[2];if(Array.isArray(M)){y=l*M.length,m=i._malloc(y),r.push(m);for(let T=0;T<M.length;T++){if(typeof M[T]!="string")throw new TypeError(`tensor data at index ${T} is not a string`);i.setValue(m+T*l,Et(M[T],r),"*")}}else{let T=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(c!=="string"&&T&&A){let C=i.UTF8ToString(s);if(T(n,C)||A(n,C)){let S=Xr(c);y=Hn(S,u),f="ml-tensor";let O=i.webnnCreateTemporaryTensor,E=i.webnnUploadTensor;if(!O||!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let K=await O(n,S,u);E(K,new Uint8Array(M.buffer,M.byteOffset,M.byteLength)),m=K}else y=M.byteLength,m=i._malloc(y),r.push(m),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,y),m)}else y=M.byteLength,m=i._malloc(y),r.push(m),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,y),m)}}let v=i.stackSave(),x=i.stackAlloc(4*u.length);try{u.forEach((T,A)=>i.setValue(x+A*l,T,l===4?"i32":"i64"));let M=i._OrtCreateTensor(Xr(c),m,y,x,u.length,cd(f));M===0&&Me(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(M)}finally{i.stackRestore(v)}},Cd=async(e,t,r,n,s,a)=>{let o=Ce(),i=o.PTR_SIZE,l=Ar.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],u=l[1],p=l[2],f=l[3],m=l[4],y=l[5],v=t.length,x=n.length,M=0,T=[],A=[],C=[],S=[],O=[],E=o.stackSave(),K=o.stackAlloc(v*i),$=o.stackAlloc(v*i),V=o.stackAlloc(x*i),Q=o.stackAlloc(x*i);try{[M,T]=kw(a),Ir("wasm prepareInputOutputTensor");for(let R=0;R<v;R++)await ad(r[R],A,S,e,u[t[R]],t[R],m);for(let R=0;R<x;R++)await ad(s[R],C,S,e,p[n[R]],v+n[R],m);Pr("wasm prepareInputOutputTensor");for(let R=0;R<v;R++)o.setValue(K+R*i,A[R],"*"),o.setValue($+R*i,u[t[R]],"*");for(let R=0;R<x;R++)o.setValue(V+R*i,C[R],"*"),o.setValue(Q+R*i,p[n[R]],"*");if(f&&!y){let{handle:R,outputPreferredLocations:re,outputPreferredLocationsEncoded:ie}=f;if(u.length!==v)throw new Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${u.length}).`);Ir("wasm bindInputsOutputs");for(let F=0;F<v;F++){let N=t[F];await o._OrtBindInput(R,u[N],A[F])!==0&&Me(`Can't bind input[${F}] for session=${e}.`)}for(let F=0;F<x;F++){let N=n[F];s[F]?.[3]?(O.push(C[F]),o._OrtBindOutput(R,p[N],C[F],0)!==0&&Me(`Can't bind pre-allocated output[${F}] for session=${e}.`)):o._OrtBindOutput(R,p[N],0,ie[N])!==0&&Me(`Can't bind output[${F}] to ${re[F]} for session=${e}.`)}Pr("wasm bindInputsOutputs"),Ar.set(e,[c,u,p,f,m,!0])}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let G;f?G=await o._OrtRunWithBinding(c,f.handle,x,V,M):G=await o._OrtRun(c,$,K,v,Q,x,V,M),G!==0&&Me("failed to call OrtRun().");let W=[],D=[];Ir("wasm ProcessOutputTensor");for(let R=0;R<x;R++){let re=Number(o.getValue(V+R*i,"*"));if(re===C[R]||O.includes(C[R])){W.push(s[R]),re!==C[R]&&o._OrtReleaseTensor(re)!==0&&Me("Can't release tensor.");continue}let ie=o.stackSave(),F=o.stackAlloc(4*i),N=!1,z,Y=0;try{o._OrtGetTensorData(re,F,F+i,F+2*i,F+3*i)!==0&&Me(`Can't access output tensor data on index ${R}.`);let fe=i===4?"i32":"i64",H=Number(o.getValue(F,fe));Y=o.getValue(F+i,"*");let Ne=o.getValue(F+i*2,"*"),Xe=Number(o.getValue(F+i*3,fe)),nt=[];for(let Pe=0;Pe<Xe;Pe++)nt.push(Number(o.getValue(Ne+Pe*i,fe)));o._OrtFree(Ne)!==0&&Me("Can't free memory for tensor dims.");let qe=nt.reduce((Pe,ye)=>Pe*ye,1);z=Po(H);let gt=f?.outputPreferredLocations[n[R]];if(z==="string"){if(gt==="gpu-buffer"||gt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Pe=[];for(let ye=0;ye<qe;ye++){let We=o.getValue(Y+ye*i,"*"),Yt=o.getValue(Y+(ye+1)*i,"*"),ke=ye===qe-1?void 0:Yt-We;Pe.push(o.UTF8ToString(We,ke))}W.push([z,nt,Pe,"cpu"])}else if(gt==="gpu-buffer"&&qe>0){let Pe=o.webgpuGetBuffer;if(!Pe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ye=Pe(Y),We=Hn(H,qe);if(We===void 0||!vd(z))throw new Error(`Unsupported data type: ${z}`);N=!0;{o.webgpuRegisterBuffer(ye,e,Y);let Yt=o.webgpuCreateDownloader(ye,We,e);W.push([z,nt,{gpuBuffer:ye,download:async()=>{let ke=await Yt();return new(Hs(z))(ke)},dispose:()=>{o._OrtReleaseTensor(re)!==0&&Me("Can't release tensor.")}},"gpu-buffer"])}}else if(gt==="ml-tensor"&&qe>0){let Pe=o.webnnEnsureTensor,ye=o.webnnIsGraphInputOutputTypeSupported;if(!Pe||!ye)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Hn(H,qe)===void 0||!bd(z))throw new Error(`Unsupported data type: ${z}`);if(!ye(e,z,!1))throw new Error(`preferredLocation "ml-tensor" for ${z} output is not supported by current WebNN Context.`);let We=await Pe(e,Y,H,nt,!1);N=!0,W.push([z,nt,{mlTensor:We,download:o.webnnCreateMLTensorDownloader(Y,z),dispose:()=>{o.webnnReleaseTensorId(Y),o._OrtReleaseTensor(re)}},"ml-tensor"])}else if(gt==="ml-tensor-cpu-output"&&qe>0){let Pe=o.webnnCreateMLTensorDownloader(Y,z)(),ye=W.length;N=!0,D.push((async()=>{let We=[ye,await Pe];return o.webnnReleaseTensorId(Y),o._OrtReleaseTensor(re),We})()),W.push([z,nt,[],"cpu"])}else{let Pe=Hs(z),ye=new Pe(qe);new Uint8Array(ye.buffer,ye.byteOffset,ye.byteLength).set(o.HEAPU8.subarray(Y,Y+ye.byteLength)),W.push([z,nt,ye,"cpu"])}}finally{o.stackRestore(ie),z==="string"&&Y&&o._free(Y),N||o._OrtReleaseTensor(re)}}f&&!m&&(o._OrtClearBoundOutputs(f.handle)!==0&&Me("Can't clear bound outputs."),Ar.set(e,[c,u,p,f,m,!1]));for(let[R,re]of await Promise.all(D))W[R][2]=re;return Pr("wasm ProcessOutputTensor"),W}finally{o.webnnOnRunEnd?.(c),o.stackRestore(E),r.forEach(G=>{G&&G[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(G[2].gpuBuffer)}),s.forEach(G=>{G&&G[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(G[2].gpuBuffer)}),A.forEach(G=>o._OrtReleaseTensor(G)),C.forEach(G=>o._OrtReleaseTensor(G)),S.forEach(G=>o._free(G)),M!==0&&o._OrtReleaseRunOptions(M),T.forEach(G=>o._free(G))}},Ad=e=>{let t=Ce(),r=Ar.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Me("Can't get an profile file name."),t._OrtFree(s)},Sd=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Gw=me(()=>{"use strict";tn(),Fw(),rn(),gd(),Sr=()=>!!De.wasm.proxy&&typeof document<"u",Wn=!1,js=!1,qs=!1,Io=new Map,Kr=(e,t)=>{let r=Io.get(e);r?r.push(t):Io.set(e,[t])},Qr=()=>{if(Wn||!js||qs||!Rt)throw new Error("worker not ready")},Yg=e=>{switch(e.data.type){case"init-wasm":Wn=!1,e.data.err?(qs=!0,od[1](e.data.err)):(js=!0,od[0]()),So&&(URL.revokeObjectURL(So),So=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Io.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Nw=async()=>{if(!js){if(Wn)throw new Error("multiple calls to 'initWasm()' detected.");if(qs)throw new Error("previous call to 'initWasm()' failed.");if(Wn=!0,Sr())return new Promise((e,t)=>{Rt?.terminate(),Tw().then(([r,n])=>{try{Rt=n,Rt.onerror=a=>t(a),Rt.onmessage=Yg,od=[e,t];let s={type:"init-wasm",in:De};!s.in.wasm.wasmPaths&&(r||ld)&&(s.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",Vt.url).href}),Rt.postMessage(s),So=r}catch(s){t(s)}},t)});try{await wd(De.wasm),await xd(De),js=!0}catch(e){throw qs=!0,e}finally{Wn=!1}}},Dw=async e=>{if(Sr())return Qr(),new Promise((t,r)=>{Kr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:De}};Rt.postMessage(n)});await Td(De,e)},Bw=async e=>Sr()?(Qr(),new Promise((t,r)=>{Kr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Rt.postMessage(n,[e.buffer])})):No(e),Uw=async(e,t)=>{if(Sr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Qr(),new Promise((r,n)=>{Kr("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Rt.postMessage(s,a)})}else return Ed(e,t)},zw=async e=>{if(Sr())return Qr(),new Promise((t,r)=>{Kr("release",[t,r]);let n={type:"release",in:e};Rt.postMessage(n)});kd(e)},$w=async(e,t,r,n,s,a)=>{if(Sr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Qr(),new Promise((o,i)=>{Kr("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};Rt.postMessage(c,Sd(l))})}else return Cd(e,t,r,n,s,a)},Vw=async e=>{if(Sr())return Qr(),new Promise((t,r)=>{Kr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Rt.postMessage(n)});Ad(e)}}),XO=me(()=>{"use strict";tn(),Gw(),Kn(),_d(),Aw(),id=(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()}`)}},Zg=e=>{switch(e[3]){case"cpu":return new Gt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!vd(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Gt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!bd(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Gt.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},jw=class{async fetchModelAndCopyToWasmMemory(e){return Bw(await Md(e))}async loadModel(e,t){Zr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Uw(r,t),en()}async dispose(){return zw(this.sessionId)}async run(e,t,r){Zr();let n=[],s=[];Object.entries(e).forEach(p=>{let f=p[0],m=p[1],y=this.inputNames.indexOf(f);if(y===-1)throw new Error(`invalid input '${f}'`);n.push(m),s.push(y)});let a=[],o=[];Object.entries(t).forEach(p=>{let f=p[0],m=p[1],y=this.outputNames.indexOf(f);if(y===-1)throw new Error(`invalid output '${f}'`);a.push(m),o.push(y)});let i=n.map((p,f)=>id(p,()=>`input "${this.inputNames[s[f]]}"`)),l=a.map((p,f)=>p?id(p,()=>`output "${this.outputNames[o[f]]}"`):null),c=await $w(this.sessionId,s,i,o,l,r),u={};for(let p=0;p<c.length;p++)u[this.outputNames[o[p]]]=a[p]??Zg(c[p]);return en(),u}startProfiling(){}endProfiling(){Vw(this.sessionId)}}}),qw={};Ks(qw,{OnnxruntimeWebAssemblyBackend:()=>pd,initializeFlags:()=>dd,wasmBackend:()=>Ww});YO=me(()=>{"use strict";tn(),Gw(),XO(),dd=()=>{(typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0);let e=De.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),De.wasm.simd=!1),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=!1),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=!1),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)De.wasm.numThreads=1;else{let t=typeof navigator>"u"?SO("node:os").cpus().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},pd=class{async init(e){dd(),await Nw(),await Dw(e)}async createInferenceSessionHandler(e,t){let r=new jw;return await r.loadModel(e,t),r}},Ww=new pd});tn();tn();tn();ZO="1.25.0-dev.20260307-d626b568e0",eL=ww;{let e=(YO(),Ro(qw)).wasmBackend;Yr("webgpu",e,5),Yr("webnn",e,5),Yr("cpu",e,10),Yr("wasm",e,10)}Object.defineProperty(De.versions,"web",{value:ZO,enumerable:!0})});var Pd=Ve(()=>{});var Kw=Ve(()=>{Pd()});var Qw,Jw=Ve(()=>{Qw="1.24.2"});var Xw,Rd,Od=Ve(()=>{Jw();Xw="warning",Rd={wasm:{},webgl:{},webgpu:{},versions:{common:Qw},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}`);Xw=e}},get logLevel(){return Xw}};Object.defineProperty(Rd,"logLevel",{enumerable:!0})});var Yw=Ve(()=>{Od()});var Zw,ey,ty=Ve(()=>{Zw=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=a*s,p=0,f=u,m=u*2,y=-1;o==="RGBA"?(p=0,f=u,m=u*2,y=u*3):o==="RGB"?(p=0,f=u,m=u*2):o==="RBG"&&(p=0,m=u,f=u*2);for(let v=0;v<a;v++)for(let x=0;x<s;x++){let M=(e.data[p++]-c[0])*l[0],T=(e.data[f++]-c[1])*l[1],A=(e.data[m++]-c[2])*l[2],C=y===-1?255:(e.data[y++]-c[3])*l[3];n.fillStyle="rgba("+M+","+T+","+A+","+C+")",n.fillRect(x,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ey=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,u;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?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let p=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,m=0,y=1,v=2,x=3,M=0,T=p,A=p*2,C=-1;i==="RGBA"?(M=0,T=p,A=p*2,C=p*3):i==="RGB"?(M=0,T=p,A=p*2):i==="RBG"&&(M=0,A=p,T=p*2),n=r.createImageData(s,a);for(let S=0;S<a*s;m+=f,y+=f,v+=f,x+=f,S++)n.data[m]=(e.data[M++]-u[0])*c[0],n.data[y]=(e.data[T++]-u[1])*c[1],n.data[v]=(e.data[A++]-u[2])*c[2],n.data[x]=C===-1?255:(e.data[C++]-u[3])*c[3]}else throw new Error("Can not access image data");return n}});var Ld,ry,ny,sy,ay,oy,iy=Ve(()=>{Do();Ld=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),p=4,f=0,m=1,y=2,v=3,x=0,M=c,T=c*2,A=-1;i==="RGB"&&(p=3,f=0,m=1,y=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(x=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,x=c*2);for(let S=0;S<c;S++,f+=p,y+=p,m+=p,v+=p)u[x++]=(e[f]+o[0])/a[0],u[M++]=(e[m]+o[1])/a[1],u[T++]=(e[y]+o[2])/a[2],A!==-1&&v!==-1&&(u[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new at("float32",u,[1,4,r,n]):new at("float32",u,[1,3,r,n])},ry=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=e.width,u.height=e.height;let p=c(u);if(p!=null){let f=e.height,m=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,m=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=f,i.width=m}else i.tensorFormat="RGBA",i.height=f,i.width=m;p.drawImage(e,0,0),o=p.getImageData(0,0,m,f).data}else throw new Error("Can not access image data")}else if(n){let u,p;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(u=t.resizedHeight,p=t.resizedWidth):(u=e.height,p=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=u,i.width=p,t!==void 0){let f=l();f.width=p,f.height=u;let m=c(f);if(m!=null)m.putImageData(e,0,0),o=m.getImageData(0,0,p,u).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=e.width,u.height=e.height;let p=c(u);if(p!=null){let f=e.height,m=e.width;return p.drawImage(e,0,0,m,f),o=p.getImageData(0,0,m,f).data,i.height=f,i.width=m,Ld(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((u,p)=>{let f=l(),m=c(f);if(!e||!m)return p();let y=new Image;y.crossOrigin="Anonymous",y.src=e,y.onload=()=>{f.width=y.width,f.height=y.height,m.drawImage(y,0,0,f.width,f.height);let v=m.getImageData(0,0,f.width,f.height);i.height=f.height,i.width=f.width,u(Ld(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Ld(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},ny=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new at({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},sy=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new at({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},ay=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new at({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},oy=(e,t,r)=>new at({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var nn,Qs,ly,cy,uy=Ve(()=>{nn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Qs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ly=!1,cy=()=>{if(!ly){ly=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(nn.set("int64",BigInt64Array),Qs.set(BigInt64Array,"int64")),t&&(nn.set("uint64",BigUint64Array),Qs.set(BigUint64Array,"uint64")),n?(nn.set("float16",r),Qs.set(r,"float16")):nn.set("float16",Uint16Array)}}});var dy,py,hy=Ve(()=>{Do();dy=e=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},py=(e,t)=>{switch(e.location){case"cpu":return new at(e.type,e.data,t);case"cpu-pinned":return new at({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new at({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new at({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new at({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var at,Do=Ve(()=>{ty();iy();uy();hy();at=class{constructor(t,r,n){cy();let s,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,a=t.dims,t.location){case"cpu-pinned":{let i=nn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof t=="string")if(s=t,l=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=nn.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof t[0];if(c==="string")s="string",i=t;else if(c==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{let c=Qs.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=c,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}let o=dy(a);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=a,this.size=o}static async fromImage(t,r){return ry(t,r)}static fromTexture(t,r){return ny(t,r)}static fromGpuBuffer(t,r){return sy(t,r)}static fromMLTensor(t,r){return ay(t,r)}static fromPinnedBuffer(t,r,n){return oy(t,r,n)}toDataURL(t){return Zw(this,t)}toImageData(t){return ey(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;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return py(this,t)}}});var Fd,Nd=Ve(()=>{Do();Fd=at});var Dd=Ve(()=>{Od()});var fy=Ve(()=>{Pd();Nd();Dd()});var my=Ve(()=>{fy()});var _y=Ve(()=>{});var gy=Ve(()=>{});var wy=Ve(()=>{});var yy=Ve(()=>{});var vy=Ve(()=>{Kw();Yw();my();Nd();_y();gy();Dd();wy();yy()});var jI={};Au(jI,{ASTFeatureExtractor:()=>Yb,ASTForAudioClassification:()=>u0,ASTModel:()=>c0,ASTPreTrainedModel:()=>Ui,AfmoeForCausalLM:()=>o0,AfmoeModel:()=>a0,AfmoePreTrainedModel:()=>Di,AlbertForMaskedLM:()=>r0,AlbertForQuestionAnswering:()=>t0,AlbertForSequenceClassification:()=>e0,AlbertModel:()=>Zx,AlbertPreTrainedModel:()=>fs,AlbertTokenizer:()=>nb,ApertusForCausalLM:()=>s0,ApertusModel:()=>n0,ApertusPreTrainedModel:()=>Ni,ArceeForCausalLM:()=>l0,ArceeModel:()=>i0,ArceePreTrainedModel:()=>Bi,AudioClassificationPipeline:()=>bI,AutoConfig:()=>ls,AutoFeatureExtractor:()=>Bt,AutoImageProcessor:()=>mt,AutoModel:()=>ns,AutoModelForAudioClassification:()=>lI,AutoModelForAudioFrameClassification:()=>VU,AutoModelForAudioTextToText:()=>HU,AutoModelForCTC:()=>iI,AutoModelForCausalLM:()=>eI,AutoModelForDepthEstimation:()=>dI,AutoModelForDocumentQuestionAnswering:()=>cI,AutoModelForImageClassification:()=>sI,AutoModelForImageFeatureExtraction:()=>pI,AutoModelForImageMatting:()=>GU,AutoModelForImageSegmentation:()=>Up,AutoModelForImageTextToText:()=>WU,AutoModelForImageToImage:()=>uI,AutoModelForMaskGeneration:()=>zU,AutoModelForMaskedLM:()=>tI,AutoModelForNormalEstimation:()=>jU,AutoModelForObjectDetection:()=>aI,AutoModelForPoseEstimation:()=>qU,AutoModelForQuestionAnswering:()=>rI,AutoModelForSemanticSegmentation:()=>zp,AutoModelForSeq2SeqLM:()=>li,AutoModelForSequenceClassification:()=>Bp,AutoModelForSpeechSeq2Seq:()=>XS,AutoModelForTextToSpectrogram:()=>YS,AutoModelForTextToWaveform:()=>ZS,AutoModelForTokenClassification:()=>JS,AutoModelForUniversalSegmentation:()=>$p,AutoModelForVision2Seq:()=>nI,AutoModelForXVector:()=>$U,AutoModelForZeroShotObjectDetection:()=>oI,AutoProcessor:()=>Ix,AutoTokenizer:()=>Ae,AutomaticSpeechRecognitionPipeline:()=>xI,BackgroundRemovalPipeline:()=>CI,BartForConditionalGeneration:()=>p0,BartForSequenceClassification:()=>h0,BartModel:()=>d0,BartPretrainedModel:()=>Ea,BartTokenizer:()=>sb,BaseStreamer:()=>UI,BeitFeatureExtractor:()=>wM,BeitForImageClassification:()=>m0,BeitModel:()=>f0,BeitPreTrainedModel:()=>zi,BertForMaskedLM:()=>g0,BertForQuestionAnswering:()=>v0,BertForSequenceClassification:()=>w0,BertForTokenClassification:()=>y0,BertModel:()=>_0,BertPreTrainedModel:()=>fn,BertTokenizer:()=>ab,BitImageProcessor:()=>yM,BlenderbotForConditionalGeneration:()=>M0,BlenderbotModel:()=>b0,BlenderbotPreTrainedModel:()=>$i,BlenderbotSmallForConditionalGeneration:()=>T0,BlenderbotSmallModel:()=>x0,BlenderbotSmallPreTrainedModel:()=>Vi,BlenderbotSmallTokenizer:()=>ob,BlenderbotTokenizer:()=>ib,BloomForCausalLM:()=>k0,BloomModel:()=>E0,BloomPreTrainedModel:()=>Gi,BloomTokenizer:()=>lb,CHMv2ForDepthEstimation:()=>O0,CHMv2ImageProcessor:()=>bM,CHMv2PreTrainedModel:()=>zh,CLIPFeatureExtractor:()=>MM,CLIPImageProcessor:()=>hh,CLIPModel:()=>F0,CLIPPreTrainedModel:()=>Nr,CLIPSegForImageSegmentation:()=>z0,CLIPSegModel:()=>U0,CLIPSegPreTrainedModel:()=>ji,CLIPTextModel:()=>N0,CLIPTextModelWithProjection:()=>Gh,CLIPTokenizer:()=>ub,CLIPVisionModel:()=>D0,CLIPVisionModelWithProjection:()=>B0,CamembertForMaskedLM:()=>A0,CamembertForQuestionAnswering:()=>P0,CamembertForSequenceClassification:()=>S0,CamembertForTokenClassification:()=>I0,CamembertModel:()=>C0,CamembertPreTrainedModel:()=>mn,CamembertTokenizer:()=>cb,ChatterboxFeatureExtractor:()=>Zb,ChatterboxModel:()=>Bh,ChatterboxPreTrainedModel:()=>Dh,ChatterboxProcessor:()=>pM,ChineseCLIPFeatureExtractor:()=>vM,ChineseCLIPModel:()=>R0,ChineseCLIPPreTrainedModel:()=>Uh,ClapAudioModelWithProjection:()=>Vh,ClapFeatureExtractor:()=>eM,ClapModel:()=>L0,ClapPreTrainedModel:()=>ka,ClapTextModelWithProjection:()=>$h,ClassifierFreeGuidanceLogitsProcessor:()=>Vx,CodeGenForCausalLM:()=>V0,CodeGenModel:()=>$0,CodeGenPreTrainedModel:()=>qi,CodeGenTokenizer:()=>pb,CodeLlamaTokenizer:()=>db,Cohere2ForCausalLM:()=>W0,Cohere2Model:()=>q0,Cohere2PreTrainedModel:()=>Hi,CohereForCausalLM:()=>j0,CohereModel:()=>G0,CoherePreTrainedModel:()=>Wi,CohereTokenizer:()=>hb,ConvBertForMaskedLM:()=>K0,ConvBertForQuestionAnswering:()=>X0,ConvBertForSequenceClassification:()=>Q0,ConvBertForTokenClassification:()=>J0,ConvBertModel:()=>H0,ConvBertPreTrainedModel:()=>_n,ConvBertTokenizer:()=>fb,ConvNextFeatureExtractor:()=>xM,ConvNextForImageClassification:()=>Z0,ConvNextImageProcessor:()=>fh,ConvNextModel:()=>Y0,ConvNextPreTrainedModel:()=>Ki,ConvNextV2ForImageClassification:()=>tT,ConvNextV2Model:()=>eT,ConvNextV2PreTrainedModel:()=>Qi,DFineForObjectDetection:()=>aT,DFineModel:()=>sT,DFinePreTrainedModel:()=>Xi,DINOv3ConvNextModel:()=>PT,DINOv3ConvNextPreTrainedModel:()=>Yh,DINOv3ViTImageProcessor:()=>kM,DINOv3ViTModel:()=>RT,DINOv3ViTPreTrainedModel:()=>Zh,DPTFeatureExtractor:()=>AM,DPTForDepthEstimation:()=>zT,DPTImageProcessor:()=>gh,DPTModel:()=>UT,DPTPreTrainedModel:()=>nl,DacDecoderModel:()=>Hh,DacDecoderOutput:()=>qh,DacEncoderModel:()=>Wh,DacEncoderOutput:()=>jh,DacFeatureExtractor:()=>uh,DacModel:()=>oT,DacPreTrainedModel:()=>Ca,DebertaForMaskedLM:()=>lT,DebertaForQuestionAnswering:()=>dT,DebertaForSequenceClassification:()=>cT,DebertaForTokenClassification:()=>uT,DebertaModel:()=>iT,DebertaPreTrainedModel:()=>gn,DebertaTokenizer:()=>_b,DebertaV2ForMaskedLM:()=>mT,DebertaV2ForQuestionAnswering:()=>wT,DebertaV2ForSequenceClassification:()=>_T,DebertaV2ForTokenClassification:()=>gT,DebertaV2Model:()=>fT,DebertaV2PreTrainedModel:()=>wn,DebertaV2Tokenizer:()=>mb,DecisionTransformerModel:()=>yT,DecisionTransformerPreTrainedModel:()=>Kh,DeepseekV3ForCausalLM:()=>hT,DeepseekV3Model:()=>pT,DeepseekV3PreTrainedModel:()=>Yi,DeiTFeatureExtractor:()=>TM,DeiTForImageClassification:()=>bT,DeiTImageProcessor:()=>mh,DeiTModel:()=>vT,DeiTPreTrainedModel:()=>Zi,DepthAnythingForDepthEstimation:()=>MT,DepthAnythingPreTrainedModel:()=>Qh,DepthEstimationPipeline:()=>OI,DepthProForDepthEstimation:()=>xT,DepthProPreTrainedModel:()=>Jh,DetrFeatureExtractor:()=>EM,DetrForObjectDetection:()=>ET,DetrForSegmentation:()=>kT,DetrImageProcessor:()=>_h,DetrModel:()=>TT,DetrObjectDetectionOutput:()=>el,DetrPreTrainedModel:()=>Aa,DetrSegmentationOutput:()=>Xh,Dinov2ForImageClassification:()=>AT,Dinov2Model:()=>CT,Dinov2PreTrainedModel:()=>tl,Dinov2WithRegistersForImageClassification:()=>IT,Dinov2WithRegistersModel:()=>ST,Dinov2WithRegistersPreTrainedModel:()=>rl,DistilBertForMaskedLM:()=>DT,DistilBertForQuestionAnswering:()=>NT,DistilBertForSequenceClassification:()=>LT,DistilBertForTokenClassification:()=>FT,DistilBertModel:()=>OT,DistilBertPreTrainedModel:()=>yn,DistilBertTokenizer:()=>gb,DocumentQuestionAnsweringPipeline:()=>PI,DonutFeatureExtractor:()=>CM,DonutImageProcessor:()=>Si,DonutSwinModel:()=>BT,DonutSwinPreTrainedModel:()=>ef,DynamicCache:()=>Oh,EdgeTamModel:()=>WC,EfficientNetForImageClassification:()=>VT,EfficientNetImageProcessor:()=>SM,EfficientNetModel:()=>$T,EfficientNetPreTrainedModel:()=>sl,ElectraForMaskedLM:()=>jT,ElectraForQuestionAnswering:()=>HT,ElectraForSequenceClassification:()=>qT,ElectraForTokenClassification:()=>WT,ElectraModel:()=>GT,ElectraPreTrainedModel:()=>vn,ElectraTokenizer:()=>wb,EncodecFeatureExtractor:()=>ch,EosTokenCriteria:()=>Hx,Ernie4_5ForCausalLM:()=>QT,Ernie4_5Model:()=>KT,Ernie4_5PretrainedModel:()=>al,EsmForMaskedLM:()=>XT,EsmForSequenceClassification:()=>YT,EsmForTokenClassification:()=>ZT,EsmModel:()=>JT,EsmPreTrainedModel:()=>_s,EsmTokenizer:()=>yb,EuroBertForMaskedLM:()=>tE,EuroBertForSequenceClassification:()=>rE,EuroBertForTokenClassification:()=>nE,EuroBertModel:()=>eE,EuroBertPreTrainedModel:()=>gs,ExaoneForCausalLM:()=>aE,ExaoneModel:()=>sE,ExaonePreTrainedModel:()=>ol,FalconForCausalLM:()=>iE,FalconH1ForCausalLM:()=>cE,FalconH1Model:()=>lE,FalconH1PreTrainedModel:()=>ll,FalconModel:()=>oE,FalconPreTrainedModel:()=>il,FalconTokenizer:()=>vb,FastViTForImageClassification:()=>dE,FastViTModel:()=>uE,FastViTPreTrainedModel:()=>cl,FeatureExtractionPipeline:()=>LI,FeatureExtractor:()=>ct,FillMaskPipeline:()=>_I,Florence2ForConditionalGeneration:()=>pE,Florence2PreTrainedModel:()=>tf,Florence2Processor:()=>ax,ForcedBOSTokenLogitsProcessor:()=>Lx,ForcedEOSTokenLogitsProcessor:()=>Fx,GLPNFeatureExtractor:()=>PM,GLPNForDepthEstimation:()=>EE,GLPNModel:()=>TE,GLPNPreTrainedModel:()=>vl,GPT2LMHeadModel:()=>FE,GPT2Model:()=>LE,GPT2PreTrainedModel:()=>El,GPT2Tokenizer:()=>xb,GPTBigCodeForCausalLM:()=>CE,GPTBigCodeModel:()=>kE,GPTBigCodePreTrainedModel:()=>bl,GPTJForCausalLM:()=>DE,GPTJModel:()=>NE,GPTJPreTrainedModel:()=>kl,GPTNeoForCausalLM:()=>SE,GPTNeoModel:()=>AE,GPTNeoPreTrainedModel:()=>Ml,GPTNeoXForCausalLM:()=>PE,GPTNeoXModel:()=>IE,GPTNeoXPreTrainedModel:()=>xl,GPTNeoXTokenizer:()=>Mb,Gemma2ForCausalLM:()=>_E,Gemma2Model:()=>mE,Gemma2PreTrainedModel:()=>dl,Gemma3ForCausalLM:()=>wE,Gemma3Model:()=>gE,Gemma3PreTrainedModel:()=>pl,Gemma3nAudioFeatureExtractor:()=>tM,Gemma3nForCausalLM:()=>nf,Gemma3nForConditionalGeneration:()=>hl,Gemma3nPreTrainedModel:()=>rf,Gemma3nProcessor:()=>ox,GemmaForCausalLM:()=>fE,GemmaModel:()=>hE,GemmaPreTrainedModel:()=>ul,GemmaTokenizer:()=>bb,Glm46VImageProcessor:()=>IM,Glm46VProcessor:()=>ix,GlmForCausalLM:()=>vE,GlmModel:()=>yE,GlmMoeDsaForCausalLM:()=>ME,GlmMoeDsaModel:()=>bE,GlmMoeDsaPreTrainedModel:()=>ml,GlmOcrForConditionalGeneration:()=>xE,GlmPreTrainedModel:()=>fl,GptOssForCausalLM:()=>OE,GptOssModel:()=>RE,GptOssPreTrainedModel:()=>Tl,GraniteForCausalLM:()=>UE,GraniteModel:()=>BE,GraniteMoeHybridForCausalLM:()=>$E,GraniteMoeHybridModel:()=>zE,GraniteMoeHybridPreTrainedModel:()=>Al,GranitePreTrainedModel:()=>Cl,GraniteSpeechFeatureExtractor:()=>rM,GraniteSpeechForConditionalGeneration:()=>VE,GraniteSpeechProcessor:()=>lx,GroundingDinoForObjectDetection:()=>GE,GroundingDinoImageProcessor:()=>RM,GroundingDinoPreTrainedModel:()=>of,GroundingDinoProcessor:()=>cx,GroupViTModel:()=>jE,GroupViTPreTrainedModel:()=>lf,HeliumForCausalLM:()=>WE,HeliumModel:()=>qE,HeliumPreTrainedModel:()=>Il,HerbertTokenizer:()=>Tb,HieraForImageClassification:()=>KE,HieraModel:()=>HE,HieraPreTrainedModel:()=>Pl,HubertForCTC:()=>tk,HubertForSequenceClassification:()=>rk,HubertModel:()=>ek,HubertPreTrainedModel:()=>ZE,HunYuanDenseV1ForCausalLM:()=>sk,HunYuanDenseV1Model:()=>nk,HunYuanDenseV1PreTrainedModel:()=>Rl,IJepaForImageClassification:()=>ck,IJepaModel:()=>lk,IJepaPreTrainedModel:()=>Ol,Idefics3ForConditionalGeneration:()=>ik,Idefics3ImageProcessor:()=>Lp,Idefics3Processor:()=>Fp,ImageClassificationPipeline:()=>kI,ImageFeatureExtractionPipeline:()=>FI,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,ImageSegmentationPipeline:()=>Zf,ImageToImagePipeline:()=>RI,ImageToTextPipeline:()=>EI,InterruptableStoppingCriteria:()=>pU,JAISLMHeadModel:()=>dk,JAISModel:()=>uk,JAISPreTrainedModel:()=>Ll,JinaCLIPImageProcessor:()=>LM,JinaCLIPModel:()=>pk,JinaCLIPPreTrainedModel:()=>Sa,JinaCLIPProcessor:()=>dx,JinaCLIPTextModel:()=>uf,JinaCLIPVisionModel:()=>hk,Lfm2ForCausalLM:()=>mk,Lfm2Model:()=>fk,Lfm2MoeForCausalLM:()=>wk,Lfm2MoeModel:()=>gk,Lfm2MoePreTrainedModel:()=>Nl,Lfm2PreTrainedModel:()=>Fl,Lfm2VlForConditionalGeneration:()=>yk,Lfm2VlImageProcessor:()=>FM,Lfm2VlProcessor:()=>px,LightOnOcrForConditionalGeneration:()=>_k,LiteWhisperForConditionalGeneration:()=>aS,Llama4ForCausalLM:()=>Mk,Llama4PreTrainedModel:()=>df,LlamaForCausalLM:()=>bk,LlamaModel:()=>vk,LlamaPreTrainedModel:()=>Dl,LlamaTokenizer:()=>Eb,LlavaForConditionalGeneration:()=>gr,LlavaOnevisionForConditionalGeneration:()=>gr,LlavaOnevisionImageProcessor:()=>NM,LlavaPreTrainedModel:()=>cf,LlavaProcessor:()=>hx,LlavaQwen2ForCausalLM:()=>ok,LogLevel:()=>Ft,LogitsProcessor:()=>Jt,LogitsProcessorList:()=>yi,LogitsWarper:()=>Li,LongT5ForConditionalGeneration:()=>Tk,LongT5Model:()=>xk,LongT5PreTrainedModel:()=>Bl,M2M100ForConditionalGeneration:()=>kk,M2M100Model:()=>Ek,M2M100PreTrainedModel:()=>Ul,M2M100Tokenizer:()=>kb,MBart50Tokenizer:()=>Ab,MBartForCausalLM:()=>Lk,MBartForConditionalGeneration:()=>Rk,MBartForSequenceClassification:()=>Ok,MBartModel:()=>Pk,MBartPreTrainedModel:()=>ws,MBartTokenizer:()=>oh,MPNetForMaskedLM:()=>v1,MPNetForQuestionAnswering:()=>x1,MPNetForSequenceClassification:()=>b1,MPNetForTokenClassification:()=>M1,MPNetModel:()=>y1,MPNetPreTrainedModel:()=>bn,MPNetTokenizer:()=>Pb,MT5ForConditionalGeneration:()=>C1,MT5Model:()=>k1,MT5PreTrainedModel:()=>Jl,MarianMTModel:()=>Ak,MarianModel:()=>Ck,MarianPreTrainedModel:()=>zl,MarianTokenizer:()=>Cb,Mask2FormerImageProcessor:()=>BM,MaskFormerFeatureExtractor:()=>DM,MaskFormerForInstanceSegmentation:()=>Ik,MaskFormerImageProcessor:()=>Ii,MaskFormerModel:()=>Sk,MaskFormerPreTrainedModel:()=>$l,MaxLengthCriteria:()=>Wx,Metric3DForDepthEstimation:()=>Fk,Metric3DPreTrainedModel:()=>pf,Metric3Dv2ForDepthEstimation:()=>Nk,Metric3Dv2PreTrainedModel:()=>hf,MgpstrForSceneTextRecognition:()=>Dk,MgpstrModelOutput:()=>ff,MgpstrPreTrainedModel:()=>mf,MgpstrProcessor:()=>fx,MgpstrTokenizer:()=>Sb,MimiDecoderModel:()=>yf,MimiDecoderOutput:()=>gf,MimiEncoderModel:()=>wf,MimiEncoderOutput:()=>_f,MimiModel:()=>Bk,MimiPreTrainedModel:()=>Ia,MinLengthLogitsProcessor:()=>Ux,MinNewTokensLengthLogitsProcessor:()=>zx,Mistral4ForCausalLM:()=>Vk,Mistral4Model:()=>$k,Mistral4PreTrainedModel:()=>Gl,MistralForCausalLM:()=>zk,MistralModel:()=>Uk,MistralPreTrainedModel:()=>Vl,MobileBertForMaskedLM:()=>jk,MobileBertForQuestionAnswering:()=>Wk,MobileBertForSequenceClassification:()=>qk,MobileBertModel:()=>Gk,MobileBertPreTrainedModel:()=>ys,MobileBertTokenizer:()=>Ib,MobileLLMForCausalLM:()=>Kk,MobileLLMModel:()=>Hk,MobileLLMPreTrainedModel:()=>jl,MobileNetV1FeatureExtractor:()=>UM,MobileNetV1ForImageClassification:()=>Jk,MobileNetV1ForSemanticSegmentation:()=>Xk,MobileNetV1ImageProcessor:()=>yh,MobileNetV1Model:()=>Qk,MobileNetV1PreTrainedModel:()=>Pa,MobileNetV2FeatureExtractor:()=>zM,MobileNetV2ForImageClassification:()=>Zk,MobileNetV2ForSemanticSegmentation:()=>e1,MobileNetV2ImageProcessor:()=>vh,MobileNetV2Model:()=>Yk,MobileNetV2PreTrainedModel:()=>Ra,MobileNetV3FeatureExtractor:()=>$M,MobileNetV3ForImageClassification:()=>r1,MobileNetV3ForSemanticSegmentation:()=>n1,MobileNetV3ImageProcessor:()=>bh,MobileNetV3Model:()=>t1,MobileNetV3PreTrainedModel:()=>Oa,MobileNetV4FeatureExtractor:()=>VM,MobileNetV4ForImageClassification:()=>a1,MobileNetV4ForSemanticSegmentation:()=>o1,MobileNetV4ImageProcessor:()=>Mh,MobileNetV4Model:()=>s1,MobileNetV4PreTrainedModel:()=>La,MobileViTFeatureExtractor:()=>GM,MobileViTForImageClassification:()=>l1,MobileViTImageProcessor:()=>xh,MobileViTModel:()=>i1,MobileViTPreTrainedModel:()=>ql,MobileViTV2ForImageClassification:()=>u1,MobileViTV2Model:()=>c1,MobileViTV2PreTrainedModel:()=>Wl,ModelRegistry:()=>az,ModernBertDecoderForCausalLM:()=>_1,ModernBertDecoderModel:()=>m1,ModernBertDecoderPreTrainedModel:()=>Hl,ModernBertForMaskedLM:()=>p1,ModernBertForSequenceClassification:()=>h1,ModernBertForTokenClassification:()=>f1,ModernBertModel:()=>d1,ModernBertPreTrainedModel:()=>vs,Moondream1ForConditionalGeneration:()=>ak,MoonshineFeatureExtractor:()=>nM,MoonshineForConditionalGeneration:()=>w1,MoonshineModel:()=>g1,MoonshinePreTrainedModel:()=>Kl,MoonshineProcessor:()=>mx,MptForCausalLM:()=>E1,MptModel:()=>T1,MptPreTrainedModel:()=>Ql,MultiModalityCausalLM:()=>A1,MultiModalityPreTrainedModel:()=>vf,MusicgenForCausalLM:()=>I1,MusicgenForConditionalGeneration:()=>bf,MusicgenModel:()=>S1,MusicgenPreTrainedModel:()=>Xl,NanoChatForCausalLM:()=>R1,NanoChatModel:()=>P1,NanoChatPreTrainedModel:()=>Yl,NemotronHForCausalLM:()=>L1,NemotronHModel:()=>O1,NemotronHPreTrainedModel:()=>Zl,NeoBertForMaskedLM:()=>N1,NeoBertForQuestionAnswering:()=>U1,NeoBertForSequenceClassification:()=>D1,NeoBertForTokenClassification:()=>B1,NeoBertModel:()=>F1,NeoBertPreTrainedModel:()=>Mn,NllbTokenizer:()=>Rb,NoBadWordsLogitsProcessor:()=>$x,NoRepeatNGramLogitsProcessor:()=>Dx,NomicBertModel:()=>z1,NomicBertPreTrainedModel:()=>Mf,NougatImageProcessor:()=>jM,NougatTokenizer:()=>Ob,OPTForCausalLM:()=>Y1,OPTModel:()=>X1,OPTPreTrainedModel:()=>ac,ObjectDetectionPipeline:()=>SI,Olmo2ForCausalLM:()=>j1,Olmo2Model:()=>G1,Olmo2PreTrainedModel:()=>tc,Olmo3ForCausalLM:()=>W1,Olmo3Model:()=>q1,Olmo3PreTrainedModel:()=>rc,OlmoForCausalLM:()=>V1,OlmoHybridForCausalLM:()=>K1,OlmoHybridModel:()=>H1,OlmoHybridPreTrainedModel:()=>nc,OlmoModel:()=>$1,OlmoPreTrainedModel:()=>ec,OpenELMForCausalLM:()=>J1,OpenELMModel:()=>Q1,OpenELMPreTrainedModel:()=>sc,OwlViTFeatureExtractor:()=>qM,OwlViTForObjectDetection:()=>rC,OwlViTImageProcessor:()=>Pi,OwlViTModel:()=>tC,OwlViTPreTrainedModel:()=>ic,OwlViTProcessor:()=>_x,Owlv2ForObjectDetection:()=>eC,Owlv2ImageProcessor:()=>WM,Owlv2Model:()=>Z1,Owlv2PreTrainedModel:()=>oc,PaliGemmaForConditionalGeneration:()=>nC,PaliGemmaProcessor:()=>gx,ParakeetFeatureExtractor:()=>sM,ParakeetForCTC:()=>sC,ParakeetPreTrainedModel:()=>xf,PatchTSMixerForPrediction:()=>oC,PatchTSMixerModel:()=>aC,PatchTSMixerPreTrainedModel:()=>lc,PatchTSTForPrediction:()=>lC,PatchTSTModel:()=>iC,PatchTSTPreTrainedModel:()=>cc,Phi3ForCausalLM:()=>pC,Phi3Model:()=>dC,Phi3PreTrainedModel:()=>dc,Phi3VForCausalLM:()=>Ef,Phi3VImageProcessor:()=>HM,Phi3VPreTrainedModel:()=>Tf,Phi3VProcessor:()=>wx,PhiForCausalLM:()=>uC,PhiModel:()=>cC,PhiPreTrainedModel:()=>uc,PixtralImageProcessor:()=>KM,PixtralProcessor:()=>yx,PreTrainedModel:()=>I,PreTrainedTokenizer:()=>le,PretrainedConfig:()=>wi,Processor:()=>Se,PvtForImageClassification:()=>fC,PvtImageProcessor:()=>QM,PvtModel:()=>hC,PvtPreTrainedModel:()=>pc,PyAnnoteFeatureExtractor:()=>dh,PyAnnoteForAudioFrameClassification:()=>_C,PyAnnoteModel:()=>mC,PyAnnotePreTrainedModel:()=>hc,PyAnnoteProcessor:()=>vx,QuestionAnsweringPipeline:()=>mI,Qwen2ForCausalLM:()=>wC,Qwen2Model:()=>gC,Qwen2MoeForCausalLM:()=>vC,Qwen2MoeModel:()=>yC,Qwen2MoePreTrainedModel:()=>mc,Qwen2PreTrainedModel:()=>fc,Qwen2Tokenizer:()=>Lb,Qwen2VLForCausalLM:()=>gl,Qwen2VLForConditionalGeneration:()=>_l,Qwen2VLImageProcessor:()=>wh,Qwen2VLPreTrainedModel:()=>sf,Qwen2VLProcessor:()=>Ri,Qwen2_5_VLForCausalLM:()=>yl,Qwen2_5_VLForConditionalGeneration:()=>wl,Qwen2_5_VLProcessor:()=>Ah,Qwen3ForCausalLM:()=>MC,Qwen3Model:()=>bC,Qwen3MoeForCausalLM:()=>TC,Qwen3MoeModel:()=>xC,Qwen3MoePreTrainedModel:()=>gc,Qwen3NextForCausalLM:()=>kC,Qwen3NextModel:()=>EC,Qwen3NextPreTrainedModel:()=>wc,Qwen3PreTrainedModel:()=>_c,Qwen3VLForCausalLM:()=>vc,Qwen3VLForConditionalGeneration:()=>yc,Qwen3VLMoeForCausalLM:()=>kf,Qwen3VLMoeForConditionalGeneration:()=>CC,Qwen3VLProcessor:()=>bx,Qwen3_5ForCausalLM:()=>Mc,Qwen3_5ForConditionalGeneration:()=>bc,Qwen3_5MoeForCausalLM:()=>Cf,Qwen3_5MoeForConditionalGeneration:()=>AC,RFDetrForObjectDetection:()=>RC,RFDetrModel:()=>PC,RFDetrObjectDetectionOutput:()=>Af,RFDetrPreTrainedModel:()=>Tc,RTDetrForObjectDetection:()=>nT,RTDetrImageProcessor:()=>JM,RTDetrModel:()=>rT,RTDetrObjectDetectionOutput:()=>ms,RTDetrPreTrainedModel:()=>Ji,RTDetrV2ForObjectDetection:()=>jC,RTDetrV2Model:()=>GC,RTDetrV2ObjectDetectionOutput:()=>Sf,RTDetrV2PreTrainedModel:()=>Ec,RawAudio:()=>Xb,RawImage:()=>Mt,RawVideo:()=>$I,RawVideoFrame:()=>em,RepetitionPenaltyLogitsProcessor:()=>Bx,ResNetForImageClassification:()=>IC,ResNetModel:()=>SC,ResNetPreTrainedModel:()=>xc,RoFormerForMaskedLM:()=>UC,RoFormerForQuestionAnswering:()=>VC,RoFormerForSequenceClassification:()=>zC,RoFormerForTokenClassification:()=>$C,RoFormerModel:()=>BC,RoFormerPreTrainedModel:()=>Tn,RoFormerTokenizer:()=>Nb,RobertaForMaskedLM:()=>LC,RobertaForQuestionAnswering:()=>DC,RobertaForSequenceClassification:()=>FC,RobertaForTokenClassification:()=>NC,RobertaModel:()=>OC,RobertaPreTrainedModel:()=>xn,RobertaTokenizer:()=>Fb,Sam2ImageProcessor:()=>ii,Sam2ImageSegmentationOutput:()=>Rf,Sam2Model:()=>kc,Sam2PreTrainedModel:()=>Of,Sam2Processor:()=>Ih,Sam2VideoProcessor:()=>Mx,Sam3ImageProcessor:()=>ii,Sam3TrackerModel:()=>HC,SamImageProcessor:()=>ii,SamImageSegmentationOutput:()=>If,SamModel:()=>qC,SamPreTrainedModel:()=>Pf,SamProcessor:()=>Sh,SapiensFeatureExtractor:()=>XM,SapiensForDepthEstimation:()=>QC,SapiensForNormalEstimation:()=>JC,SapiensForSemanticSegmentation:()=>KC,SapiensImageProcessor:()=>Th,SapiensPreTrainedModel:()=>Fa,SeamlessM4TFeatureExtractor:()=>aM,SegformerFeatureExtractor:()=>YM,SegformerForImageClassification:()=>YC,SegformerForSemanticSegmentation:()=>ZC,SegformerImageProcessor:()=>Eh,SegformerModel:()=>XC,SegformerPreTrainedModel:()=>Na,SiglipImageProcessor:()=>ZM,SiglipModel:()=>eA,SiglipPreTrainedModel:()=>Cc,SiglipTextModel:()=>Lf,SiglipTokenizer:()=>Db,SiglipVisionModel:()=>tA,SmolLM3ForCausalLM:()=>nA,SmolLM3Model:()=>rA,SmolLM3PreTrainedModel:()=>Ac,SmolVLMImageProcessor:()=>Lp,SmolVLMProcessor:()=>Fp,SnacDecoderModel:()=>Nf,SnacEncoderModel:()=>Ff,SnacFeatureExtractor:()=>oM,SnacModel:()=>sA,SnacPreTrainedModel:()=>Da,SolarOpenForCausalLM:()=>oA,SolarOpenModel:()=>aA,SolarOpenPreTrainedModel:()=>Sc,SpeechT5FeatureExtractor:()=>iM,SpeechT5ForSpeechToText:()=>lA,SpeechT5ForTextToSpeech:()=>cA,SpeechT5HifiGan:()=>uA,SpeechT5Model:()=>iA,SpeechT5PreTrainedModel:()=>Ba,SpeechT5Processor:()=>xx,SpeechT5Tokenizer:()=>Bb,SqueezeBertForMaskedLM:()=>pA,SqueezeBertForQuestionAnswering:()=>fA,SqueezeBertForSequenceClassification:()=>hA,SqueezeBertModel:()=>dA,SqueezeBertPreTrainedModel:()=>bs,SqueezeBertTokenizer:()=>Ub,StableLmForCausalLM:()=>_A,StableLmModel:()=>mA,StableLmPreTrainedModel:()=>Ic,Starcoder2ForCausalLM:()=>wA,Starcoder2Model:()=>gA,Starcoder2PreTrainedModel:()=>Pc,StoppingCriteria:()=>hs,StoppingCriteriaList:()=>Rh,StyleTextToSpeech2Model:()=>yA,StyleTextToSpeech2PreTrainedModel:()=>Df,SummarizationPipeline:()=>gI,SupertonicForConditionalGeneration:()=>Uf,SupertonicPreTrainedModel:()=>Bf,SuppressTokensAtBeginLogitsProcessor:()=>Ph,Swin2SRForImageSuperResolution:()=>TA,Swin2SRImageProcessor:()=>ex,Swin2SRModel:()=>xA,Swin2SRPreTrainedModel:()=>Rc,SwinForImageClassification:()=>bA,SwinForSemanticSegmentation:()=>MA,SwinModel:()=>vA,SwinPreTrainedModel:()=>Ua,T5ForConditionalGeneration:()=>kA,T5Model:()=>EA,T5PreTrainedModel:()=>Oc,T5Tokenizer:()=>zb,TableTransformerForObjectDetection:()=>AA,TableTransformerModel:()=>CA,TableTransformerObjectDetectionOutput:()=>zf,TableTransformerPreTrainedModel:()=>Lc,TemperatureLogitsWarper:()=>Gx,Tensor:()=>q,Text2TextGenerationPipeline:()=>$c,TextClassificationPipeline:()=>hI,TextGenerationPipeline:()=>yI,TextStreamer:()=>zI,TextToAudioPipeline:()=>TI,TokenClassificationPipeline:()=>fI,TokenizersBackend:()=>le,TopKLogitsWarper:()=>dU,TopPLogitsWarper:()=>uU,TrOCRForCausalLM:()=>SA,TrOCRPreTrainedModel:()=>$f,TranslationPipeline:()=>wI,UltravoxModel:()=>Sl,UltravoxPreTrainedModel:()=>af,UltravoxProcessor:()=>Tx,UniSpeechForCTC:()=>PA,UniSpeechForSequenceClassification:()=>RA,UniSpeechModel:()=>IA,UniSpeechPreTrainedModel:()=>za,UniSpeechSatForAudioFrameClassification:()=>NA,UniSpeechSatForCTC:()=>LA,UniSpeechSatForSequenceClassification:()=>FA,UniSpeechSatModel:()=>OA,UniSpeechSatPreTrainedModel:()=>Ms,VLChatProcessor:()=>ux,VLMImageProcessor:()=>OM,VaultGemmaForCausalLM:()=>BA,VaultGemmaModel:()=>DA,VaultGemmaPreTrainedModel:()=>Fc,ViTFeatureExtractor:()=>tx,ViTForImageClassification:()=>$A,ViTImageProcessor:()=>kh,ViTMAEModel:()=>VA,ViTMAEPreTrainedModel:()=>Vf,ViTMSNForImageClassification:()=>jA,ViTMSNModel:()=>GA,ViTMSNPreTrainedModel:()=>Dc,ViTModel:()=>zA,ViTPreTrainedModel:()=>Nc,VisionEncoderDecoderModel:()=>UA,VitMatteForImageMatting:()=>qA,VitMatteImageProcessor:()=>rx,VitMattePreTrainedModel:()=>Gf,VitPoseForPoseEstimation:()=>WA,VitPoseImageProcessor:()=>nx,VitPosePreTrainedModel:()=>jf,VitsModel:()=>HA,VitsModelOutput:()=>qf,VitsPreTrainedModel:()=>Wf,VitsTokenizer:()=>$b,VoxtralForConditionalGeneration:()=>KA,VoxtralProcessor:()=>Ex,VoxtralRealtimeFeatureExtractor:()=>uM,VoxtralRealtimeForConditionalGeneration:()=>Kf,VoxtralRealtimePreTrainedModel:()=>Hf,VoxtralRealtimeProcessor:()=>kx,Wav2Vec2BertForCTC:()=>JA,Wav2Vec2BertForSequenceClassification:()=>XA,Wav2Vec2BertModel:()=>QA,Wav2Vec2BertPreTrainedModel:()=>$a,Wav2Vec2CTCTokenizer:()=>Vb,Wav2Vec2FeatureExtractor:()=>lM,Wav2Vec2ForAudioFrameClassification:()=>YE,Wav2Vec2ForCTC:()=>JE,Wav2Vec2ForSequenceClassification:()=>XE,Wav2Vec2Model:()=>QE,Wav2Vec2PreTrainedModel:()=>Mr,Wav2Vec2Processor:()=>Cx,Wav2Vec2ProcessorWithLM:()=>Ax,WavLMForAudioFrameClassification:()=>rS,WavLMForCTC:()=>ZA,WavLMForSequenceClassification:()=>eS,WavLMForXVector:()=>tS,WavLMModel:()=>YA,WavLMPreTrainedModel:()=>En,WeSpeakerFeatureExtractor:()=>cM,WeSpeakerResNetModel:()=>nS,WeSpeakerResNetPreTrainedModel:()=>Jf,WhisperFeatureExtractor:()=>dM,WhisperForConditionalGeneration:()=>Xf,WhisperModel:()=>sS,WhisperPreTrainedModel:()=>Bc,WhisperProcessor:()=>Sx,WhisperTextStreamer:()=>XU,WhisperTimeStampLogitsProcessor:()=>Nx,WhisperTokenizer:()=>jb,XLMForQuestionAnswering:()=>uS,XLMForSequenceClassification:()=>lS,XLMForTokenClassification:()=>cS,XLMModel:()=>oS,XLMPreTrainedModel:()=>kn,XLMRobertaForMaskedLM:()=>pS,XLMRobertaForQuestionAnswering:()=>mS,XLMRobertaForSequenceClassification:()=>hS,XLMRobertaForTokenClassification:()=>fS,XLMRobertaModel:()=>dS,XLMRobertaPreTrainedModel:()=>Cn,XLMRobertaTokenizer:()=>qb,XLMTokenizer:()=>Wb,XLMWithLMHeadModel:()=>iS,XVectorOutput:()=>Qf,YolosFeatureExtractor:()=>sx,YolosForObjectDetection:()=>gS,YolosImageProcessor:()=>Ch,YolosModel:()=>_S,YolosObjectDetectionOutput:()=>Yf,YolosPreTrainedModel:()=>Uc,YoutuForCausalLM:()=>yS,YoutuModel:()=>wS,YoutuPreTrainedModel:()=>zc,ZeroShotAudioClassificationPipeline:()=>MI,ZeroShotClassificationPipeline:()=>vI,ZeroShotImageClassificationPipeline:()=>AI,ZeroShotObjectDetectionPipeline:()=>II,cat:()=>Fe,cos_sim:()=>GD,dot:()=>Bv,env:()=>ge,full:()=>lt,full_like:()=>_i,interpolate:()=>Xp,interpolate_4d:()=>Nt,layer_norm:()=>lB,load_image:()=>NB,load_video:()=>YU,log_softmax:()=>Dv,matmul:()=>Jv,mean:()=>ki,mean_pooling:()=>Xv,ones:()=>xt,ones_like:()=>th,permute:()=>Qv,pipeline:()=>QU,quantize_embeddings:()=>Zv,rand:()=>cB,randn:()=>Yv,random:()=>ba,read_audio:()=>Kb,rfft:()=>iB,slice:()=>Yp,softmax:()=>rt,stack:()=>Fr,std_mean:()=>Zp,topk:()=>pn,zeros:()=>rh,zeros_like:()=>nh});function bv(e){return Object.keys(e).length===0}function cn(e,t){e&&e(t)}function _L(e){return Number.isInteger(e)||typeof e=="bigint"}function xy(e){return e==null||e===-1}function Ty(e){let t=[],r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function jt(...e){return Array.prototype.concat.apply([],e)}function gL(...e){return e.reduce((t,r)=>t.flatMap(n=>r.map(s=>[n,s])))}function pi(e,t){return Math.abs((e+t)%(2*t)-t)}function ot(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function wL(e,t){let r=0;for(let n of e)n===t&&++r;return r}function oF(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new NL(e);case"Precompiled":return new BL(e);case"Sequence":return new zL(e);case"Replace":return new VL(e);case"NFC":return new qL(e);case"NFD":return new HL(e);case"NFKC":return new QL(e);case"NFKD":return new XL(e);case"Strip":return new ZL(e);case"StripAccents":return new tF(e);case"Lowercase":return new nF(e);case"Prepend":return new aF(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}function IF(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new bF;case"Sequence":return new EF(e);case"Whitespace":return new dF;case"WhitespaceSplit":return new CF;case"Metaspace":return new hF(e);case"ByteLevel":return new cF(e);case"Split":return new mF(e);case"Punctuation":return new gF(e);case"Digits":return new yF(e);case"Replace":return new xF(e);case"FixedLength":return new SF(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}function DF(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}function WF(e,t){switch(e.type){case"WordPiece":return new Ay(e);case"Unigram":return new Iy(e,t.eos_token);case"BPE":return new Py(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Iy(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Py(e):new Ay(e):new qF(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}`)}}function aN(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new JF(e);case"ByteLevel":return new YF(e);case"BertProcessing":return new eN(e);case"RobertaProcessing":return new rN(e);case"Sequence":return new sN(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}function CN(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new lN(e);case"WordPiece":return new uN(e);case"Metaspace":return new pN(e);case"BPEDecoder":return new fN(e);case"CTC":return new _N(e);case"Sequence":return new wN(e);case"Replace":return new vN(e);case"Fuse":return new MN(e);case"Strip":return new TN(e);case"ByteFallback":return new kN(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}function Ry(e){return/\w/.test(e)}function Js(e){return/[0-9]/.test(e)}function Oy(e){return/\s/.test(e)}function RN(e,t={}){return e.endsWith(`
5
+ `)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function ON(e,t={}){let r=[],n=RN(e,t),s=0,a=0,o=c=>{let u="";for(;c(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");let p=n[s++],f=PN.get(p);if(f===void 0)throw new SyntaxError(`Unexpected escaped character: ${p}`);u+=f;continue}if(u+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===B.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;s<n.length&&Oy(n[s]);)++s};e:for(;s<n.length;){let c=r.at(-1)?.type;if(c===void 0||c===B.CloseStatement||c===B.CloseExpression||c===B.Comment){let p="";for(;s<n.length&&!(n[s]==="{"&&(n[s+1]==="%"||n[s+1]==="{"||n[s+1]==="#"));)p+=n[s++];if(p.length>0){r.push(new Ot(p,B.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;let p=n[s]==="-";p&&++s;let f="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");f+=n[s++]}let m=f.endsWith("-");m&&(f=f.slice(0,-1)),p&&i(),r.push(new Ot(f,B.Comment)),s+=2,m&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new Ot("{%",B.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new Ot("{{",B.OpenExpression)),a=0,s+=3;continue}if(o(Oy),n.slice(s,s+3)==="-%}"){r.push(new Ot("%}",B.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Ot("}}",B.CloseExpression)),s+=3,l();continue}let u=n[s];if(u==="-"||u==="+"){let p=r.at(-1)?.type;if(p===B.Text||p===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(p){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++s;let f=o(Js);r.push(new Ot(`${u}${f}`,f.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(let[p,f]of IN){if(p==="}}"&&a>0)continue;if(n.slice(s,s+p.length)===p){r.push(new Ot(p,f)),f===B.OpenExpression?a=0:f===B.OpenCurlyBracket?++a:f===B.CloseCurlyBracket&&--a,s+=p.length;continue e}}if(u==="'"||u==='"'){++s;let p=o(f=>f!==u);r.push(new Ot(p,B.StringLiteral)),++s;continue}if(Js(u)){let p=o(Js);if(n[s]==="."&&Js(n[s+1])){++s;let f=o(Js);p=`${p}.${f}`}r.push(new Ot(p,B.NumericLiteral));continue}if(Ry(u)){let p=o(Ry);r.push(new Ot(p,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}function nD(e){let t=new LN([]),r=0;function n(F,N){let z=e[r++];if(!z||z.type!==F)throw new Error(`Parser Error: ${N}. ${z.type} !== ${F}.`);return z}function s(F){if(!l(F))throw new SyntaxError(`Expected ${F}`);++r}function a(){switch(e[r].type){case B.Comment:return new $N(e[r++].value);case B.Text:return c();case B.OpenStatement:return u();case B.OpenExpression:return p();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...F){return r+F.length<=e.length&&F.every((N,z)=>N===e[r+z].type)}function i(...F){return e[r]?.type===B.OpenStatement&&e[r+1]?.type===B.Identifier&&F.includes(e[r+1]?.value)}function l(...F){return r+F.length<=e.length&&F.every((N,z)=>e[r+z].type==="Identifier"&&N===e[r+z].value)}function c(){return new Fy(n(B.Text,"Expected text token").value)}function u(){if(n(B.OpenStatement,"Expected opening statement token"),e[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);let F=e[r].value,N;switch(F){case"set":++r,N=f();break;case"if":++r,N=m(),n(B.OpenStatement,"Expected {% token"),s("endif"),n(B.CloseStatement,"Expected %} token");break;case"macro":++r,N=y(),n(B.OpenStatement,"Expected {% token"),s("endmacro"),n(B.CloseStatement,"Expected %} token");break;case"for":++r,N=x(),n(B.OpenStatement,"Expected {% token"),s("endfor"),n(B.CloseStatement,"Expected %} token");break;case"call":{++r;let z=null;o(B.OpenParen)&&(z=V());let Y=ie();if(Y.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let fe=V();n(B.CloseStatement,"Expected closing statement token");let H=[];for(;!i("endcall");)H.push(a());n(B.OpenStatement,"Expected '{%'"),s("endcall"),n(B.CloseStatement,"Expected closing statement token");let Ne=new Ly(Y,fe);N=new tD(Ne,z,H);break}case"break":++r,n(B.CloseStatement,"Expected closing statement token"),N=new DN;break;case"continue":++r,n(B.CloseStatement,"Expected closing statement token"),N=new BN;break;case"filter":{++r;let z=ie();z instanceof Qn&&o(B.OpenParen)&&(z=$(z)),n(B.CloseStatement,"Expected closing statement token");let Y=[];for(;!i("endfilter");)Y.push(a());n(B.OpenStatement,"Expected '{%'"),s("endfilter"),n(B.CloseStatement,"Expected '%}'"),N=new KN(z,Y);break}default:throw new SyntaxError(`Unknown statement type: ${F}`)}return N}function p(){n(B.OpenExpression,"Expected opening expression token");let F=M();return n(B.CloseExpression,"Expected closing expression token"),F}function f(){let F=v(),N=null,z=[];if(o(B.Equals))++r,N=v();else{for(n(B.CloseStatement,"Expected %} token");!i("endset");)z.push(a());n(B.OpenStatement,"Expected {% token"),s("endset")}return n(B.CloseStatement,"Expected closing statement token"),new UN(F,N,z)}function m(){let F=M();n(B.CloseStatement,"Expected closing statement token");let N=[],z=[];for(;!i("elif","else","endif");)N.push(a());if(i("elif")){++r,++r;let Y=m();z.push(Y)}else if(i("else"))for(++r,++r,n(B.CloseStatement,"Expected closing statement token");!i("endif");)z.push(a());return new FN(F,N,z)}function y(){let F=ie();if(F.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=V();n(B.CloseStatement,"Expected closing statement token");let z=[];for(;!i("endmacro");)z.push(a());return new zN(F,N,z)}function v(F=!1){let N=F?ie:M,z=[N()],Y=o(B.Comma);for(;Y&&(++r,z.push(N()),!!o(B.Comma)););return Y?new Ny(z):z[0]}function x(){let F=v(!0);if(!(F instanceof Qn||F instanceof Ny))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${F.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let N=M();n(B.CloseStatement,"Expected closing statement token");let z=[];for(;!i("endfor","else");)z.push(a());let Y=[];if(i("else"))for(++r,++r,n(B.CloseStatement,"Expected closing statement token");!i("endfor");)Y.push(a());return new NN(F,N,z,Y)}function M(){return T()}function T(){let F=A();if(l("if")){++r;let N=A();if(l("else")){++r;let z=T();return new rD(N,F,z)}else return new QN(F,N)}return F}function A(){let F=C();for(;l("or");){let N=e[r];++r;let z=C();F=new Xs(N,F,z)}return F}function C(){let F=S();for(;l("and");){let N=e[r];++r;let z=S();F=new Xs(N,F,z)}return F}function S(){let F;for(;l("not");){let N=e[r];++r;let z=S();F=new XN(N,z)}return F??O()}function O(){let F=E();for(;;){let N;if(l("not","in"))N=new Ot("not in",B.Identifier),r+=2;else if(l("in"))N=e[r++];else if(o(B.ComparisonBinaryOperator))N=e[r++];else break;let z=E();F=new Xs(N,F,z)}return F}function E(){let F=D();for(;o(B.AdditiveBinaryOperator);){let N=e[r];++r;let z=D();F=new Xs(N,F,z)}return F}function K(){let F=W(ie());return o(B.OpenParen)?$(F):F}function $(F){let N=new Ly(F,V());return N=W(N),o(B.OpenParen)&&(N=$(N)),N}function V(){n(B.OpenParen,"Expected opening parenthesis for arguments list");let F=Q();return n(B.CloseParen,"Expected closing parenthesis for arguments list"),F}function Q(){let F=[];for(;!o(B.CloseParen);){let N;if(e[r].type===B.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;let z=M();N=new eD(z)}else if(N=M(),o(B.Equals)){if(++r,!(N instanceof Qn))throw new SyntaxError("Expected identifier for keyword argument");let z=M();N=new ZN(N,z)}F.push(N),o(B.Comma)&&++r}return F}function G(){let F=[],N=!1;for(;!o(B.CloseSquareBracket);)o(B.Colon)?(F.push(void 0),++r,N=!0):(F.push(M()),o(B.Colon)&&(++r,N=!0));if(F.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(F.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new YN(...F)}return F[0]}function W(F){for(;o(B.Dot)||o(B.OpenSquareBracket);){let N=e[r];++r;let z,Y=N.type===B.OpenSquareBracket;if(Y)z=G(),n(B.CloseSquareBracket,"Expected closing square bracket");else if(z=ie(),z.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");F=new VN(F,z,Y)}return F}function D(){let F=R();for(;o(B.MultiplicativeBinaryOperator);){let N=e[r++],z=R();F=new Xs(N,F,z)}return F}function R(){let F=re();for(;l("is");){++r;let N=l("not");N&&++r;let z=ie();if(!(z instanceof Qn))throw new SyntaxError("Expected identifier for the test");F=new JN(F,N,z)}return F}function re(){let F=K();for(;o(B.Pipe);){++r;let N=ie();if(!(N instanceof Qn))throw new SyntaxError("Expected identifier for the filter");o(B.OpenParen)&&(N=$(N)),F=new HN(F,N)}return F}function ie(){let F=e[r++];switch(F.type){case B.NumericLiteral:{let N=F.value;return N.includes(".")?new jN(Number(N)):new GN(Number(N))}case B.StringLiteral:{let N=F.value;for(;o(B.StringLiteral);)N+=e[r++].value;return new Fy(N)}case B.Identifier:return new Qn(F.value);case B.OpenParen:{let N=v();return n(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case B.OpenSquareBracket:{let N=[];for(;!o(B.CloseSquareBracket);)N.push(M()),o(B.Comma)&&++r;return++r,new qN(N)}case B.OpenCurlyBracket:{let N=new Map;for(;!o(B.CloseCurlyBracket);){let z=M();n(B.Colon,"Expected colon between key and value in object literal");let Y=M();N.set(z,Y),o(B.Comma)&&++r}return++r,new WN(N)}default:throw new SyntaxError(`Unexpected token: ${F.type}`)}}for(;r<e.length;)t.body.push(a());return t}function sD(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");let n=[];if(r>0)for(let s=e;s<t;s+=r)n.push(s);else for(let s=e;s>t;s+=r)n.push(s);return n}function Dy(e,t,r,n=1){let s=Math.sign(n);s>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));let a=[];for(let o=t;s*o<s*r;o+=n)a.push(e[o]);return a}function aD(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function oD(e){return iD(new Date,e)}function iD(e,t){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),s=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return s(e.getMonth()+1);case"%d":return s(e.getDate());case"%b":return n.format(e);case"%B":return r.format(e);case"%H":return s(e.getHours());case"%M":return s(e.getMinutes());case"%%":return"%";default:return a}})}function lD(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function cD(e,t,r,n){if(n===0)return e;let s=n==null||n<0?1/0:n,a=t.length===0?new RegExp("(?=)","gu"):new RegExp(lD(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}function zy(e){return e.replace(uD,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function un(e,t={},r=0,n=!0){let{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t,l,c;switch(o?[l,c]=o:s?(l=",",c=": "):(l=", ",c=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let u=JSON.stringify(e.value);return a&&(u=zy(u)),u}case"ArrayValue":case"ObjectValue":{let u=s?" ".repeat(s):"",p=`
6
+ `+u.repeat(r),f=p+u;if(e.type==="ArrayValue"){let m=e.value.map(y=>un(y,t,r+1,n));return s?`[${f}${m.join(`${l}${f}`)}${p}]`:`[${m.join(l)}]`}else{let m=Array.from(e.value.entries());i&&(m=m.sort(([v],[x])=>v.localeCompare(x)));let y=m.map(([v,x])=>{let M=JSON.stringify(v);a&&(M=zy(M));let T=`${M}${c}${un(x,t,r+1,n)}`;return s?`${f}${T}`:T});return s?`{${y.join(l)}${p}}`:`{${y.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}function dD(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",sD),e.set("strftime_now",oD),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Vy(e,t){let r=t.split("."),n=e;for(let s of r)if(n instanceof tt)n=n.value.get(s)??new Oe;else if(n instanceof _e){let a=parseInt(s,10);if(!isNaN(a)&&a>=0&&a<n.value.length)n=n.value[a];else return new Oe}else return new Oe;return n}function Ap(e,t,r=!1){if(e instanceof Be&&t instanceof Be)return 0;if(e instanceof Be||t instanceof Be)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Oe&&t instanceof Oe)return 0;if(e instanceof Oe||t instanceof Oe)throw new Error(`Cannot compare ${e.type} with ${t.type}`);let n=a=>a instanceof de||a instanceof ze||a instanceof ae,s=a=>a instanceof ae?a.value?1:0:a.value;if(n(e)&&n(t)){let a=s(e),o=s(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}function ai(e){switch(typeof e){case"number":return Number.isInteger(e)?new de(e):new ze(e);case"string":return new Z(e);case"boolean":return new ae(e);case"undefined":return new Oe;case"object":return e===null?new Be:Array.isArray(e)?new _e(e.map(ai)):new tt(new Map(Object.entries(e).map(([t,r])=>[t,ai(r)])));case"function":return new Le((t,r)=>{let n=e(...t.map(s=>s.value))??null;return ai(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function mD(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function _D(e,t=" "){let r=typeof t=="number"?" ".repeat(t):t;return Wt(e.body,0,r).replace(/\n$/,"")}function it(...e){return hD+e.join(" ")+fD}function Wt(e,t,r){return e.map(n=>gD(n,t,r)).join(Ke)}function gD(e,t,r){let n=r.repeat(t);switch(e.type){case"Program":return Wt(e.body,t,r);case"If":return wD(e,t,r);case"For":return yD(e,t,r);case"Set":return vD(e,t,r);case"Macro":return bD(e,t,r);case"Break":return n+it("break");case"Continue":return n+it("continue");case"CallStatement":return MD(e,t,r);case"FilterStatement":return xD(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+we(e)+" -}}"}}function wD(e,t,r){let n=r.repeat(t),s=[],a=e;for(;a&&(s.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=n+it("if",we(s[0].test))+Ke+Wt(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=Ke+n+it("elif",we(s[i].test))+Ke+Wt(s[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=Ke+n+it("else")+Ke+Wt(a.alternate,t+1,r)),o+=Ke+n+it("endif"),o}function yD(e,t,r){let n=r.repeat(t),s="";if(e.iterable.type==="SelectExpression"){let o=e.iterable;s=`${we(o.lhs)} if ${we(o.test)}`}else s=we(e.iterable);let a=n+it("for",we(e.loopvar),"in",s)+Ke+Wt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Ke+n+it("else")+Ke+Wt(e.defaultBlock,t+1,r)),a+=Ke+n+it("endfor"),a}function vD(e,t,r){let n=r.repeat(t),s=we(e.assignee),a=e.value?we(e.value):"",o=n+it("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Ke+Wt(e.body,t+1,r)+Ke+n+it("endset")}function bD(e,t,r){let n=r.repeat(t),s=e.args.map(we).join(", ");return n+it("macro",`${e.name.value}(${s})`)+Ke+Wt(e.body,t+1,r)+Ke+n+it("endmacro")}function MD(e,t,r){let n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(we).join(", ")})`:"",a=we(e.call),o=n+it(`call${s}`,a)+Ke;return o+=Wt(e.body,t+1,r)+Ke,o+=n+it("endcall"),o}function xD(e,t,r){let n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:we(e.filter),a=n+it("filter",s)+Ke;return a+=Wt(e.body,t+1,r)+Ke,a+=n+it("endfilter"),a}function we(e,t=-1){switch(e.type){case"SpreadExpression":return`*${we(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{let r=e,n=mD(r),s=we(r.left,n),a=we(r.right,n+1),o=`${s} ${r.operator.value} ${a}`;return n<t?`(${o})`:o}case"UnaryExpression":{let r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+we(r.argument,1/0)}case"CallExpression":{let r=e,n=r.args.map(we).join(", ");return`${we(r.callee)}(${n})`}case"MemberExpression":{let r=e,n=we(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(n=`(${n})`);let s=we(r.property);return!r.computed&&r.property.type!=="Identifier"&&(s=`(${s})`),r.computed?`${n}[${s}]`:`${n}.${s}`}case"FilterExpression":{let r=e,n=we(r.operand,1/0);return r.filter.type==="CallExpression"?`${n} | ${we(r.filter)}`:`${n} | ${r.filter.value}`}case"SelectExpression":{let r=e;return`${we(r.lhs)} if ${we(r.test)}`}case"TestExpression":{let r=e;return`${we(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=e.value.map(we),n=e.type==="ArrayLiteral"?"[]":"()";return`${n[0]}${r.join(", ")}${n[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([n,s])=>`${we(n)}: ${we(s)}`).join(", ")}}`;case"SliceExpression":{let r=e,n=r.start?we(r.start):"",s=r.stop?we(r.stop):"",a=r.step?`:${we(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{let r=e;return`${r.key.value}=${we(r.value)}`}case"Ternary":{let r=e,n=`${we(r.trueExpr)} if ${we(r.condition,0)} else ${we(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}function Pv(e,t){let r=0;for(let s=0;s<t.length;++s)r+=t[s];let n=e()*r;for(let s=0;s<t.length;++s)if(n-=t[s],n<0)return s;return t.length-1}function Bo(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function ds(e,t=null,r=null){let n;try{n=new URL(e)}catch{return!1}return!(t&&!t.includes(n.protocol)||r&&!r.includes(n.hostname))}function ID(e){return!(!SD.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function PD(e,t,r){if(!r)return null;let n=AD[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function RD(e,t,r){let n=e.headers.get("Content-Length"),s=n?parseInt(n,10):r??0;n===null&&!r&&ce.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),o=0,i=e.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let p=o+u.length;if(p>s){s=p;let m=new Uint8Array(s);m.set(a),a=m}a.set(u,o),o=p;let f=o/s*100;return t({progress:f,loaded:o,total:s}),l()}return await l(),a}function jy(e){return ds(e,["blob:"])}function qy(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof ci<"u"&&ci.url)t=ci.url;else return e;return new URL(e,t).href}async function ps(e=null){let t=null;if(ge.useCustomCache){if(!ge.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ge.customCache.match||!ge.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=ge.customCache}if(!t&&ge.experimental_useCrossOriginStorage&&Hy.isAvailable()&&(t=new Hy),!t&&ge.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ge.cacheKey)}catch(r){ce.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ge.useFSCache){if(!pe.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new Rv(e??ge.cacheDir)}return t}async function LD(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}function Lv(e,t){let r=Ud.get(e);if(r!==void 0)return r;let n=t().then(s=>s,s=>(Ud.delete(e),Promise.reject(s)));return Ud.put(e,n),n}async function DD(e){if(!ds(e,["http:","https:"]))return null;let t=Fv(e);return t.set("Range","bytes=0-0"),ge.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function Ma(e,t,r={}){let n=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return Lv(n,()=>BD(e,t,r))}async function BD(e,t,r){let n=await ps(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=xa(e,t,r,n),l=await Ta(n,s,o);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(ge.allowLocalModels&&!ds(s,["http:","https:"]))try{let u=await ma(s);if(typeof u!="string"&&u.status!==404){let p=u.headers.get("content-length"),f=u.headers.get("content-type");return{exists:!0,size:p?parseInt(p,10):void 0,contentType:f||void 0,fromCache:!1}}}catch{}if(ge.allowRemoteModels&&!r.local_files_only&&i)try{let c=await DD(a);if(c&&c.status>=200&&c.status<300){let u,p=c.headers.get("content-type");if(c.status===206){let f=c.headers.get("content-range");if(f){let m=f.match(/bytes \d+-\d+\/(\d+)/);m&&(u=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let f=c.headers.get("content-length");u=f?parseInt(f,10):void 0}return{exists:!0,size:u,contentType:p||void 0,fromCache:!1}}}catch(c){ce.warn(`Unable to fetch file metadata for "${a}": ${c}`)}return{exists:!1,fromCache:!1}}async function ma(e){return ge.useFS&&!ds(e,["http:","https:","blob:"])?new fi(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ge.fetch(e,{headers:Fv(e)})}function Fv(e){let t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){let n=!!process.env?.TESTING_REMOTELY,s=ge.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),ds(e,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function xa(e,t,r={},n=null){let s=r.revision??"main",a=Bo(e,t),o=ID(e),i=o?Bo(ge.localModelPath,a):a,l=Bo(ge.remoteHost,ge.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),c=n instanceof Rv?s==="main"?a:Bo(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function Ta(e,t,r){if(e)return await LD(e,t,r)}async function UD(e,t,r,n,s,a,o={}){if(await r.match(n)===void 0)if(a){if(typeof s!="string"){let i=new Headers(s.headers);i.set("content-length",a.byteLength.toString()),await r.put(n,new Response(a,{headers:i})).catch(l=>{ce.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=o.progress_callback?l=>cn(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function zD(e,t,r=!0,n={},s=!1,a=null){let{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=xa(e,t,n,a),p,f=!1,m;m=await Ta(a,i,c);let y=m!==void 0;if(!y){if(ge.allowLocalModels)if(ds(o,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!ge.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{m=await ma(i),p=i}catch(T){ce.warn(`Unable to load from local path "${i}": "${T}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(n.local_files_only||!ge.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(m=await ma(l),m.status!==200)return PD(m.status,l,r);p=c}f=a&&typeof Response<"u"&&m instanceof Response&&m.status===200}cn(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(pe.IS_NODE_ENV&&s)){let M;if(typeof m!="string")if(!n.progress_callback)M=new Uint8Array(await m.arrayBuffer());else if(y&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))M=new Uint8Array(await m.arrayBuffer()),cn(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M.length,total:M.length});else{let T,A=m.headers.get("content-length");if(A)T=parseInt(A,10);else try{let C=await Ma(e,t,n);C.size&&(T=C.size)}catch{}M=await RD(m,C=>{cn(n.progress_callback,{status:"progress",name:e,file:t,...C})},T)}v=M}if(f&&p&&typeof m!="string"&&await UD(e,t,a,p,m,v,n),cn(n.progress_callback,{status:"done",name:e,file:t}),v){if(!pe.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(m instanceof fi)return m.filePath;let x=await a?.match(p);if(x instanceof fi)return x.filePath;if(x instanceof Response)return new Uint8Array(await x.arrayBuffer());if(typeof x=="string")return x;throw new Error("Unable to get model file path or buffer.")}async function mi(e,t,r=!0,n={},s=!1){if(!ge.allowLocalModels){if(n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!ge.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}cn(n.progress_callback,{status:"initiate",name:e,file:t});let a=await ps(n?.cache_dir);return await zD(e,t,r,n,s,a)}async function Nv(e,t,r=!0,n={}){let s=await mi(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function yr(e,t,r=!0,n={}){let s=await Nv(e,t,r,n);return s===null?{}:JSON.parse(s)}function $D(e,[t,r,n],[s,a],o="bilinear",i=!1){let l=a/n,c=s/r,u=new e.constructor(s*a*t),p=r*n,f=s*a;for(let m=0;m<s;++m)for(let y=0;y<a;++y){let v=m*a+y,x=(y+.5)/l-.5,M=(m+.5)/c-.5,T=Math.floor(x),A=Math.floor(M),C=Math.min(T+1,n-1),S=Math.min(A+1,r-1);T=Math.max(T,0),A=Math.max(A,0);let O=x-T,E=M-A,K=(1-O)*(1-E),$=O*(1-E),V=(1-O)*E,Q=O*E,G=A*n,W=S*n,D=G+T,R=G+C,re=W+T,ie=W+C;for(let F=0;F<t;++F){let N=F*p;u[F*f+v]=K*e[N+D]+$*e[N+R]+V*e[N+re]+Q*e[N+ie]}}return u}function VD(e,t,r){let n=new Array(r.length),s=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)s[i]=l,n[i]=t[r[i]],l*=n[i];let a=r.map((i,l)=>s[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let c=t.length-1,u=i;c>=0;--c)l+=u%t[c]*a[c],u=Math.floor(u/t[c]);o[l]=e[i]}return[o,n]}function rt(e){let t=Ge(e)[0],r=e.map(a=>Math.exp(a-t)),n=r.reduce((a,o)=>a+o,0);return r.map(a=>a/n)}function Dv(e){let t=Ge(e)[0],r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);let n=Math.log(r);return e.map(a=>a-t-n)}function Bv(e,t){let r=0;for(let n=0;n<e.length;++n)r+=e[n]*t[n];return r}function GD(e,t){let r=Bv(e,t),n=Ky(e),s=Ky(t);return r/(n*s)}function Ky(e){return Math.sqrt(e.reduce((t,r)=>t+r*r,0))}function Sp(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}function Ge(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]>t&&(t=e[n],r=n);return[t,r]}function Uv(e){return e>0&&(e&e-1)===0}function WD(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");let r=new e.constructor(e.length),n=new e.constructor(t),s=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-s;i<=s;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function da(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}function HD(e){let t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function KD(e){let t=e.length,r=e[0].length,n=[t+1,r+1],s=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));s[0][0]=0;let a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let u=1;u<n[1];++u)for(let p=1;p<n[0];++p){let f=s[p-1][u-1],m=s[p-1][u],y=s[p][u-1],v,x;f<m&&f<y?(v=f,x=0):m<f&&m<y?(v=m,x=1):(v=y,x=2),s[p][u]=e[p-1][u-1]+v,a[p][u]=x}for(let u=0;u<n[1];++u)a[0][u]=2;for(let u=0;u<n[0];++u)a[u][0]=1;let o=t,i=r,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}async function Vv(e){let t=e.split("/").pop(),r;try{if(r=await ps(),r){let s=await r.match(e);if(s)return s}}catch(s){ce.warn(`Failed to load ${t} from cache:`,s)}let n=await ge.fetch(e);if(!n.ok)throw new Error(`Failed to fetch ${t}: ${n.status} ${n.statusText}`);if(r)try{await r.put(e,n.clone())}catch(s){ce.warn(`Failed to cache ${t}:`,s)}return n}async function XD(e){let t=await Vv(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ce.warn("Failed to read WASM binary:",r),null}}async function YD(e){if(pe.IS_SERVICE_WORKER_ENV||pe.IS_CHROME_AVAILABLE)return e;let t=await Vv(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return ce.warn("Failed to read WASM factory:",r),null}}function Gv(e){return e<=Ft.DEBUG?0:e<=Ft.INFO?2:e<=Ft.WARNING||e<=Ft.ERROR?3:4}function rB(e=null){if(!e)return Ip;switch(e){case"auto":return Lt;case"gpu":return Lt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(Lt.includes(e))return[ZD[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Lt.join(", ")}.`)}async function nB(){if(Jn)return Jn;if(!(ge.useWasmCache&&typeof He?.wasm?.wasmPaths=="object"&&He?.wasm?.wasmPaths?.wasm&&He?.wasm?.wasmPaths?.mjs)){if(pe.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Jn=Promise.resolve(),Jn}return Jn=(async()=>{let t=He.wasm.wasmPaths,r=!1;await Promise.all([t.wasm&&!jy(t.wasm)?(async()=>{try{let n=await XD(qy(t.wasm));n&&(He.wasm.wasmBinary=n,r=!0)}catch(n){ce.warn("Failed to pre-load WASM binary:",n)}})():Promise.resolve(),t.mjs&&!jy(t.mjs)?(async()=>{try{let n=await YD(qy(t.mjs));n&&(He.wasm.wasmPaths.mjs=n)}catch(n){ce.warn("Failed to pre-load WASM factory:",n)}})():Promise.resolve()]),r||(He.wasm.wasmPaths.mjs=t.mjs)})(),Jn}async function jv(e,t,r){await nB();let n=Gv(ge.logLevel??Ft.WARNING),s=()=>tB.create(e,{logSeverityLevel:n,...t}),a=await(pe.IS_WEB_ENV?Jy=Jy.then(s):s());return a.config=r,a}async function qv(e,t){let r=()=>e.run(t);return pe.IS_WEB_ENV?Xy=Xy.then(r):r()}function Wv(e){return e instanceof as.Tensor}function Jp(){return He?.wasm?.proxy}function Hv(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${zd}).`),zd):zd}function Kv(e,t,r,{configDtype:n=null,warn:s}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===ft.auto){if(n){let l=typeof n=="string"?n:n?.[t];if(l&&l!==ft.auto&&ft.hasOwnProperty(l))return l}i=Zy[r]??Yy}else a&&ft.hasOwnProperty(a)?i=a:i=Zy[r]??Yy;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}function oB(e,t){let r=e.length,n=t.reduce((a,o)=>a*o);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let a=t.length-1;a>=0;a--)s=s.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return s[0]}function Qv(e,t){let[r,n]=VD(e.data,e.dims,t);return new q(e.type,r,n)}function Xp(e,[t,r],n="bilinear",s=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=$D(e.data,[a,o,i],[t,r],n,s);return new q(e.type,l,[a,t,r])}async function Nt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let n;if(t.length===2)n=[...e.dims.slice(0,2),...t];else if(t.length===3)n=[e.dims[0],...t];else if(t.length===4)n=t;else throw new Error("`size` must be of length 2, 3, or 4.");let s;if(r==="nearest")s=await dn.nearest_interpolate_4d;else if(r==="bilinear")s=await dn.bilinear_interpolate_4d;else if(r==="bicubic")s=await dn.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let a=new q("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await s({x:e,s:a})}async function Jv(e,t){return await(await dn.matmul)({a:e,b:t})}async function iB(e,t){return await(await dn.rfft)({x:e,a:t})}async function pn(e,t){let r=await dn.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new q("int64",[BigInt(t)],[1])})}async function Yp(e,t,r,n,s){return await(await dn.slice)({x:e,s:Uo(t),e:Uo(r),a:Uo(n),t:Uo(s??new Array(n.length).fill(1))})}function Xv(e,t){let r=e.data,n=t.data,s=[e.dims[0],e.dims[2]],a=new r.constructor(s[0]*s[1]),[o,i,l]=e.dims,c=0;for(let u=0;u<o;++u){let p=u*l*i;for(let f=0;f<l;++f){let m=0,y=0,v=u*i,x=p+f;for(let T=0;T<i;++T){let A=Number(n[v+T]);y+=A,m+=r[x+T*l]*A}let M=m/y;a[c++]=M}}return new q(e.type,a,s)}function lB(e,t,{eps:r=1e-5}={}){if(e.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[n,s]=e.dims;if(t.length!==1&&t[0]!==s)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[a,o]=Zp(e,1,0,!0),i=a.data,l=o.data,c=e.data,u=new c.constructor(c.length);for(let p=0;p<n;++p){let f=p*s;for(let m=0;m<s;++m){let y=f+m;u[y]=(c[y]-l[p])/(i[p]+r)}}return new q(e.type,u,e.dims)}function ev(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,n)=>r!==1||!t.includes(n))),e}function tv(e,t){return t=sr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function sr(e,t,r=null,n=!0){if(e<-t||e>=t){if(n)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Fe(e,t=0){t=sr(t,e[0].dims.length);let r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);let n=r.reduce((o,i)=>o*i,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let o=0;for(let i of e){let l=i.data;s.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){let{data:l,dims:c}=e[i];for(let u=0;u<l.length;++u){let p=0;for(let f=c.length-1,m=u,y=1;f>=0;--f){let v=c[f],x=m%v;f===t&&(x+=o),p+=x*y,y*=r[f],m=Math.floor(m/v)}s[p]=l[u]}o+=c[t]}}return new q(a,s,r)}function Fr(e,t=0){return Fe(e.map(r=>r.unsqueeze(t)),t)}function pa(e,t,r,n=!1,s=null){let a=t.data,o=t.dims;r=sr(r,o.length);let i=o.slice();i[r]=1;let l=new a.constructor(a.length/o[r]);s!==null&&l.fill(s);for(let c=0;c<a.length;++c){let u=0;for(let p=o.length-1,f=c,m=1;p>=0;--p){let y=o[p];if(p!==r){let v=f%y;u+=v*m,m*=i[p]}f=Math.floor(f/y)}l[u]=e(l[u],a[c],c,u)}return n||i.splice(r,1),[t.type,l,i]}function Zp(e,t=null,r=1,n=!1){let s=e.data,a=e.dims;if(t===null){let m=s.reduce((M,T)=>M+T,0)/s.length,y=Math.sqrt(s.reduce((M,T)=>M+(T-m)**2,0)/(s.length-r)),v=new q(e.type,[m],[]);return[new q(e.type,[y],[]),v]}t=sr(t,a.length);let o=ki(e,t,n),i=o.data,[l,c,u]=pa((f,m,y,v)=>f+(m-i[v])**2,e,t,n);for(let f=0;f<c.length;++f)c[f]=Math.sqrt(c[f]/(a[t]-r));return[new q(l,c,u),o]}function ki(e,t=null,r=!1){let n=e.dims,s=e.data;if(t===null){let l=s.reduce((c,u)=>c+u,0);return new q(e.type,[l/s.length],[])}t=sr(t,n.length);let[a,o,i]=pa((l,c)=>l+c,e,t,r);if(n[t]!==1)for(let l=0;l<o.length;++l)o[l]/=n[t];return new q(a,o,i)}function $d(e){let t=new Array(e.length);for(let r=e.length-1,n=1;r>=0;--r)t[r]=n,n*=e[r];return t}function eh(e,t,r,n){let s=e.reduce((a,o)=>a*o,1);return new q(r,new n(s).fill(t),e)}function lt(e,t){let r,n;if(typeof t=="number")r="float32",n=Float32Array;else if(typeof t=="bigint")r="int64",n=BigInt64Array;else if(typeof t=="boolean")r="bool",n=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return eh(e,t,r,n)}function _i(e,t){return lt(e.dims,t)}function xt(e){return eh(e,1n,"int64",BigInt64Array)}function th(e){return xt(e.dims)}function rh(e){return eh(e,0n,"int64",BigInt64Array)}function nh(e){return rh(e.dims)}function cB(e){let t=e.reduce((r,n)=>r*n,1);return new q("float32",Float32Array.from({length:t},()=>ba.random()),e)}function Yv(e){let t=e.reduce((r,n)=>r*n,1);return new q("float32",Float32Array.from({length:t},()=>ba.gauss()),e)}function Zv(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'");let r=t==="binary",n=r?"int8":"uint8",s=r?Int8Array:Uint8Array,a=e.data,o=new s(a.length/8);for(let i=0;i<a.length;++i){let l=a[i]>0?1:0,c=Math.floor(i/8),u=i%8;o[c]|=l<<7-u,r&&u===0&&(o[c]-=128)}return new q(n,o,[e.dims[0],e.dims[1]/8])}async function sh(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await Ma(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function eb(e,t){let r=await sh(e);return await Promise.all(r.map(n=>yr(e,n,!0,t)))}function tb(e){let 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}.`)}}function dB(e,t,r,n){for(let s of Object.keys(e)){let a=t-e[s].length,o=r(s),i=new Array(a).fill(o);e[s]=n==="right"?jt(e[s],i):jt(i,e[s])}}function pB(e,t){for(let r of Object.keys(e))e[r].length=t}function sn(e,...t){for(let r of t){if(!Object.hasOwn(e,r))continue;let n=e[r];if(n)if(typeof n=="object"){if(n.__type==="AddedToken")return n.content;throw Error(`Unknown token: ${n}`)}else return n}return null}function hB(e){let t=[];for(let r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}function ah(e,t,r,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let s=n.src_lang,a=n.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(s!==void 0){if(!e.language_codes.includes(s))throw new Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(s);break}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}function _B(e){e=e.toLowerCase();let t=mB.get(e);if(t===void 0){let r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),oi.has(e))t=e;else{let s=e.length===2?oi.keys():oi.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}function bt(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}async function Hb(e,t){if(pe.IS_BROWSER_ENV){if(pe.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(r)}else if(pe.IS_FS_AVAILABLE){let r=t.stream(),n=bB.fromWeb(r),s=At.createWriteStream(e);await xB(n,s)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Kb(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await ma(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});typeof t>"u"&&ce.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);let s=await n.decodeAudioData(r),a;if(s.numberOfChannels===2){let o=Math.sqrt(2),i=s.getChannelData(0),l=s.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<s.length;++c)a[c]=o*(i[c]+l[c])/2}else a=s.getChannelData(0);return a}function Qb(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);let r=1-t,n=2*Math.PI/(e-1),s=new Float64Array(e);for(let a=0;a<e;++a)s[a]=t-r*Math.cos(a*n);return s}function nv(e){return Qb(e,.5)}function TB(e){return Qb(e,.54)}function Vd(e,t="htk"){let r=EB[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}function CB(e,t="htk"){let r=kB[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}function AB(e,t){let r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),n=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){let i=n[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}let s=t.length-2,a=Array.from({length:s},()=>new Array(e.length));for(let o=0;o<e.length;++o){let i=n[o];for(let l=0;l<s;++l){let c=-i[l]/r[l],u=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,u))}}return a}function sv(e,t,r){let n=(t-e)/(r-1);return Float64Array.from({length:r},(s,a)=>e+n*a)}function or(e,t,r,n,s,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>n)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${n}`);let l=Vd(r,o),c=Vd(n,o),u=sv(l,c,t+2),p=CB(u,o),f;if(i){let y=s/((e-1)*2);f=Vd(Float64Array.from({length:e},(v,x)=>x*y),o),p=u}else f=sv(0,Math.floor(s/2),e);let m=AB(f,p);if(a!==null&&a==="slaney")for(let y=0;y<t;++y){let v=m[y],x=2/(p[y+2]-p[y]);for(let M=0;M<e;++M)v[M]*=x}return m}function SB(e,t,r){let n=new e.constructor(e.length+t+r),s=e.length-1;for(let a=0;a<e.length;++a)n[t+a]=e[a];for(let a=1;a<=t;++a)n[t-a]=e[pi(a,s)];for(let a=1;a<=r;++a)n[s+t+a]=e[pi(s-a,s)];return n}function Jb(e,t,r,n,s){if(r<=0)throw new Error("reference must be greater than zero");if(n<=0)throw new Error("min_value must be greater than zero");r=Math.max(n,r);let a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(n,e[o])-a);if(s!==null){if(s<=0)throw new Error("db_range must be greater than zero");let o=Ge(e)[0]-s;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function IB(e,t=1,r=1e-5,n=null){return Jb(e,20,t,r,n)}function PB(e,t=1,r=1e-10,n=null){return Jb(e,10,t,r,n)}async function vr(e,t,r,n,{fft_length:s=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:u=!0,mel_filters:p=null,mel_floor:f=1e-10,log_mel:m=null,max_log_mel:y=null,reference:v=1,min_value:x=1e-10,db_range:M=null,remove_dc_offset:T=null,min_num_frames:A=null,max_num_frames:C=null,do_pad:S=!0,transpose:O=!1,mel_offset:E=0}={}){let K=t.length;if(s===null&&(s=r),r>s)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(K!==r)throw new Error(`Length of the window (${K}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&p!==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(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o)switch(i){case"reflect":{let z=Math.floor((s-1)/2)+1;e=SB(e,z,z);break}case"constant":{let z=Math.floor(s/2),Y=new e.constructor(e.length+2*z);Y.set(e,z),e=Y;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let $=Math.floor(1+Math.floor((e.length-r)/n));A!==null&&$<A&&($=A);let V=l?Math.floor(s/2)+1:s,Q=$,G=$;C!==null&&(C>$?S&&(G=C):G=Q=C);let W=new qD(s),D=new Float64Array(s),R=new Float64Array(W.outputBufferSize),re=new Float32Array(V*G);for(let z=0;z<Q;++z){let Y=z*n,fe=Math.min(e.length-Y,r);fe!==r&&D.fill(0,0,r);for(let H=0;H<fe;++H)D[H]=e[Y+H];if(T){let H=0;for(let Xe=0;Xe<fe;++Xe)H+=D[Xe];let Ne=H/fe;for(let Xe=0;Xe<fe;++Xe)D[Xe]-=Ne}if(c!==null){for(let H=fe-1;H>=1;--H)D[H]-=c*D[H-1];D[0]*=1-c}for(let H=0;H<t.length;++H)D[H]*=t[H];W.realTransform(R,D);for(let H=0;H<V;++H){let Ne=H<<1;re[H*G+z]=R[Ne]**2+R[Ne+1]**2}}if(a!==null&&a!==2){let z=a/2;for(let Y=0;Y<re.length;++Y)re[Y]**=z}let ie=p.length,F=await Jv(new q("float32",p.flat(),[ie,V]),new q("float32",re,[V,G]));O&&(F=F.transpose(1,0));let N=F.data;for(let z=0;z<N.length;++z)N[z]=E+Math.max(f,N[z]);if(a!==null&&m!==null){let z=Math.min(N.length,Q*ie);switch(m){case"log":for(let Y=0;Y<z;++Y)N[Y]=Math.log(N[Y]);break;case"log10":for(let Y=0;Y<z;++Y)N[Y]=Math.log10(N[Y]);break;case"log10_max_norm":{for(let H=0;H<z;++H)N[H]=Math.log10(N[H]);let fe=(y??Ge(N)[0])-8;for(let H=0;H<z;++H)N[H]=(Math.max(N[H],fe)+4)/4;break}case"dB":if(a===1)IB(N,v,x,M);else if(a===2)PB(N,v,x,M);else throw new Error(`Cannot use log_mel option '${m}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${m}'`)}}return F}function br(e,t,{periodic:r=!0,frame_length:n=null,center:s=!0}={}){let a=r?e+1:e,o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=nv(a);break;case"hamming":o=TB(a);break;case"povey":o=nv(a).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),n===null)return o;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);return o}function RB(e,t){let r=e.reduce((a,o)=>a+o.length,0),n=new ArrayBuffer(44),s=new DataView(n);return zo(s,0,"RIFF"),s.setUint32(4,36+r*4,!0),zo(s,8,"WAVE"),zo(s,12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,1,!0),s.setUint32(24,t,!0),s.setUint32(28,t*4,!0),s.setUint16(32,4,!0),s.setUint16(34,32,!0),zo(s,36,"data"),s.setUint32(40,r*4,!0),new Blob([n,...e.map(a=>a.buffer)],{type:"audio/wav"})}function zo(e,t,r){for(let n=0;n<r.length;++n)e.setUint8(t+n,r.charCodeAt(n))}function av(e,t,r=0,n=null){let s=e/t,a=HD(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),a<r&&(a=Math.ceil(s)*t),a}function ov([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function fM([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function Ai(e,t=.5,r=null,n=!1){let s=e.logits,a=e.pred_boxes,[o,i,l]=s.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let u=0;u<o;++u){let p=r!==null?r[u]:null,f={boxes:[],classes:[],scores:[]},m=s[u],y=a[u];for(let v=0;v<i;++v){let x=m[v],M=[],T;if(n){T=x.sigmoid().data;for(let A=0;A<T.length;++A)T[A]>t&&M.push(A)}else{let A=Ge(x.data)[1];if(A===l-1||(T=rt(x.data),T[A]<t))continue;M.push(A)}for(let A of M){let C=y[v].data;C=fM(C),p!==null&&(C=C.map((S,O)=>S*p[(O+1)%2])),f.boxes.push(C),f.classes.push(A),f.scores.push(T[A])}}c.push(f)}return c}function mM(e,t=null){let r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let s=[];for(let a=0;a<n;++a){let o=t!==null?t[a]:null,i=r[a];o!==null&&(i=Xp(i,o,"bilinear",!1));let[l,c]=o??i.dims.slice(-2),u=new q("int32",new Int32Array(l*c),[l,c]),p=i[0].data,f=u.data;for(let v=1;v<i.dims[0];++v){let x=i[v].data;for(let M=0;M<x.length;++M)x[M]>p[M]&&(p[M]=x[M],f[M]=v)}let m=new Array(i.dims[0]);for(let v=0;v<f.length;++v){let x=f[v];m[x]=x}let y=m.filter(v=>v!==void 0);s.push({segmentation:u,labels:y})}return s}function DB(e,t,r,n){let s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){let l=e[i],c=t[i],u=Ge(l.data)[1];if(u===n)continue;let f=rt(l.data)[u];f>r&&(s.push(c),a.push(f),o.push(u))}return[s,a,o]}function BB(e,t,r,n=.5,s=.8){let a=[],o=0,i=0,l=t[r].data;for(let u=0;u<e.length;++u)e[u]===r&&(a.push(u),++o),l[u]>=n&&++i;let c=o>0&&i>0;return c&&(c=o/i>s),[c,a]}function UB(e,t,r,n,s,a=null,o=null){let[i,l]=o??e[0].dims,c=new q("int32",new Int32Array(i*l),[i,l]),u=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=Xp(e[v],o,"bilinear",!1);let p=new Int32Array(e[0].data.length),f=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let x=t[v],M=e[v].data;for(let T=0;T<M.length;++T)M[T]*=x,M[T]>f[T]&&(p[T]=v,f[T]=M[T])}let m=0,y=c.data;for(let v=0;v<r.length;++v){let x=r[v],[M,T]=BB(p,e,v,n,s);if(M){++m;for(let A of T)y[A]=m;u.push({id:m,label_id:x,score:t[v]})}}return[c,u]}function ph(e,t,r=28,n=56*56,s=14*14*4*1280,a=1){if(e<r||t<r){let l=Math.max(r/e,r/t);e=Math.round(e*l),t=Math.round(t*l)}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>s){let l=Math.sqrt(a*e*t/s);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r)}else if(a*o*i<n){let l=Math.sqrt(n/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function _M(e,t=.5,r=.5,n=.8,s=null,a=null){s===null&&(ce.warn("`label_ids_to_fuse` unset. No instance will be fused."),s=new Set);let o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid(),[c,u,p]=o.dims;if(p-=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 f=[];for(let m=0;m<c;++m){let y=a!==null?a[m]:null,v=o[m],x=l[m],[M,T,A]=DB(v,x,t,p);if(A.length===0){let[O,E]=y??x.dims.slice(-2),K=new q("int32",new Int32Array(O*E).fill(-1),[O,E]);f.push({segmentation:K,segments_info:[]});continue}let[C,S]=UB(M,T,A,r,n,s,y);f.push({segmentation:C,segments_info:S})}return f}function gM(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}function iv(e,t){return Math.round(e/t)*t}function zB(e,t,r,n,s){let a=1/0,o=[1,1],i=r*n;for(let l of t){let c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*s*s*l[0]*l[1]&&(o=l)}return o}function $B(e,t){let r=[],n=new Set;for(let s=e;s<=t;++s)for(let a=1;a<=s;++a)for(let o=1;o<=s;++o){let i=a*o;if(i>=e&&i<=t){let l=a<<16|o;n.has(l)||(n.add(l),r.push([a,o]))}}return r.sort((s,a)=>s[0]*s[1]-a[0]*a[1])}function VB(e,t){let[r,n,s,a]=e.dims,o=Math.floor(s/t),i=Math.floor(a/t),l=t*t*n,c=e.data,u=new Float32Array(r*o*i*l),p=s*a;for(let f=0;f<r;++f){let m=f*n*p,y=f*o*i*l;for(let v=0;v<o;++v)for(let x=0;x<i;++x){let M=y+(v*i+x)*l;for(let T=0;T<t;++T){let A=(v*t+T)*a+x*t;for(let C=0;C<t;++C){let S=A+C;for(let O=0;O<n;++O)u[M++]=c[m+O*p+S]}}}}return new q("float32",u,[r,o*i,l])}function GB(e,t){let[,r,n]=e.dims,s=new BigInt64Array(t);s.fill(1n,0,r);let a=e;if(r<t){let o=new Float32Array(t*n);o.set(e.data),a=new q("float32",o,[1,t,n])}return{padded:a,mask:new q("int64",s,[t])}}function qB(e,t){let n=e.dims.at(-1)-1,s=e.tolist();s.fill(!1,0,1),s.fill(!1,n);let a=t.tolist();return s.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}function WB(e,t,r,n,s,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=n+`<row_${i+1}_col_${l+1}>`+s.repeat(e);o+=`
7
+ `}return o+=`
8
+ ${n}${a}`+s.repeat(e)+`${n}`,o}function HB(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function KB(e,t,r,n,s,a){return e===0&&t===0?HB(r,n,s,a):WB(r,e,t,n,s,a)}function QB(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
9
+ `}function ZB(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.subarray(n,Math.min(n+t,e.length)));return r}async function rU(e,t){return await yr(e,"config.json",!0,t)}function Zn(e){let t={},r={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=Zn(e.text_config);break;case"moondream1":r=Zn(e.phi_config);break;case"musicgen":r=Zn(e.decoder);break;case"multi_modality":r=Zn(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"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let s=Zn(e.decoder),a="num_decoder_layers"in s,o=ot(e,["model_type","is_encoder_decoder"]);return a?(o.num_decoder_layers=s.num_decoder_layers,o.num_decoder_heads=s.num_decoder_heads,o.decoder_hidden_size=s.decoder_hidden_size,o.num_encoder_layers=s.num_encoder_layers,o.num_encoder_heads=s.num_encoder_heads,o.encoder_hidden_size=s.encoder_hidden_size):(o.num_layers=s.num_layers,o.num_heads=s.num_heads,o.hidden_size=s.hidden_size),o}let n={...r,...ot(e,["model_type","multi_query","is_encoder_decoder"])};for(let s in t)n[s]=e[t[s]];return n}function Oi(e,t){e instanceof wi||(e=new wi(e));let r=t?.batch_size??1;if(["lfm2","lfm2_moe"].includes(e.model_type)){let n=t?.prefix??"past_key_values",s=n==="present"?"present":"past",a={},{layer_types:o,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,conv_L_cache:u}=e,p=c/i;for(let f=0;f<o.length;++f)if(o[f]==="full_attention")for(let m of["key","value"])a[`${n}.${f}.${m}`]=[r,l,0,p];else if(o[f]==="conv")a[`${s}_conv.${f}`]=[r,c,u];else throw new Error(`Unsupported layer type: ${o[f]}`);return a}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){let n=t?.prefix??"past_key_values",s=n==="present"?"present":"past",a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??o?.length,l=a.num_key_value_heads,c=a.head_dim??a.hidden_size/a.num_attention_heads,u=a.mamba_n_heads??a.mamba_num_heads,p=a.mamba_d_head??a.mamba_head_dim,f=a.mamba_d_state??a.ssm_state_size,m=a.mamba_n_groups??a.n_groups,y=a.mamba_d_conv??a.conv_kernel,x=(a.mamba_d_ssm??(a.mamba_expand?a.mamba_expand*a.hidden_size:u*p))+2*m*f,M={};for(let T=0;T<i;++T)if((!o||o[T]==="mamba")&&(M[`${s}_conv.${T}`]=[r,x,y],M[`${s}_ssm.${T}`]=[r,u,p,f]),!o||o[T]==="attention")for(let A of["key","value"])M[`${n}.${T}.${A}`]=[r,l,0,c];return M}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){let n=t?.prefix??"past_key_values",s=n==="present"?"present":"past",a={},{head_dim:o,layer_types:i,num_attention_heads:l,num_key_value_heads:c,hidden_size:u,linear_num_value_heads:p,linear_num_key_heads:f,linear_key_head_dim:m,linear_value_head_dim:y,linear_conv_kernel_dim:v}=e,x=m*f,M=y*p,T=o??u/l;for(let A=0;A<i.length;++A)if(i[A]==="full_attention")for(let C of["key","value"])a[`${n}.${A}.${C}`]=[r,c,0,T];else if(i[A]==="linear_attention"){if(e.model_type==="olmo_hybrid")a[`${s}_conv.${A}.key`]=[r,x,v],a[`${s}_conv.${A}.value`]=[r,M,v],a[`${s}_conv.${A}.query`]=[r,x,v];else{let C=x*2+M;a[`${s}_conv.${A}`]=[r,C,v]}a[`${s}_recurrent.${A}`]=[r,p,m,y]}else throw new Error(`Unsupported layer type: ${i[A]}`);return a}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let n;return e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder"?n=e.audio_config:n=e.text_config,Oi(n,t)}return nU(e,t)}function nU(e,{prefix:t="past_key_values",batch_size:r=1}={}){let n={},s=e.normalized_config;if(s.is_encoder_decoder&&"num_encoder_heads"in s&&"num_decoder_heads"in s){let a=s.encoder_dim_kv??s.encoder_hidden_size/s.num_encoder_heads,o=s.decoder_dim_kv??s.decoder_hidden_size/s.num_decoder_heads,i=[r,s.num_encoder_heads,0,a],l=[r,s.num_decoder_heads,0,o];for(let c=0;c<s.num_decoder_layers;++c)n[`${t}.${c}.encoder.key`]=i,n[`${t}.${c}.encoder.value`]=i,n[`${t}.${c}.decoder.key`]=l,n[`${t}.${c}.decoder.value`]=l}else{let a=s.num_heads,o=s.num_layers,i=s.dim_kv??s.hidden_size/(s.num_attention_heads??a);if(s.model_type==="falcon"){let l=[r*a,0,i];for(let c=0;c<o;++c)n[`${t}.${c}.key`]=l,n[`${t}.${c}.value`]=l}else if(s.multi_query){let l=[r*a,0,2*i];for(let c=0;c<o;++c)n[`${t}.${c}.key_value`]=l}else if(s.model_type==="bloom"){let l=[r*a,i,0],c=[r*a,0,i];for(let u=0;u<o;++u)n[`${t}.${u}.key`]=l,n[`${t}.${u}.value`]=c}else if(s.model_type==="openelm")for(let l=0;l<o;++l){let c=[r,a[l],0,i];n[`${t}.${l}.key`]=c,n[`${t}.${l}.value`]=c}else{let l=[r,a,0,i];for(let c=0;c<o;++c)n[`${t}.${c}.key`]=l,n[`${t}.${c}.value`]=l}}return n}function Px(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function Rx(e,t){let r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function sU(e,t,r,n){let s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await mi(e,a,!0,r,pe.IS_NODE_ENV)}async function aU(e,t,r,n,s,a={}){let o=`${t}${r}.onnx`,i=pe.IS_NODE_ENV,l=[],c=Px(s,o,t);if(c>0){if(c>Gy)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Gy}).`);let u=Rx(o,c);for(let p of u){let f=`${n.subfolder??""}/${p}`;l.push(new Promise(async(m,y)=>{let v=await mi(e,f,!0,n,i);m(v instanceof Uint8Array?{path:p,data:v}:p)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async u=>{if(typeof u.data=="string"){let p=await mi(e,u.data,!0,n);return{...u,data:p}}return u}));return Promise.all(l)}async function oU(e,t,r,n=!1,s=void 0){let a=r.config?.["transformers.js_config"]??{},o=Hv(r.device??a.device,t,{warn:C=>ce.info(C)}),i=rB(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});let c=Kv(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:C=>ce.info(C)});if(Pp.hasOwnProperty(c)){if(o==="webgpu"&&!pe.IS_NODE_ENV&&c===ft.fp16&&!await aB())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(ft).join(", ")}`);let u=a.kv_cache_dtype,p=u?typeof u=="string"?u:u[c]??"float32":void 0;if(p&&!["float32","float16"].includes(p))throw new Error(`Invalid kv_cache_dtype: ${p}. Should be one of: float32, float16`);let f=Pp[c],m={...r.session_options};m.executionProviders??(m.executionProviders=i);let y=a.free_dimension_overrides;y?m.freeDimensionOverrides??(m.freeDimensionOverrides=y):o.startsWith("webnn")&&!m.freeDimensionOverrides&&ce.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let v=sU(e,t,r,f),x=r.use_external_data_format??a.use_external_data_format,M=await aU(e,t,f,r,x,m);if(M.length>0&&!pe.IS_NODE_ENV&&(m.externalData=M),n&&o==="webgpu"&&u!==!1){let C=Oi(r.config,{prefix:"present",session_name:s});if(Object.keys(C).length>0&&!Jp()){let S={};for(let O in C)S[O]="gpu-buffer";m.preferredOutputLocation=S}}return{buffer_or_path:await v,session_options:m,session_config:{dtype:c,kv_cache_dtype:p,device:o}}}async function iU(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{let a=n?.[s]??!1,{buffer_or_path:o,session_options:i,session_config:l}=await oU(e,t[s],r,a,s),c=await jv(o,i,l);return[s,c]})))}function Ox(e){for(let t in e)Wv(e[t])?e[t]=new q(e[t]):typeof e[t]=="object"&&Ox(e[t]);return e}async function be(e,t){let r=lU(e,t);try{let n=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i=o.ort_tensor;return pe.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await qv(e,n);return Ox(s)}catch(n){let s=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw ce.error(`An error occurred during model execution: "${n}".`),ce.error("Inputs given to model:",s),n}}function lU(e,t){let r=Object.create(null),n=[];for(let o of e.inputNames){let i=t[o];if(!(i instanceof q)){n.push(o);continue}r[o]=Jp()?i.clone():i}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);let s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ce.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}function gU(e){es=e}function Dp(e){if(e instanceof q)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 q("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new q("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function Kx(e){return new q("bool",[e],[1])}function wU(e,t,r={}){let n=ts[e]??ts.default;return{sessions:n.sessions(t,r),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}async function Go(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,...a}=t;if(!r){let o=ot(t,e.sessions.model.inputNames);r=(await Lr(e,o)).last_hidden_state}return a.input_ids=s,a.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=t.attention_mask),await _r(e,a,!0)}async function Lr(e,t){let r=e.sessions.model,n=ot(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=nh(n.input_ids)}if(r.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let s=n.pixel_values.dims;n.pixel_mask=xt([s[0],s[2],s[3]])}return await be(r,n)}async function yU(e,t){let r=await e.encode(t);return await e.decode(r)}async function _r(e,t,r=!1){let n=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:s,...a}=t;if(n.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=Kx(!!s)),n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=bU(a,s,i)}n.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new q("int64",[0n],[])),e.addPastKeyValues(a,s);let o=ot(a,n.inputNames);return await be(n,o)}async function Qx(e,{encode_function:t,merge_function:r,modality_input_names:n,modality_output_name:s,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:p=null,...f}){if(!l){l=await e.encode_text({input_ids:a,...f});let y=ot(f,n);if(Object.keys(y).length>0){if(a.dims[1]!==1){let v=await t({...y,...f});({inputs_embeds:l,attention_mask:o}=r({[s]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){let v=a.dims[1],x=c.get_seq_length();o=Fe([xt([a.dims[0],x]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){let{image_grid_thw:y,video_grid_thw:v}=f;[i]=e.get_rope_index(a,y,v,o)}return await _r(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:u,logits_processor:p},!0)}async function vU(e,t){return await Qx(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 dv(e,t){return await Qx(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 Jx(e,t=0){let[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;o<r;++o){let i=o*n,l=BigInt(t);for(let c=0;c<n;++c){let u=i+c;s[u]===0n?a[u]=BigInt(1):(a[u]=l,l+=s[u])}}return{data:a,dims:e.dims}}function bU(e,t=null,r=0){let{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=Jx(a,r),l=new q("int64",o,i);if(t){let c=-(n??s).dims.at(1);l=l.slice(null,[c,null])}return l}function ha(e,t,r,n){let s=r.past_key_values?r.past_key_values.get_seq_length():0;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new q("int64",[1n],[])),!r.attention_mask){let o;for(let i of["input_ids","inputs_embeds","position_ids"])if(r[i]){o=r[i].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=xt([o[0],s+o[1]])}if(r.past_key_values){let{input_ids:o,attention_mask:i}=r;i&&i.dims[1]>o.dims[1]||s<o.dims[1]&&(r.input_ids=o.slice(null,[s,null]))}return r}function vi(e,t,r,n){return r.past_key_values&&(t=t.map(s=>[s.at(-1)])),{...r,decoder_input_ids:Dp(t)}}function Ys(e,...t){return e.config.is_encoder_decoder?vi(e,...t):ha(e,...t)}function Xx({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){let a=n.tolist().map(c=>c.reduce((u,p,f)=>(p==e&&u.push(f),u),[])),o=a.reduce((c,u)=>c+u.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){let u=a[c],p=t[c];for(let f=0;f<u.length;++f)p[u[f]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function Fh({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return Xx({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function Yx({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:n,attention_mask:s}){return Xx({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}async function MU(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{let s=await yr(e,t[n],!1,r);return[n,s]})))}function EU(e,t){let{text_config:r,audio_config:n}=e.config,s=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=n,i=a+o,l=new Oh,c=s?.config?.kv_cache_dtype??"float32",u=c==="float16"?is.float16:is.float32,p=Oi(n,{batch_size:1});for(let y in p){let v=p[y].reduce((x,M)=>x*M,1);l[y]=new q(c,new u(v),p[y])}let f=new q(c,new u(i*hv),[1,i,hv]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw new Error("input_features must be iterable or async iterable");return{encoder_session:s,enc_kv_cache:l,enc_padding_cache:f,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:m,text_hidden_size:r.hidden_size}}async function kU(e,t){let r=t.dims[2],n=Math.floor((TU+r-3)/2)+1,s=new q("int64",BigInt64Array.from({length:n},(u,p)=>BigInt(e.enc_past_seq_len+p)),[1,n]),a=e.enc_past_seq_len+n,o=xt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await be(e.encoder_session,{input_features:t,attention_mask:o,position_ids:s,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=l;for(let u in c)if(u.startsWith("present.")){let p=u.replace("present","past_key_values"),f=e.enc_kv_cache[p];f?.location==="gpu-buffer"&&f.dispose(),e.enc_kv_cache[p]=c[u]}return e.enc_past_seq_len=a,i}async function CU(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}let n=await kU(e,r.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function AU(e,t,r){if(e.audio_embed_queue.length===0)return;let n=t.data,s=0,a=r;for(;a>0&&e.audio_embed_queue.length>0;){let o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let u=0;u<l*e.text_hidden_size;++u)n[s*e.text_hidden_size+u]+=o.data[c+u];s+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}async function Xt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>Mt.read(t)))}async function fa(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?Kb(r,t):r instanceof Float64Array?new Float32Array(r):r))}function Vp(e,t){t&&(e=e.map(o=>o|0));let[r,n,s,a]=e;return{xmin:r,ymin:n,xmax:s,ymax:a}}function fv(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}function KU(e,{config:t=null,cache_dir:r=null,local_files_only:n=!1,revision:s="main"}={}){if(t!==null)return ls.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s});let a=JSON.stringify([e,r,n,s]);return Lv(a,()=>ls.from_pretrained(e,{config:t,cache_dir:r,local_files_only:n,revision:s}))}async function DI(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await KU(e,{config:t});let a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=n??o.device,u=r??o.dtype,p,f=t.architectures||[],m=!1;for(let M of f){let T=mr.get(M);if(T!==void 0){p=T,m=!0;break}}if(!m&&t.model_type){let M=mr.get(t.model_type);if(M!==void 0&&(p=M,m=!0),!m){for(let T of Object.values(es))if(T.has(t.model_type)){p=mr.get(T.get(t.model_type)),m=!0;break}}}if(!m){let M=f.length>0?f.join(", "):"(none)";ce.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${M}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Ci}`),p=J.EncoderOnly}let y=(M,T=null)=>{T=T??M;let A=Hv(c,M),C=Kv(u,M,A),S=Pp[C]??"",O=`${T}${S}.onnx`,E=l?`${l}/${O}`:O;a.push(E);let K=Px(i,O,M);for(let $ of Rx(O,K)){let V=l?`${l}/${$}`:$;a.push(V)}},{sessions:v,optional_configs:x}=wU(p,t,{model_file_name:s});for(let[M,T]of Object.entries(v))y(M,T);if(x)for(let M of Object.values(x))a.push(M);return a}async function BI(e){if(!e)throw new Error("modelId is required");return(await Ma(e,_a,{})).exists?[_a]:[]}async function Va(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null,include_tokenizer:a=!0,include_processor:o=!0}={}){let i=await DI(e,{config:t,dtype:r,device:n,model_file_name:s});if(a){let l=await sh(e);i.push(...l)}if(o){let l=await BI(e);i.push(...l)}return i}async function Ga(e,t,r={}){e=NI[e]??e;let n=bi[e];if(!n)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(bi).join(", ")}]`);let{type:s}=n;return Va(t,{...r,include_tokenizer:s!=="audio"&&s!=="image",include_processor:s!=="text"})}async function QU(e,t=null,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:u=null,model_file_name:p=null,session_options:f={}}={}){e=NI[e]??e;let m=bi[e.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(bi)}]`);t||(t=m.default.model,ce.info(`No model specified. Using default model: "${t}".`),!l&&m.default.dtype&&(l=m.default.dtype));let y=await Ga(e,t,{device:i,dtype:l}),v={};r&&(await Promise.all(y.map(async Q=>Ma(t,Q)))).forEach((Q,G)=>{Q.exists&&(v[y[G]]={loaded:0,total:Q.size??0})});let x={progress_callback:r?V=>{if(V.status==="progress"){v[V.file]={loaded:V.loaded,total:V.total};let Q=Object.values(v).reduce((D,R)=>D+R.loaded,0),G=Object.values(v).reduce((D,R)=>D+R.total,0),W=G>0?Q/G*100:0;r({status:"progress_total",name:V.name,progress:W,loaded:Q,total:G,files:structuredClone(v)})}r(V)}:void 0,config:n,cache_dir:s,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:u,model_file_name:p,session_options:f},M=y.includes("tokenizer.json"),T=y.includes("preprocessor_config.json"),A=m.model,C;if(Array.isArray(A)){let V=n??await ls.from_pretrained(t,x),{model_type:Q}=V,G=A.find(W=>W.supports(Q));if(!G)throw Error(`Unsupported model type "${Q}" for task "${e}". None of the candidate model classes support this type.`);C=G.from_pretrained(t,{...x,config:V})}else C=A.from_pretrained(t,x);let[S,O,E]=await Promise.all([M?Ae.from_pretrained(t,x):null,T?Ix.from_pretrained(t,x):null,C]),K={task:e,model:E};S&&(K.tokenizer=S),O&&(K.processor=O),cn(r,{status:"ready",task:e,model:t});let $=m.pipeline;return new $(K)}async function YU(e,{num_frames:t=null,fps:r=null}={}){if(!pe.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(t==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let n=[],s=document.createElement("video");if(s.crossOrigin="anonymous",s.muted=!0,typeof e=="string")s.src=e;else if(e instanceof Blob)s.src=URL.createObjectURL(e);else if(e instanceof HTMLVideoElement)s.src=e.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(p=>s.onloadedmetadata=p),s.seekable.start(0)===s.seekable.end(0)){let f=await(await ge.fetch(s.src)).blob();s.src=URL.createObjectURL(f),await new Promise(m=>s.onloadedmetadata=m)}let a=s.duration,o,i;t!=null?(o=t,i=t===1?0:a/(t-1)):(i=1/r,o=Math.floor(a/i));let l=[];for(let p=0;p<o;++p)l.push(t===1?a/2:p*i);let c=document.createElement("canvas");c.width=s.videoWidth,c.height=s.videoHeight;let u=c.getContext("2d",{willReadFrequently:!0});for(let p of l){s.currentTime=p,await new Promise(v=>{s.onseeked=v}),u.drawImage(s,0,0,c.width,c.height);let f=u.getImageData(0,0,c.width,c.height),m=new Mt(f.data,c.width,c.height,4),y=new em(m,p);n.push(y)}return s.remove(),new $I(n,a)}async function Vc(e,t,r={}){let n=await ps(r?.cache_dir);if(!n)return{allCached:!1,files:t.map(o=>({file:o,cached:!1}))};let s=await Promise.all(t.map(async a=>{let{localPath:o,proposedCacheKey:i}=xa(e,a,r,n),l=await Ta(n,o,i);return{file:a,cached:!!l}}));return{allCached:s.every(a=>a.cached),files:s}}async function VI(e,t,r={}){let n=await ps(r?.cache_dir);if(!n)return!1;let{localPath:s,proposedCacheKey:a}=xa(e,t,r,n);return!!await Ta(n,s,a)}async function ZU(e,t={}){if(!e)throw new Error("modelId is required");if(!await VI(e,"config.json",t))return!1;let r=await Va(e,t);return(await Vc(e,r,t)).allCached}async function ez(e,t={}){if(!e)throw new Error("modelId is required");let r=await Va(e,t);return await Vc(e,r,t)}async function tz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");if(!await VI(t,"config.json",r))return!1;let n=await Ga(e,t,r);return(await Vc(t,n,r)).allCached}async function rz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let n=await Ga(e,t,r);return await Vc(t,n,r)}async function GI(e,t,r={}){let n=await ps(r?.cache_dir);if(!n)return{filesDeleted:0,filesCached:0,files:t.map(a=>({file:a,deleted:!1,wasCached:!1}))};if(!n.delete)throw new Error("Cache does not support delete operation");let s=await Promise.all(t.map(async a=>{let{localPath:o,proposedCacheKey:i}=xa(e,a,r,n),c=!!await Ta(n,o,i),u=!1;if(c){let p=await n.delete(i),f=!p&&i!==o?await n.delete(o):!1;u=p||f}return{file:a,deleted:u,wasCached:c}}));return{filesDeleted:s.filter(a=>a.deleted).length,filesCached:s.filter(a=>a.wasCached).length,files:s}}async function nz(e,t={}){if(!e)throw new Error("modelId is required");let r=await Va(e,t);return await GI(e,r,t)}async function sz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let n=await Ga(e,t,r);return await GI(t,n,r)}var ci,tL,cs,At,ar,rL,nL,Gp,ss,wv,ui,sL,BV,Mi,yv,vv,jp,qp,aL,oL,iL,lL,cL,uL,dL,pL,pe,Wp,di,hL,by,fL,mL,Ft,My,ge,ce,yL,Ey,vL,bL,Mv,ML,xL,ky,TL,hi,Hp,xi,EL,kL,CL,AL,SL,IL,qt,Kp,PL,xv,Cy,RL,OL,ya,LL,wr,FL,NL,DL,BL,UL,zL,$L,VL,GL,Ti,jL,qL,WL,HL,KL,QL,JL,XL,YL,ZL,eF,tF,rF,nF,sF,aF,Tv,iF,Ht,lF,cF,uF,dF,pF,hF,fF,mF,_F,gF,wF,yF,vF,bF,MF,xF,TF,EF,kF,CF,AF,SF,Ev,PF,Ei,RF,Ay,Sy,OF,LF,Bd,FF,NF,BF,Iy,UF,zF,$F,VF,GF,Py,jF,qF,HF,KF,va,QF,JF,XF,YF,ZF,eN,tN,rN,nN,sN,Av,oN,Kt,iN,lN,cN,uN,dN,pN,hN,fN,mN,_N,gN,wN,yN,vN,bN,MN,xN,TN,EN,kN,Sv,AN,SN,B,Ot,IN,PN,Qt,LN,FN,NN,DN,BN,UN,zN,$N,St,VN,Ly,Qn,us,GN,jN,Fy,qN,Ny,WN,Xs,HN,KN,QN,JN,XN,YN,ZN,eD,tD,rD,By,Uy,ir,de,ze,Z,ae,uD,tt,ua,_e,$y,Le,Be,Oe,on,pD,Ke,hD,fD,TD,Dt,ED,fi,Qp,rr,ba,kD,CD,Rv,AD,Gy,SD,Ov,OD,Wy,ga,Hd,Hy,wa,ht,gv,FD,ND,Ud,zv,jD,qD,QD,$v,JD,ZD,eB,Lt,Ip,as,Qy,tB,Jy,Jn,Xy,He,Rr,Kd,dn,sB,zd,aB,ft,Yy,Zy,Pp,is,q,Uo,uB,le,rb,nb,sb,ab,ob,ib,lb,cb,ub,db,pb,hb,fb,mb,_b,gb,wb,yb,vb,bb,Mb,xb,Tb,Eb,kb,Cb,oh,Ab,Sb,Ib,Pb,Rb,Ob,Lb,Fb,Nb,Db,Bb,Ub,zb,fB,$b,Vb,Gb,oi,mB,gB,rv,jb,qb,Wb,Ae,Ci,ih,_a,wB,yB,Zs,Se,Rp,ct,lh,vB,bB,MB,xB,EB,kB,Xb,Yb,ch,Zb,eM,uh,tM,rM,nM,OB,sM,dh,aM,oM,iM,lM,cM,uM,dM,Bt,jo,pM,Op,ln,hM,Or,LB,FB,Mt,NB,ue,gi,wM,yM,vM,bM,hh,MM,fh,xM,mh,TM,_h,EM,kM,Si,CM,gh,AM,SM,wh,IM,PM,RM,Lp,OM,LM,FM,NM,Ii,DM,BM,yh,UM,vh,zM,bh,$M,Mh,VM,xh,GM,jM,Pi,qM,WM,Ct,jB,Gd,Xn,jd,HM,KM,QM,JM,ii,Th,XM,Eh,YM,ZM,ex,kh,tx,rx,nx,Ch,sx,mt,qo,ax,an,ox,ea,Ri,Qd,ix,ta,lx,Wo,cx,ra,Fp,na,ux,Ho,dx,Ko,px,sa,hx,lv,Qo,fx,Jo,mx,Xo,_x,Yn,aa,gx,cv,JB,Yo,wx,oa,yx,Jd,vx,Ah,bx,Xd,Sh,Ih,Mx,Zo,xx,ia,Tx,$o,XB,YB,la,Ex,uv,qd,Vo,eU,tU,ca,kx,ei,Cx,ti,Ax,ri,Sx,Ix,wi,ls,Qe,oe,je,Je,_t,hn,cU,Jt,Li,yi,Lx,Fx,Ph,Nx,Dx,Bx,Ux,zx,$x,Vx,Gx,uU,dU,jx,hs,Rh,Wx,Hx,pU,Fi,hU,fU,mU,_U,Oh,es,J,ts,mr,Lh,os,I,Nh,fs,Zx,e0,t0,r0,Ni,n0,s0,Di,a0,o0,Bi,i0,l0,Ui,c0,u0,Ea,d0,p0,h0,zi,f0,m0,fn,_0,g0,w0,y0,v0,$i,b0,M0,Vi,x0,T0,Gi,E0,k0,mn,C0,A0,S0,I0,P0,xU,pv,Dh,Bh,Uh,R0,zh,O0,ka,L0,$h,Vh,Nr,F0,N0,Gh,D0,B0,ji,U0,z0,qi,$0,V0,Wi,G0,j0,Hi,q0,W0,_n,H0,K0,Q0,J0,X0,Ki,Y0,Z0,Qi,eT,tT,Ji,rT,nT,ms,Xi,sT,aT,jh,qh,Ca,oT,Wh,Hh,gn,iT,lT,cT,uT,dT,Yi,pT,hT,wn,fT,mT,_T,gT,wT,Kh,yT,Zi,vT,bT,Qh,MT,Jh,xT,Aa,TT,ET,kT,el,Xh,tl,CT,AT,rl,ST,IT,Yh,PT,Zh,RT,yn,OT,LT,FT,NT,DT,ef,BT,nl,UT,zT,sl,$T,VT,vn,GT,jT,qT,WT,HT,al,KT,QT,_s,JT,XT,YT,ZT,gs,eE,tE,rE,nE,ol,sE,aE,il,oE,iE,ll,lE,cE,cl,uE,dE,tf,pE,ul,hE,fE,dl,mE,_E,pl,gE,wE,rf,hl,nf,fl,yE,vE,ml,bE,ME,sf,_l,gl,wl,yl,xE,vl,TE,EE,bl,kE,CE,Ml,AE,SE,xl,IE,PE,Tl,RE,OE,El,LE,FE,kl,NE,DE,Cl,BE,UE,Al,zE,$E,af,Sl,VE,of,GE,lf,jE,Il,qE,WE,Pl,HE,KE,Mr,QE,JE,XE,YE,ZE,ek,tk,rk,Rl,nk,sk,cf,gr,ak,ok,ik,Ol,lk,ck,Ll,uk,dk,Sa,pk,uf,hk,Fl,fk,mk,_k,Nl,gk,wk,yk,Dl,vk,bk,df,Mk,Bl,xk,Tk,Ul,Ek,kk,zl,Ck,Ak,$l,Sk,Ik,ws,Pk,Rk,Ok,Lk,pf,Fk,hf,Nk,ff,mf,Dk,_f,gf,Ia,Bk,wf,yf,Vl,Uk,zk,Gl,$k,Vk,ys,Gk,jk,qk,Wk,jl,Hk,Kk,Pa,Qk,Jk,Xk,Ra,Yk,Zk,e1,Oa,t1,r1,n1,La,s1,a1,o1,ql,i1,l1,Wl,c1,u1,vs,d1,p1,h1,f1,Hl,m1,_1,Kl,g1,w1,bn,y1,v1,b1,M1,x1,Ql,T1,E1,Jl,k1,C1,vf,A1,Xl,S1,I1,bf,Yl,P1,R1,Zl,O1,L1,Mn,F1,N1,D1,B1,U1,Mf,z1,ec,$1,V1,tc,G1,j1,rc,q1,W1,nc,H1,K1,sc,Q1,J1,ac,X1,Y1,oc,Z1,eC,ic,tC,rC,nC,xf,sC,lc,aC,oC,cc,iC,lC,uc,cC,uC,dc,dC,pC,Tf,Ef,pc,hC,fC,hc,mC,_C,fc,gC,wC,mc,yC,vC,_c,bC,MC,gc,xC,TC,wc,EC,kC,yc,vc,CC,kf,bc,Mc,AC,Cf,xc,SC,IC,Tc,PC,RC,Af,xn,OC,LC,FC,NC,DC,Tn,BC,UC,zC,$C,VC,Ec,GC,jC,Sf,If,Pf,qC,Rf,Of,kc,WC,HC,Fa,KC,QC,JC,Na,XC,YC,ZC,Cc,eA,Lf,tA,Ac,rA,nA,Da,sA,Ff,Nf,Sc,aA,oA,Ba,iA,lA,cA,uA,bs,dA,pA,hA,fA,Ic,mA,_A,Pc,gA,wA,Df,yA,Bf,Uf,Ua,vA,bA,MA,Rc,xA,TA,Oc,EA,kA,Lc,CA,AA,zf,$f,SA,za,IA,PA,RA,Ms,OA,LA,FA,NA,Fc,DA,BA,UA,Nc,zA,$A,Vf,VA,Dc,GA,jA,Gf,qA,jf,WA,qf,Wf,HA,KA,hv,TU,Wd,SU,Hf,Kf,$a,QA,JA,XA,Qf,En,YA,ZA,eS,tS,rS,Jf,nS,IU,Bc,sS,Xf,aS,kn,oS,iS,lS,cS,uS,Cn,dS,pS,hS,fS,mS,Uc,_S,gS,Yf,zc,wS,yS,PU,RU,OU,LU,vS,bS,MS,xS,TS,ES,kS,FU,CS,AS,SS,IS,PS,NU,RS,OS,LS,rs,FS,NS,DS,BS,US,zS,$S,VS,DU,GS,jS,qS,WS,HS,KS,BU,QS,UU,Te,ni,Ee,si,ns,Yd,Bp,Zd,JS,ep,li,tp,XS,rp,YS,np,ZS,sp,eI,ap,tI,op,rI,ip,nI,lp,sI,cp,Up,up,zp,dp,$p,pp,aI,hp,oI,fp,zU,mp,iI,_p,lI,gp,$U,wp,VU,yp,cI,vp,GU,bp,uI,Mp,dI,xp,jU,Tp,qU,Ep,pI,kp,WU,Cp,HU,$e,hI,fI,mI,_I,$c,gI,wI,yI,vI,bI,MI,xI,TI,EI,kI,mv,Zf,CI,AI,SI,II,PI,RI,OI,LI,FI,bi,NI,JU,UI,_v,zI,XU,em,$I,az,qI=Ve(()=>{Hw();vy();ci={},tL=Object.defineProperty,cs=(e,t)=>{for(var r in t)tL(e,r,{get:t[r],enumerable:!0})},At={},ar={},rL={},nL="4.0.0-next.8",Gp=typeof self<"u",ss=!bv(At),wv=!bv(ar),ui=Gp&&"caches"in self,sL=typeof globalThis.Deno<"u",BV=typeof globalThis.Bun<"u",Mi=sL&&ui&&!ss,yv=typeof process<"u",vv=yv&&process?.release?.name==="node"&&!Mi,jp=typeof window<"u"&&typeof window.document<"u",qp=Gp&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),aL=jp||qp||Mi,oL=vv||typeof navigator<"u"&&"gpu"in navigator,iL=typeof navigator<"u"&&"ml"in navigator,lL=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",cL=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",uL=typeof ServiceWorkerGlobalScope<"u"&&Gp&&self instanceof ServiceWorkerGlobalScope,dL=()=>{if(typeof navigator>"u")return!1;let e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&n},pL=dL(),pe=Object.freeze({IS_BROWSER_ENV:jp,IS_WEBWORKER_ENV:qp,IS_WEB_ENV:aL,IS_SERVICE_WORKER_ENV:uL,IS_DENO_WEB_RUNTIME:Mi,IS_WEB_CACHE_AVAILABLE:ui,IS_WEBGPU_AVAILABLE:oL,IS_WEBNN_AVAILABLE:iL,IS_SAFARI:pL,IS_PROCESS_AVAILABLE:yv,IS_NODE_ENV:vv,IS_FS_AVAILABLE:ss,IS_PATH_AVAILABLE:wv,IS_CRYPTO_AVAILABLE:lL,IS_CHROME_AVAILABLE:cL}),Wp=ss&&wv,di="./";if(Wp){let e=Object(ci).url;e?di=ar.dirname(ar.dirname(rL.fileURLToPath(e))):typeof __dirname<"u"&&(di=ar.dirname(__dirname))}hL=Wp?ar.join(di,"/.cache/"):null,by="/models/",fL=Wp?ar.join(di,by):by,mL=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ft=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),My=Ft.WARNING,ge={version:nL,backends:{onnx:{}},get logLevel(){return My},set logLevel(e){My=e,ge.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(jp||qp||Mi),localModelPath:fL,useFS:ss,useBrowserCache:ui,useFSCache:ss,cacheDir:hL,useCustomCache:!1,customCache:null,useWasmCache:ui||ss,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:mL};ce={error(...e){ge.logLevel<=Ft.ERROR&&console.error(...e)},warn(...e){ge.logLevel<=Ft.WARNING&&console.warn(...e)},info(...e){ge.logLevel<=Ft.INFO&&console.log(...e)},debug(...e){ge.logLevel<=Ft.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},yL=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let r of e){let n=t;for(let s=0;s<r.length;++s){let a=r[s];n=n[a]??(n[a]=Object.create(null))}n.end=r}return t}split(e){let t=[],r=e.length,n=0,s=0;for(;s<r;){let a=this.trie,o=null,i=s;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(s>n&&t.push(e.slice(n,s)),t.push(o),s+=o.length,n=s):++s}return n<r&&t.push(e.slice(n)),t}},Ey=yL,vL=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}},bL=vL,Mv=(()=>{let e=[...Array.from({length:94},(s,a)=>a+33),...Array.from({length:12},(s,a)=>a+161),...Array.from({length:82},(s,a)=>a+174)],t=e.slice(),r=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+r),r+=1);let n=t.map(s=>String.fromCharCode(s));return Object.fromEntries(e.map((s,a)=>[s,n[a]]))})(),ML=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),xL=ML(Mv),ky=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",TL=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${ky}])]+`,` ?[^\\s${ky}]+`]]),hi="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Hp=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"),xi=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[n,s]of TL)r=r.replaceAll(n,s);try{return new RegExp(r,"gu")}catch(n){if(!(n instanceof SyntaxError)||!n.message.toLowerCase().includes("invalid property name"))throw n;let s=!1,a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return s=!0,`${i}{Script=${l}}`}});if(!s)throw n;try{return new RegExp(a,"gu")}catch{throw n}}}else if(e.String!==void 0){let r=EL(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},EL=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),kL=(e,t,r)=>{let n=[],s=0;for(;s<e.length;){if(n.push(e[s]),(t.get(e[s])??r)!==r){++s;continue}for(;++s<e.length&&(t.get(e[s])??r)===r;)t.get(n.at(-1))!==r&&(n[n.length-1]+=e[s])}return n},CL=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,AL=e=>Number.isInteger(e)||typeof e=="bigint",SL=e=>{let t=0;for(let r of e)++t;return t},IL=e=>xv(e.toLowerCase()),qt=(...e)=>Array.prototype.concat.apply([],e),Kp=e=>new Map(Object.entries(e)),PL=(e,t)=>{let r=[],n=0;for(let s of e.matchAll(t)){let a=s[0];n<s.index&&r.push(e.slice(n,s.index)),a.length>0&&r.push(a),n=s.index+a.length}return n<e.length&&r.push(e.slice(n)),r},xv=e=>e.replace(new RegExp("\\p{M}","gu"),""),Cy=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(let n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},RL=e=>e.match(/\S+/g)||[],OL=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ya=OL,LL=class extends ya{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},wr=LL,FL=class extends wr{tokenize_chinese_chars(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r],s=n.charCodeAt(0);CL(s)?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
10
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){let t=[];for(let r of e){let n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},NL=FL,DL=class extends wr{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("\uFF5E")?e=e.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):e=e.normalize("NFKC"),e}},BL=DL,UL=class extends wr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Tv(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},zL=UL,$L=class extends wr{normalize(e){let t=xi(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},VL=$L,GL=class extends wr{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Ti=GL,jL=class extends Ti{constructor(){super(...arguments),this.form="NFC"}},qL=jL,WL=class extends Ti{constructor(){super(...arguments),this.form="NFD"}},HL=WL,KL=class extends Ti{constructor(){super(...arguments),this.form="NFKC"}},QL=KL,JL=class extends Ti{constructor(){super(...arguments),this.form="NFKD"}},XL=JL,YL=class extends wr{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}},ZL=YL,eF=class extends wr{normalize(e){return xv(e)}},tF=eF,rF=class extends wr{normalize(e){return e.toLowerCase()}},nF=rF,sF=class extends wr{normalize(e){return e=this.config.prepend+e,e}},aF=sF;Tv=oF,iF=class extends ya{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Ht=iF,lF=class extends Ht{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Mv,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(n=>Array.from(this.text_encoder.encode(n),s=>this.byte_encoder[s]).join(""))}},cF=lF,uF=class extends Ht{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},dF=uF,pF=class extends Ht{constructor(e){super(),this.replacement=e.replacement??"\u2581",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){let{section_index:r=void 0}=t??{},n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},hF=pF,fF=class extends Ht{constructor(e){super(),this.config=e,this.pattern=xi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):PL(e,this.pattern)}},mF=fF,_F=class extends Ht{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${hi}]+|[${hi}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},gF=_F,wF=class extends Ht{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},yF=wF,vF=class extends Ht{constructor(){super(),this.pattern=new RegExp(`[^\\s${hi}]+|[${hi}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},bF=vF,MF=class extends Ht{constructor(e){super(),this.config=e,this.pattern=xi(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},xF=MF,TF=class extends Ht{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Ev(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},EF=TF,kF=class extends Ht{pre_tokenize_text(e){return RL(e)}},CF=kF,AF=class extends Ht{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},SF=AF;Ev=IF,PF=class extends ya{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=kL(t,this.tokens_to_ids,this.unk_token_id)),t}},Ei=PF,RF=class extends Ei{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Kp(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(let[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){let t=[];for(let r of e){let n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0,o=[];for(;a<n.length;){let i=n.length,l=null;for(;a<i;){let c=n.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},Ay=RF,Sy=class kv{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new kv(!1,new Map)}},OF=class{constructor(){this.root=Sy.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let r of e){let n=t.children.get(r);n===void 0&&(n=Sy.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(let n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},LF=OF,Bd=class Cv{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){let t=new Cv(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},FF=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new Bd(this.bos_token_id??0,0,0,0,0),s=new Bd(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(e,t,r,n){let s=this.nodes.length,a=new Bd(n,s,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;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]){let u=c.backtrace_score+o.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}let r=[],s=this.begin_nodes[e][0].prev;if(s===null)return[];let a=s.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},NF=FF;BF=class extends Ei{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=DF(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new LF,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,r=1,n=0;for(;n<t.length;){let s=!1,a=[],o=t.slice(n).join(""),i=this.trie.common_prefix_search(o);for(let l of i){a.push(l);let c=this.tokens_to_ids.get(l),u=this.scores[c],p=SL(l);e.insert(n,p,u,c),!s&&p===r&&(s=!0)}s||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){let t=new NF(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let n=this.tokenize(r);t.push(...n)}return t}},Iy=BF,UF=class{constructor(e=(r,n)=>r>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){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);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},zF=UF,$F=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){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()}},VF=$F,GF=class extends Ei{constructor(e){super(e),this.tokens_to_ids=Kp(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(let[r,n]of this.tokens_to_ids)this.vocab[n]=r;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new VF(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){let s=new zF((i,l)=>i.score<l.score),a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(s,o),o=l}for(;!s.is_empty();){let i=s.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let i=a;i!==null;i=i.next)n.push(i.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let n=this.bpe(r);for(let s of n)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){let a=Array.from(this.text_encoder.encode(s)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);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}},Py=GF,jF=class extends Ei{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=Kp(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(e){return e}},qF=jF;HF=WF,KF=class extends ya{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},va=KF,QF=class extends va{post_process(e,t=null,r=!0){let n=t===null?this.config.single:this.config.pair,s=[],a=[];for(let o of n)"SpecialToken"in o?r&&(s.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(s=qt(s,e),a=qt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=qt(s,t),a=qt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},JF=QF,XF=class extends va{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},YF=XF,ZF=class extends va{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=qt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let s=[],a=r?[this.sep[0]]:[];e=qt(e,s,t,a),n=qt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},eN=ZF,tN=class extends va{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=qt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){let s=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=qt(e,s,t,a),n=qt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},rN=tN,nN=class extends va{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>Av(t))}post_process(e,t=null,r=!0){let n={tokens:e,tokens_pair:t};for(let s of this.processors)n=s.post_process(n.tokens,n.tokens_pair,r);return n}},sN=nN;Av=aN,oN=class extends ya{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("")}},Kt=oN,iN=class extends Kt{constructor(e){super(e),this.byte_decoder=xL,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let n of e)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},lN=iN,cN=class extends Kt{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){let n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=Hp(t)),t})}},uN=cN,dN=class extends Kt{constructor(e){super(e),this.replacement=e.replacement??"\u2581"}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}},pN=dN,hN=class extends Kt{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},fN=hN,mN=class extends Kt{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";let t=[e[0]];for(let s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let n=t.filter(s=>s!==this.pad_token).join("");return this.cleanup&&(n=Hp(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},_N=mN,gN=class extends Kt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Sv(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},wN=gN,yN=class extends Kt{decode_chain(e){let t=xi(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},vN=yN,bN=class extends Kt{decode_chain(e){return[e.join("")]}},MN=bN,xN=class extends Kt{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let s=0;s<this.start&&t[s]===this.content;++s){r=s+1;continue}let n=t.length;for(let s=0;s<this.stop;++s){let a=t.length-s-1;if(t[a]===this.content){n=a;continue}else break}return t.slice(r,n)})}},TN=xN,EN=class extends Kt{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],r=[];for(let n of e){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){let a=parseInt(n.slice(3,5),16);isNaN(a)||(s=a)}if(s!==null)r.push(s);else{if(r.length>0){let a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(n)}}if(r.length>0){let n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},kN=EN;Sv=CN,AN=class{constructor(e,t){let r=Cy(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let n=Cy(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=Tv(this.tokenizer.normalizer),this.pre_tokenizer=Ev(this.tokenizer.pre_tokenizer),this.model=HF(this.tokenizer.model,this.config),this.post_processor=Av(this.tokenizer.post_processor),this.decoder=Sv(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let s=[],a=[];this.added_tokens_map=new Map;for(let o of this.tokenizer.added_tokens){let i=new bL(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){let l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else s.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Ey(s),this.splitter_normalized=new Ey(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){let{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=s.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:s,attention_mask:new Array(o.length).fill(1)};return n&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!AL(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(s=>this.model.vocab[Number(s)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=Hp(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((r,n)=>{let s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),s.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((r,n)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=IL(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let s=this.splitter_normalized.split(r);return s.forEach((a,o)=>{let i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(s[o-1]=s[o-1].trimEnd()),i.rstrip&&o<s.length-1&&(s[o+1]=s[o+1].trimStart()))}),s.flatMap(a=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];let o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:n}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){let n=this.encode_text(e),s=this.encode_text(t||null);return this.post_processor?this.post_processor(n,s,r):{tokens:qt(n??[],s??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let r=0;r<this.model.vocab.length;++r){let n=this.model.vocab[r];(e||!this.added_tokens_map.has(n))&&t.set(n,r)}return t}},SN=AN,B=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Ot=class{constructor(e,t){this.value=e,this.type=t}};IN=[["{%",B.OpenStatement],["%}",B.CloseStatement],["{{",B.OpenExpression],["}}",B.CloseExpression],["(",B.OpenParen],[")",B.CloseParen],["{",B.OpenCurlyBracket],["}",B.CloseCurlyBracket],["[",B.OpenSquareBracket],["]",B.CloseSquareBracket],[",",B.Comma],[".",B.Dot],[":",B.Colon],["|",B.Pipe],["<=",B.ComparisonBinaryOperator],[">=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],PN=new Map([["n",`
11
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);Qt=class{constructor(){w(this,"type","Statement")}},LN=class extends Qt{constructor(t){super();w(this,"type","Program");this.body=t}},FN=class extends Qt{constructor(t,r,n){super();w(this,"type","If");this.test=t,this.body=r,this.alternate=n}},NN=class extends Qt{constructor(t,r,n,s){super();w(this,"type","For");this.loopvar=t,this.iterable=r,this.body=n,this.defaultBlock=s}},DN=class extends Qt{constructor(){super(...arguments);w(this,"type","Break")}},BN=class extends Qt{constructor(){super(...arguments);w(this,"type","Continue")}},UN=class extends Qt{constructor(t,r,n){super();w(this,"type","Set");this.assignee=t,this.value=r,this.body=n}},zN=class extends Qt{constructor(t,r,n){super();w(this,"type","Macro");this.name=t,this.args=r,this.body=n}},$N=class extends Qt{constructor(t){super();w(this,"type","Comment");this.value=t}},St=class extends Qt{constructor(){super(...arguments);w(this,"type","Expression")}},VN=class extends St{constructor(t,r,n){super();w(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=n}},Ly=class extends St{constructor(t,r){super();w(this,"type","CallExpression");this.callee=t,this.args=r}},Qn=class extends St{constructor(t){super();w(this,"type","Identifier");this.value=t}},us=class extends St{constructor(t){super();w(this,"type","Literal");this.value=t}},GN=class extends us{constructor(){super(...arguments);w(this,"type","IntegerLiteral")}},jN=class extends us{constructor(){super(...arguments);w(this,"type","FloatLiteral")}},Fy=class extends us{constructor(){super(...arguments);w(this,"type","StringLiteral")}},qN=class extends us{constructor(){super(...arguments);w(this,"type","ArrayLiteral")}},Ny=class extends us{constructor(){super(...arguments);w(this,"type","TupleLiteral")}},WN=class extends us{constructor(){super(...arguments);w(this,"type","ObjectLiteral")}},Xs=class extends St{constructor(t,r,n){super();w(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=n}},HN=class extends St{constructor(t,r){super();w(this,"type","FilterExpression");this.operand=t,this.filter=r}},KN=class extends Qt{constructor(t,r){super();w(this,"type","FilterStatement");this.filter=t,this.body=r}},QN=class extends St{constructor(t,r){super();w(this,"type","SelectExpression");this.lhs=t,this.test=r}},JN=class extends St{constructor(t,r,n){super();w(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=n}},XN=class extends St{constructor(t,r){super();w(this,"type","UnaryExpression");this.operator=t,this.argument=r}},YN=class extends St{constructor(t=void 0,r=void 0,n=void 0){super();w(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=n}},ZN=class extends St{constructor(t,r){super();w(this,"type","KeywordArgumentExpression");this.key=t,this.value=r}},eD=class extends St{constructor(t){super();w(this,"type","SpreadExpression");this.argument=t}},tD=class extends Qt{constructor(t,r,n){super();w(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=n}},rD=class extends St{constructor(t,r,n){super();w(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=n}};By=class extends Error{},Uy=class extends Error{},ir=class{constructor(e=void 0){w(this,"type","RuntimeValue");w(this,"value");w(this,"builtins",new Map);this.value=e}__bool__(){return new ae(!!this.value)}toString(){return String(this.value)}},de=class extends ir{constructor(){super(...arguments);w(this,"type","IntegerValue")}},ze=class extends ir{constructor(){super(...arguments);w(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends ir{constructor(){super(...arguments);w(this,"type","StringValue");w(this,"builtins",new Map([["upper",new Le(()=>new Z(this.value.toUpperCase()))],["lower",new Le(()=>new Z(this.value.toLowerCase()))],["strip",new Le(()=>new Z(this.value.trim()))],["title",new Le(()=>new Z(aD(this.value)))],["capitalize",new Le(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new Le(()=>new Z(this.value.trimEnd()))],["lstrip",new Le(()=>new Z(this.value.trimStart()))],["startswith",new Le(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let r=t[0];if(r instanceof Z)return new ae(this.value.startsWith(r.value));if(r instanceof _e){for(let n of r.value){if(!(n instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(n.value))return new ae(!0)}return new ae(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Le(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let r=t[0];if(r instanceof Z)return new ae(this.value.endsWith(r.value));if(r instanceof _e){for(let n of r.value){if(!(n instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(n.value))return new ae(!0)}return new ae(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Le(t=>{let r=t[0]??new Be;if(!(r instanceof Z||r instanceof Be))throw new Error("sep argument must be a string or null");let n=t[1]??new de(-1);if(!(n instanceof de))throw new Error("maxsplit argument must be a number");let s=[];if(r instanceof Be){let a=this.value.trimStart();for(let{0:o,index:i}of a.matchAll(/\S+/g)){if(n.value!==-1&&s.length>=n.value&&i!==void 0){s.push(o+a.slice(i+o.length));break}s.push(o)}}else{if(r.value==="")throw new Error("empty separator");s=this.value.split(r.value),n.value!==-1&&s.length>n.value&&s.push(s.splice(n.value).join(r.value))}return new _e(s.map(a=>new Z(a)))})],["replace",new Le(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let r=t[0],n=t[1];if(!(r instanceof Z&&n instanceof Z))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Be:s=t[2]:s=new Be,!(s instanceof de||s instanceof Be))throw new Error("replace() count argument must be a number or null");return new Z(cD(this.value,r.value,n.value,s.value))})]]))}},ae=class extends ir{constructor(){super(...arguments);w(this,"type","BooleanValue")}},uD=/[\x7f-\uffff]/g;tt=class extends ir{constructor(){super(...arguments);w(this,"type","ObjectValue");w(this,"builtins",new Map([["get",new Le(([t,r])=>{if(!(t instanceof Z))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new Be})],["items",new Le(()=>this.items())],["keys",new Le(()=>this.keys())],["values",new Le(()=>this.values())],["dictsort",new Le(t=>{let r=new Map,n=t.filter(l=>l instanceof ua?(r=l.value,!1):!0),s=n.at(0)??r.get("case_sensitive")??new ae(!1);if(!(s instanceof ae))throw new Error("case_sensitive must be a boolean");let a=n.at(1)??r.get("by")??new Z("key");if(!(a instanceof Z))throw new Error("by must be a string");if(!["key","value"].includes(a.value))throw new Error("by must be either 'key' or 'value'");let o=n.at(2)??r.get("reverse")??new ae(!1);if(!(o instanceof ae))throw new Error("reverse must be a boolean");let i=Array.from(this.value.entries()).map(([l,c])=>new _e([new Z(l),c])).sort((l,c)=>{let u=a.value==="key"?0:1,p=l.value[u],f=c.value[u],m=Ap(p,f,s.value);return o.value?-m:m});return new _e(i)})]]))}__bool__(){return new ae(this.value.size>0)}items(){return new _e(Array.from(this.value.entries()).map(([t,r])=>new _e([new Z(t),r])))}keys(){return new _e(Array.from(this.value.keys()).map(t=>new Z(t)))}values(){return new _e(Array.from(this.value.values()))}toString(){return un(this,{},0,!1)}},ua=class extends tt{constructor(){super(...arguments);w(this,"type","KeywordArgumentsValue")}},_e=class extends ir{constructor(){super(...arguments);w(this,"type","ArrayValue");w(this,"builtins",new Map([["length",new de(this.value.length)]]))}__bool__(){return new ae(this.value.length>0)}toString(){return un(this,{},0,!1)}},$y=class extends _e{constructor(){super(...arguments);w(this,"type","TupleValue")}},Le=class extends ir{constructor(){super(...arguments);w(this,"type","FunctionValue")}},Be=class extends ir{constructor(){super(...arguments);w(this,"type","NullValue")}},Oe=class extends ir{constructor(){super(...arguments);w(this,"type","UndefinedValue")}},on=class{constructor(e){w(this,"variables",new Map([["namespace",new Le(e=>{if(e.length===0)return new tt(new Map);if(e.length!==1||!(e[0]instanceof tt))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));w(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Le],["odd",e=>{if(!(e instanceof de))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof de))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 de||e instanceof ze],["integer",e=>e instanceof de],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof tt],["sequence",e=>e instanceof _e||e instanceof tt||e instanceof Z],["lower",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));this.parent=e}set(e,t){return this.declareVariable(e,ai(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 Oe}catch{return new Oe}}};pD=class{constructor(e){w(this,"global");this.global=e??new on}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}let n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ae(r.value==n.value);case"!=":return new ae(r.value!=n.value)}if(r instanceof Oe||n instanceof Oe){if(n instanceof Oe&&["in","not in"].includes(e.operator.value))return new ae(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Be||n instanceof Be)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Z(r.value.toString()+n.value.toString());if((r instanceof de||r instanceof ze)&&(n instanceof de||n instanceof ze)){let s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{let o=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof ze||n instanceof ze?new ze(o):new de(o)}case"/":return new ze(s/a);case"%":{let o=s%a;return r instanceof ze||n instanceof ze?new ze(o):new de(o)}case"<":return new ae(s<a);case">":return new ae(s>a);case">=":return new ae(s>=a);case"<=":return new ae(s<=a)}}else if(r instanceof _e&&n instanceof _e)switch(e.operator.value){case"+":return new _e(r.value.concat(n.value))}else if(n instanceof _e){let s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ae(s);case"not in":return new ae(!s)}}}if(r instanceof Z||n instanceof Z)switch(e.operator.value){case"+":return new Z(r.value.toString()+n.value.toString())}if(r instanceof Z&&n instanceof Z)switch(e.operator.value){case"in":return new ae(n.value.includes(r.value));case"not in":return new ae(!n.value.includes(r.value))}if(r instanceof Z&&n instanceof tt)switch(e.operator.value){case"in":return new ae(n.value.has(r.value));case"not in":return new ae(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(e,t){let r=[],n=new Map;for(let s of e)if(s.type==="SpreadExpression"){let a=s,o=this.evaluate(a.argument,t);if(!(o instanceof _e))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(let i of o.value)r.push(i)}else if(s.type==="KeywordArgumentExpression"){let a=s;n.set(a.key.value,this.evaluate(a.value,t))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,t))}return[r,n]}applyFilter(e,t,r){if(t.type==="Identifier"){let n=t;if(n.value==="safe")return e;if(n.value==="tojson")return new Z(un(e,{}));if(e instanceof _e)switch(n.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new de(e.value.length);case"reverse":return new _e(e.value.slice().reverse());case"sort":return new _e(e.value.slice().sort((s,a)=>Ap(s,a,!1)));case"join":return new Z(e.value.map(s=>s.value).join(""));case"string":return new Z(un(e,{},0,!1));case"unique":{let s=new Set,a=[];for(let o of e.value)s.has(o.value)||(s.add(o.value),a.push(o));return new _e(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof Z)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let s=e.builtins.get(n.value);if(s instanceof Le)return s.value([],r);if(s instanceof de)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new Z(e.value.trim());case"indent":return new Z(e.value.split(`
12
+ `).map((s,a)=>a===0||s.length===0?s:" "+s).join(`
13
+ `));case"join":case"string":return e;case"int":{let s=parseInt(e.value,10);return new de(isNaN(s)?0:s)}case"float":{let s=parseFloat(e.value);return new ze(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof de||e instanceof ze)switch(n.value){case"abs":return e instanceof de?new de(Math.abs(e.value)):new ze(Math.abs(e.value));case"int":return new de(Math.floor(e.value));case"float":return new ze(e.value);case"string":return new Z(e.toString());default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof tt)switch(n.value){case"items":return new _e(Array.from(e.value.entries()).map(([s,a])=>new _e([new Z(s),a])));case"length":return new de(e.value.size);default:{let s=e.builtins.get(n.value);if(s)return s instanceof Le?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof ae)switch(n.value){case"bool":return new ae(e.value);case"int":return new de(e.value?1:0);case"float":return new ze(e.value?1:0);case"string":return new Z(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){let n=t;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);let s=n.callee.value;if(s==="tojson"){let[,a]=this.evaluateArguments(n.args,r),o=a.get("indent")??new Be;if(!(o instanceof de||o instanceof Be))throw new Error("If set, indent must be a number");let i=a.get("ensure_ascii")??new ae(!1);if(!(i instanceof ae))throw new Error("If set, ensure_ascii must be a boolean");let l=a.get("sort_keys")??new ae(!1);if(!(l instanceof ae))throw new Error("If set, sort_keys must be a boolean");let c=a.get("separators")??new Be,u=null;if(c instanceof _e||c instanceof $y){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[p,f]=c.value;if(!(p instanceof Z)||!(f instanceof Z))throw new Error("separators must be a tuple of two strings");u=[p.value,f.value]}else if(!(c instanceof Be))throw new Error("If set, separators must be a tuple of two strings");return new Z(un(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(s==="join"){let a;if(e instanceof Z)a=Array.from(e.value);else if(e instanceof _e)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`);let[o,i]=this.evaluateArguments(n.args,r),l=o.at(0)??i.get("separator")??new Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(a.join(l.value))}else if(s==="int"||s==="float"){let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("default")??(s==="int"?new de(0):new ze(0));if(e instanceof Z){let l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new de(l):new ze(l)}else{if(e instanceof de||e instanceof ze)return e;if(e instanceof ae)return s==="int"?new de(e.value?1:0):new ze(e.value?1:0);throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}}else if(s==="default"){let[a,o]=this.evaluateArguments(n.args,r),i=a[0]??new Z(""),l=a[1]??o.get("boolean")??new ae(!1);if(!(l instanceof ae))throw new Error("`default` filter flag must be a boolean");return e instanceof Oe||l.value&&!e.__bool__().value?i:e}if(e instanceof _e){switch(s){case"sort":{let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new ae(!1);if(!(i instanceof ae))throw new Error("reverse must be a boolean");let l=a.at(1)??o.get("case_sensitive")??new ae(!1);if(!(l instanceof ae))throw new Error("case_sensitive must be a boolean");let c=a.at(2)??o.get("attribute")??new Be;if(!(c instanceof Z||c instanceof de||c instanceof Be))throw new Error("attribute must be a string, integer, or null");let u=p=>{if(c instanceof Be)return p;let f=c instanceof de?String(c.value):c.value;return Vy(p,f)};return new _e(e.value.slice().sort((p,f)=>{let m=u(p),y=u(f),v=Ap(m,y,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{let a=s==="selectattr";if(e.value.some(p=>!(p instanceof tt)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(p=>p.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);let[o,i,l]=n.args.map(p=>this.evaluate(p,r)),c;if(i){let p=r.tests.get(i.value);if(!p)throw new Error(`Unknown test: ${i.value}`);c=p}else c=(...p)=>p[0].__bool__().value;let u=e.value.filter(p=>{let f=p.value.get(o.value),m=f?c(f,l):!1;return a?m:!m});return new _e(u)}case"map":{let[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){let o=a.get("attribute");if(!(o instanceof Z))throw new Error("attribute must be a string");let i=a.get("default"),l=e.value.map(c=>{if(!(c instanceof tt))throw new Error("items in map must be an object");let u=Vy(c,o.value);return u instanceof Oe?i??new Oe:u});return new _e(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof Z){switch(s){case"indent":{let[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=a.at(1)??o.get("first")??new ae(!1),c=a.at(2)??o.get("blank")??new ae(!1),u=e.value.split(`
14
+ `),p=" ".repeat(i.value),f=u.map((m,y)=>!l.value&&y===0||!c.value&&m.length===0?m:p+m);return new Z(f.join(`
15
+ `))}case"replace":{let a=e.builtins.get("replace");if(!(a instanceof Le))throw new Error("replace filter not available");let[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new ua(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof tt){let a=e.builtins.get(s);if(a&&a instanceof Le){let[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new ua(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${s}`)}else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){let r=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw new Error(`Unknown test: ${e.test.value}`);let s=n(r);return new ae(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Oe}evaluateUnaryExpression(e,t){let r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ae(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(let n of e){let s=this.evaluate(n,t);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(r+=s.toString())}return new Z(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[r,n]=this.evaluateArguments(e.args,t);n.size>0&&r.push(new ua(n));let s=this.evaluate(e.callee,t);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof _e||e instanceof Z))throw new Error("Slice object must be an array or string");let n=this.evaluate(t.start,r),s=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(n instanceof de||n instanceof Oe))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof de||s instanceof Oe))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof de||a instanceof Oe))throw new Error("Slice step must be numeric or undefined");return e instanceof _e?new _e(Dy(e.value,n.value,s.value,a.value)):new Z(Dy(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){let r=this.evaluate(e.object,t),n;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);n=this.evaluate(e.property,t)}else n=new Z(e.property.value);let s;if(r instanceof tt){if(!(n instanceof Z))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof _e||r instanceof Z)if(n instanceof de)s=r.value.at(n.value),r instanceof Z&&(s=new Z(r.value.at(n.value)));else if(n instanceof Z)s=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Z))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof ir?s:new Oe}evaluateSet(e,t){let r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){let n=e.assignee.value;t.setVariable(n,r)}else if(e.assignee.type==="TupleLiteral"){let n=e.assignee;if(!(r instanceof _e))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let s=r.value;if(s.length!==n.value.length)throw new Error(`Too ${n.value.length>s.length?"few":"many"} items to unpack in set`);for(let a=0;a<n.value.length;++a){let o=n.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,s[a])}}else if(e.assignee.type==="MemberExpression"){let n=e.assignee,s=this.evaluate(n.object,t);if(!(s instanceof tt))throw new Error("Cannot assign to member of non-object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Be}evaluateIf(e,t){let r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let r=new on(t),n,s;if(e.iterable.type==="SelectExpression"){let c=e.iterable;s=this.evaluate(c.lhs,r),n=c.test}else s=this.evaluate(e.iterable,r);if(!(s instanceof _e||s instanceof tt))throw new Error(`Expected iterable or object type in for loop: got ${s.type}`);s instanceof tt&&(s=s.keys());let a=[],o=[];for(let c=0;c<s.value.length;++c){let u=new on(r),p=s.value[c],f;if(e.loopvar.type==="Identifier")f=m=>m.setVariable(e.loopvar.value,p);else if(e.loopvar.type==="TupleLiteral"){let m=e.loopvar;if(p.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${p.type}`);let y=p;if(m.value.length!==y.value.length)throw new Error(`Too ${m.value.length>y.value.length?"few":"many"} items to unpack`);f=v=>{for(let x=0;x<m.value.length;++x){if(m.value[x].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${m.value[x].type}`);v.setVariable(m.value[x].value,y.value[x])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);n&&(f(u),!this.evaluate(n,u).__bool__().value)||(a.push(p),o.push(f))}let i="",l=!0;for(let c=0;c<a.length;++c){let u=new Map([["index",new de(c+1)],["index0",new de(c)],["revindex",new de(a.length-c)],["revindex0",new de(a.length-c-1)],["first",new ae(c===0)],["last",new ae(c===a.length-1)],["length",new de(a.length)],["previtem",c>0?a[c-1]:new Oe],["nextitem",c<a.length-1?a[c+1]:new Oe]]);r.setVariable("loop",new tt(u)),o[c](r);try{let p=this.evaluateBlock(e.body,r);i+=p.value}catch(p){if(p instanceof Uy)continue;if(p instanceof By)break;throw p}l=!1}if(l){let c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new Z(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Le((r,n)=>{let s=new on(n);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let o=0;o<e.args.length;++o){let i=e.args[o],l=r[o];if(i.type==="Identifier"){let c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);s.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){let c=i,u=l??a?.value.get(c.key.value)??this.evaluate(c.value,s);s.setVariable(c.key.value,u)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(e.body,s)})),new Be}evaluateCallStatement(e,t){let r=new Le((i,l)=>{let c=new on(l);if(e.callerArgs)for(let u=0;u<e.callerArgs.length;++u){let p=e.callerArgs[u];if(p.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${p.type}`);c.setVariable(p.value,i[u]??new Oe)}return this.evaluateBlock(e.body,c)}),[n,s]=this.evaluateArguments(e.call.args,t);n.push(new ua(s));let a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);let o=new on(t);return o.setVariable("caller",r),a.value(n,o)}evaluateFilterStatement(e,t){let r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new Oe;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 By;case"Continue":throw new Uy;case"IntegerLiteral":return new de(e.value);case"FloatLiteral":return new ze(e.value);case"StringLiteral":return new Z(e.value);case"ArrayLiteral":return new _e(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new $y(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{let r=new Map;for(let[n,s]of e.value){let a=this.evaluate(n,t);if(!(a instanceof Z))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new tt(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Be;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};Ke=`
16
+ `,hD="{%- ",fD=" -%}";TD=class{constructor(e){w(this,"parsed");let t=ON(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=nD(t)}render(e){let t=new on;if(dD(t),e)for(let[s,a]of Object.entries(e))t.set(s,a);return new pD(t).run(this.parsed).value}format(e){return _D(this.parsed,e?.indent||" ")}},Dt=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")}},ED={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"},fi=class Iv{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=At.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=At.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();let n=At.createReadStream(t);this.body=new ReadableStream({start(s){n.on("data",a=>s.enqueue(a)),n.on("end",()=>s.close()),n.on("error",a=>s.error(a))},cancel(){n.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",ED[t]??"application/octet-stream")}clone(){let t=new Iv(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await At.promises.readFile(this.filePath)).buffer}async blob(){let t=await At.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await At.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Qp=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(pe.IS_CRYPTO_AVAILABLE){let o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;let t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,n=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))n.push(o&4294967295);n.length||n.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let s=1,a=0;for(let o=Math.max(624,n.length);o>0;--o,++s,++a)s>=624&&(t[0]=t[623],s=1),a>=n.length&&(a=0),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1664525))+n[a]+a>>>0;for(let o=623;o>0;--o,++s)s>=624&&(t[0]=t[623],s=1),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1566083941))-s>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let n=this.random()*2*Math.PI,s=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*s,this._gauss_next=Math.sin(n)*s}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){let r=32-Math.clz32(t+1),n=this._int32()>>>32-r;for(;n>t;)n=this._int32()>>>32-r;let s=e[t];e[t]=e[n],e[n]=s}}choices(e,t){return e[Pv(this._random_fn,t)]}};rr=new Qp,ba=Object.freeze({Random:Qp,seed:rr.seed.bind(rr),random:rr.random.bind(rr),gauss:rr.gauss.bind(rr),shuffle:rr.shuffle.bind(rr),choices:rr.choices.bind(rr)}),kD=e=>Pv(ba.random,e),CD=new Qp,Rv=class{constructor(e){this.path=e}async match(e){let t=ar.join(this.path,e),r=new fi(t);if(r.exists)return r}async put(e,t,r=void 0){let n=ar.join(this.path,e),s=pe.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=CD._int32().toString(36),o=n+`.tmp.${s}.${a}`;try{let i=t.headers.get("Content-Length"),l=parseInt(i??"0"),c=0;await At.promises.mkdir(ar.dirname(n),{recursive:!0});let u=At.createWriteStream(o),p=t.body.getReader();for(;;){let{done:f,value:m}=await p.read();if(f)break;await new Promise((v,x)=>{u.write(m,M=>{if(M){x(M);return}v()})}),c+=m.length;let y=l?c/l*100:0;r?.({progress:y,loaded:c,total:l})}await new Promise((f,m)=>{u.close(y=>y?m(y):f())}),await At.promises.rename(o,n)}catch(i){try{await At.promises.unlink(o)}catch{}throw i}}async delete(e){let t=ar.join(this.path,e);try{return await At.promises.unlink(t),!0}catch{return!1}}},AD={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"},Gy=100,SD=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;Ov="SHA-256",OD="experimental_transformers-hash-cache",Wy=e=>({algorithm:Ov,value:e}),Hy=(Hd=class{constructor(){so(this,ga,null);w(this,"_getHashCache",()=>(ut(this,ga)??ao(this,ga,caches.open(OD)),ut(this,ga)));w(this,"match",async e=>{let t=await this._getFileHash(e);if(t)try{let[r]=await navigator.crossOriginStorage.requestFileHandles([Wy(t)]),n=await r.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}});w(this,"put",async(e,t)=>{let r=await this._getFileHash(e);if(r){let n=await t.blob();await this._storeBlobInCOS(n,r)}else this._processAndStore(e,t.body)});w(this,"_storeBlobInCOS",async(e,t)=>{let[r]=await navigator.crossOriginStorage.requestFileHandles([Wy(t)],{create:!0}),n=await r.createWritable();await n.write(e),await n.close()});w(this,"_processAndStore",async(e,t)=>{try{let r=[];for await(let a of t)r.push(a);let n=new Blob(r),s=await this._getBlobHash(n);await this._storeBlobInCOS(n,s);try{await(await this._getHashCache()).put(e,new Response(s))}catch{}}catch{}});w(this,"delete",async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}});w(this,"_getFileHash",async e=>{try{let t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();let n=await this._getLfsFileHash(e);return n?(await t.put(e,new Response(n)),n):null}catch{return null}});w(this,"_getLfsFileHash",async e=>{if(!e.includes("/resolve/"))return null;let t=e.replace("/resolve/","/raw/");try{let n=(await fetch(t).then(s=>s.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}});w(this,"_getBlobHash",async e=>{let t=await e.arrayBuffer(),r=await crypto.subtle.digest(Ov,t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")})}},ga=new WeakMap,w(Hd,"isAvailable",()=>typeof navigator<"u"&&"crossOriginStorage"in navigator),Hd);FD=(gv=class{constructor(e){so(this,wa);so(this,ht);ao(this,wa,e),ao(this,ht,new Map)}get(e){if(!ut(this,ht).has(e))return;let t=ut(this,ht).get(e);return ut(this,ht).delete(e),ut(this,ht).set(e,t),t}put(e,t){ut(this,ht).has(e)&&ut(this,ht).delete(e),ut(this,ht).set(e,t),ut(this,ht).size>ut(this,wa)&&ut(this,ht).delete(ut(this,ht).keys().next().value)}delete(e){return ut(this,ht).delete(e)}clear(){ut(this,ht).clear()}},wa=new WeakMap,ht=new WeakMap,gv),ND=100,Ud=new FD(ND);zv=class{constructor(e){if(this.size=e|0,this.size<=1||!Uv(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;r<this.table.length;r+=2){let n=Math.PI*r/this.size;this.table[r]=Math.cos(n),this.table[r+1]=-Math.sin(n)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let n=0;n<this._width;n+=2){let s=this._width-n-2;this._bitrev[r]|=(r>>>n&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let r=t||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)r[n>>>1]=e[n];return r}toComplexArray(e,t){let r=t||this.createComplexArray();for(let n=0;n<r.length;n+=2)r[n]=e[n>>>1],r[n+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size}_transform4(e,t,r){let n=this._csize,a=1<<this._width,o=n/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){let p=c[l];this._singleTransform2(t,e,i,p,a)}else for(i=0,l=0;i<n;i+=o,++l){let p=c[l];this._singleTransform4(t,e,i,p,a,r)}let u=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;let p=o>>>2;for(i=0;i<n;i+=o){let f=i+p-1;for(let m=i,y=0;m<f;m+=2,y+=a){let v=m,x=v+p,M=x+p,T=M+p,A=e[v],C=e[v+1],S=e[x],O=e[x+1],E=e[M],K=e[M+1],$=e[T],V=e[T+1],Q=u[y],G=r*u[y+1],W=S*Q-O*G,D=S*G+O*Q,R=u[2*y],re=r*u[2*y+1],ie=E*R-K*re,F=E*re+K*R,N=u[3*y],z=r*u[3*y+1],Y=$*N-V*z,fe=$*z+V*N,H=A+ie,Ne=C+F,Xe=A-ie,nt=C-F,qe=W+Y,gt=D+fe,Pe=r*(W-Y),ye=r*(D-fe);e[v]=H+qe,e[v+1]=Ne+gt,e[x]=Xe+ye,e[x+1]=nt-Pe,e[M]=H-qe,e[M+1]=Ne-gt,e[T]=Xe-ye,e[T+1]=nt+Pe}}}}_singleTransform2(e,t,r,n,s){let a=e[n],o=e[n+1],i=e[n+s],l=e[n+s+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,n,s,a){let o=s*2,i=s*3,l=e[n],c=e[n+1],u=e[n+s],p=e[n+s+1],f=e[n+o],m=e[n+o+1],y=e[n+i],v=e[n+i+1],x=l+f,M=c+m,T=l-f,A=c-m,C=u+y,S=p+v,O=a*(u-y),E=a*(p-v);t[r]=x+C,t[r+1]=M+S,t[r+2]=T+E,t[r+3]=A-O,t[r+4]=x-C,t[r+5]=M-S,t[r+6]=T-E,t[r+7]=A+O}_realTransform4(e,t,r){let n=this._csize,a=1<<this._width,o=n/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){let f=c[l];this._singleRealTransform2(t,e,i,f>>>1,a>>>1)}else for(i=0,l=0;i<n;i+=o,++l){let f=c[l];this._singleRealTransform4(t,e,i,f>>>1,a>>>1,r)}let u=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;let f=o>>>1,m=f>>>1,y=m>>>1;for(i=0;i<n;i+=o)for(let v=0,x=0;v<=y;v+=2,x+=a){let M=i+v,T=M+m,A=T+m,C=A+m,S=e[M],O=e[M+1],E=e[T],K=e[T+1],$=e[A],V=e[A+1],Q=e[C],G=e[C+1],W=S,D=O,R=u[x],re=r*u[x+1],ie=E*R-K*re,F=E*re+K*R,N=u[2*x],z=r*u[2*x+1],Y=$*N-V*z,fe=$*z+V*N,H=u[3*x],Ne=r*u[3*x+1],Xe=Q*H-G*Ne,nt=Q*Ne+G*H,qe=W+Y,gt=D+fe,Pe=W-Y,ye=D-fe,We=ie+Xe,Yt=F+nt,ke=r*(ie-Xe),Ie=r*(F-nt);if(e[M]=qe+We,e[M+1]=gt+Yt,e[T]=Pe+Ie,e[T+1]=ye-ke,v===0){e[A]=qe-We,e[A+1]=gt-Yt;continue}if(v===y)continue;let An=i+m-v,xs=i+f-v;e[An]=Pe-r*Ie,e[An+1]=-ye-r*ke,e[xs]=qe-r*We,e[xs+1]=-gt+r*Yt}}let p=n>>>1;for(let f=2;f<p;f+=2)e[n-f]=e[f],e[n-f+1]=-e[f+1]}_singleRealTransform2(e,t,r,n,s){let a=e[n],o=e[n+s];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,n,s,a){let o=s*2,i=s*3,l=e[n],c=e[n+s],u=e[n+o],p=e[n+i],f=l+u,m=l-u,y=c+p,v=a*(c-p);t[r]=f+y,t[r+1]=0,t[r+2]=m,t[r+3]=-v,t[r+4]=f-y,t[r+5]=0,t[r+6]=m,t[r+7]=v}},jD=class{constructor(e){let t=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=t;let s=new Float64Array(r),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){let u=(c+1-e)**2/2,p=Math.sqrt(i**2+l**2)**u,f=u*Math.atan2(l,i),m=2*c;s[m]=p*Math.cos(f),s[m+1]=p*Math.sin(f),a[m]=s[m],a[m+1]=-s[m+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new zv(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){let n=this._buffer1,s=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(r)for(let u=0;u<l.length;u+=2){let p=u+1,f=u>>1,m=t[f];n[u]=m*l[u],n[p]=m*l[p]}else for(let u=0;u<l.length;u+=2){let p=u+1;n[u]=t[u]*l[u]-t[p]*l[p],n[p]=t[u]*l[p]+t[p]*l[u]}this._f.transform(a,n);for(let u=0;u<i.length;u+=2){let p=u+1;s[u]=a[u]*i[u]-a[p]*i[p],s[p]=a[u]*i[p]+a[p]*i[u]}this._f.inverseTransform(o,s);for(let u=0;u<o.length;u+=2){let p=o[u+c],f=o[u+c+1],m=l[u],y=l[u+1];e[u]=p*m-f*y,e[u+1]=p*y+f*m}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},qD=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Uv(e),this.isPowerOfTwo?(this.fft=new zv(e),this.outputBufferSize=2*e):(this.fft=new jD(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};QD=function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0,u=(l&32768)<<16,p=(l&31744)>>10,f=l&1023;if(p===31)c=u|2139095040|f<<13;else if(p===0)if(f===0)c=u;else{let m=113;for(;!(f&1024);)f<<=1,--m;f&=-1025,c=u|m<<23|f<<13}else c=u|p+112<<23|f<<13;o[0]=c,e[l]=i[0]}}let r=t.length,n=e,s=new Float32Array(r);for(let a=0;a<r;++a)s[a]=n[t[a]];return s}}(),$v={};cs($v,{default:()=>JD});JD={};ZD=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"}});eB={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Lt=[],Qy=Symbol.for("onnxruntime");if(Qy in globalThis)as=globalThis[Qy];else if(pe.IS_NODE_ENV){switch(as=$v,process.platform){case"win32":Lt.push("dml");break;case"linux":process.arch==="x64"&&Lt.push("cuda");break;case"darwin":Lt.push("coreml");break}Lt.push("webgpu"),Lt.push("cpu"),Ip=["cpu"]}else as=Id,pe.IS_WEBNN_AVAILABLE&&Lt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),pe.IS_WEBGPU_AVAILABLE&&Lt.push("webgpu"),Lt.push("wasm"),Ip=["wasm"];tB=as.InferenceSession;Jy=Promise.resolve(),Jn=null;Xy=Promise.resolve();He=as?.env;if(He){let e=function(t){let r=Gv(t);He.logLevel=eB[r]};if(He.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&He.versions?.web&&!He.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${He.versions.web}/dist/`;He.wasm.wasmPaths=pe.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}He.wasm.proxy=!1}He.webgpu&&(He.webgpu.powerPreference="high-performance"),e(ge.logLevel??Ft.WARNING),ge.backends.onnx={...He,setLogLevel:e}}Rr=async(e,t,r)=>{let n=await jv(new Uint8Array(e),t);return async s=>{let a=Jp(),o=Object.fromEntries(Object.entries(s).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await qv(n,o);return Array.isArray(r)?r.map(l=>new q(i[l])):new q(i[r])}},dn=(Kd=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Rr([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=Rr([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=Rr([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=Rr([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=Rr([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=Rr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Rr([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=Rr([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}},w(Kd,"session_options",{}),Kd),sB=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"}),zd=pe.IS_NODE_ENV?"cpu":"wasm";aB=function(){let e;return async function(){if(e===void 0)if(!pe.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}}(),ft=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Yy=ft.fp32,Zy=Object.freeze({[sB.wasm]:ft.q8}),Pp=Object.freeze({[ft.fp32]:"",[ft.fp16]:"_fp16",[ft.int8]:"_int8",[ft.uint8]:"_uint8",[ft.q8]:"_quantized",[ft.q4]:"_q4",[ft.q4f16]:"_q4f16",[ft.bnb4]:"_bnb4"});is=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}),q=class Ue{constructor(...t){w(this,"ort_tensor");return Wv(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new Fd(t[0],t[1],t[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let s=Number(n);if(Number.isInteger(s))return r._getitem(s)}return r[n]},set:(r,n,s)=>r[n]=s})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[t,...r]=this.dims;if(r.length>0){let n=r.reduce((s,a)=>s*a);for(let s=0;s<t;++s)yield this._subarray(s,n,r)}else yield*this.data}_getitem(t){let[r,...n]=this.dims;if(t=sr(t,r),n.length>0){let s=n.reduce((a,o)=>a*o);return this._subarray(t,s,n)}else return new Ue(this.type,[this.data[t]],n)}indexOf(t){let r=this.data;for(let n=0;n<r.length;++n)if(r[n]==t)return n;return-1}_subarray(t,r,n){let s=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(s,a):this.data.slice(s,a);return new Ue(this.type,o,n)}item(){let 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 oB(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]=t(r[n],n,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]*=t;return this}div(t){return this.clone().div_(t)}div_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]/=t;return this}add(t){return this.clone().add_(t)}add_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){let r=this.data;for(let n=0;n<r.length;++n)r[n]-=t;return this}clone(){return new Ue(this.type,this.data.slice(),this.dims.slice())}slice(...t){let r=[],n=[];for(let u=0;u<this.dims.length;++u){let p=t[u];if(p==null)n.push([0,this.dims[u]]),r.push(this.dims[u]);else if(typeof p=="number")p=sr(p,this.dims[u],u),n.push([p,p+1]);else if(Array.isArray(p)&&p.length===2){let[f,m]=p;if(f=f===null?0:sr(f,this.dims[u],u,!1),m=m===null?this.dims[u]:sr(m,this.dims[u],u,!1),f>m)throw new Error(`Invalid slice: ${p}`);let y=[Math.max(f,0),Math.min(m,this.dims[u])];n.push(y),r.push(y[1]-y[0])}else throw new Error(`Invalid slice: ${p}`)}let s=n.map(([u,p])=>p-u),a=s.reduce((u,p)=>u*p),o=this.data,i=new o.constructor(a),l=this.stride(),c=!0;for(let u=1;u<s.length;++u)if(n[u][0]!==0||n[u][1]!==this.dims[u]){c=!1;break}if(c){let u=n[0][0]*l[0],p=n[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(u,p));else if(Array.isArray(o)){let f=o.slice(u,p);for(let m=0;m<f.length;++m)i[m]=f[m]}else throw new Error("Unsupported data type for slicing")}else for(let u=0;u<a;++u){let p=0;for(let f=s.length-1,m=u;f>=0;--f){let y=s[f];p+=(m%y+n[f][0])*l[f],m=Math.floor(m/y)}i[u]=o[p]}return new Ue(this.type,i,r)}permute(...t){return Qv(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,n=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);let s=this.data,a=s instanceof BigInt64Array||s instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a?(o=(p,f)=>p+f,i=0n):(o=(p,f)=>p+f**t,i=0),r===null){let p=s.reduce(o,i);return t!==1&&(p=p**(1/t)),new Ue(this.type,[p],[])}let[l,c,u]=pa(o,this,r,n);if(t!==1)for(let p=0;p<c.length;++p)c[p]=c[p]**(1/t);return new Ue(l,c,u)}normalize_(t=2,r=1){r=sr(r,this.dims.length);let n=this.norm(t,r,!0),s=this.data,a=n.data;for(let o=0;o<s.length;++o){let i=0;for(let l=this.dims.length-1,c=o,u=1;l>=0;--l){let p=this.dims[l];if(l!==r){let f=c%p;i+=f*u,u*=this.dims[l]}c=Math.floor(c/p)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return $d(this.dims)}squeeze(t=null){return new Ue(this.type,this.data,ev(this.dims,t))}squeeze_(t=null){return this.dims=ev(this.dims,t),this}unsqueeze(t){return new Ue(this.type,this.data,tv(this.dims,t))}unsqueeze_(t){return this.dims=tv(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;s<t.length;++s)if(t[s]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=s}let n=this.data;if(r!==-1){let s=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=n.length/s}return new Ue(this.type,n,t)}neg_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){let r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]>t?1:0;return new Ue("bool",r,this.dims)}lt(t){let r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]<t?1:0;return new Ue("bool",r,this.dims)}clamp_(t,r){let n=this.data;for(let s=0;s<n.length;++s)n[s]=Math.min(Math.max(n[s],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return ki(this,t,r)}min(t=null,r=!1){if(t===null){let o=Sp(this.data)[0];return new Ue(this.type,[o],[])}let[n,s,a]=pa((o,i)=>Math.min(o,i),this,t,r,1/0);return new Ue(n,s,a)}max(t=null,r=!1){if(t===null){let o=Ge(this.data)[0];return new Ue(this.type,[o],[])}let[n,s,a]=pa((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Ue(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let n=Sp(this.data)[1];return new Ue("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let n=Ge(this.data)[1];return new Ue("int64",[BigInt(n)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(u=>u===1)){if(t.length===this.dims.length)return this.clone();let u=t.length-this.dims.length,p=Array(u).fill(1).concat(this.dims);return new Ue(this.type,this.data.slice(),p)}let r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((u,p)=>u*t[p]),a=s.reduce((u,p)=>u*p,1),o=this.data,i=new o.constructor(a),l=$d(n),c=$d(s);for(let u=0;u<a;++u){let p=u,f=0;for(let m=0;m<s.length;++m){let y=Math.floor(p/c[m]);p=p%c[m];let v=y%n[m];f+=v*l[m]}i[u]=o[f]}return new Ue(this.type,i,s)}tile(...t){if(t.length<this.dims.length){let r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!is.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r,n=["int64","uint64"].includes(this.type),s=["int64","uint64"].includes(t);if(n&&!s)r=Number;else if(!n&&s)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Ue(t,QD(this.data),this.dims);return new Ue(t,is[t].from(this.data,r),this.dims)}};Uo=e=>new q("int64",e,[e.length]);uB=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];le=class extends Dt{constructor(t,r){super();w(this,"return_token_type_ids",!1);w(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new SN(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=sn(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=sn(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=sn(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=sn(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=sn(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=sn(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let s=Object.create(null);for(let{name:a,template:o}of this.chat_template){if(typeof a!="string"||typeof o!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[a]=o}this.chat_template=s}this._compiled_template_cache=new Map;let n=hB(this._tokenizer);this.all_special_ids=n.map(s=>s.id),this.all_special_tokens=n.map(s=>s.content)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){let i=await eb(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,{text_pair:r=null,add_special_tokens:n=!0,padding:s=!1,truncation:a=null,max_length:o=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let c=Array.isArray(t),u;if(c){if(t.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(t.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=t.map((f,m)=>this._encode_plus(f,{text_pair:r[m],add_special_tokens:n,return_token_type_ids:l}))}else u=t.map(f=>this._encode_plus(f,{add_special_tokens:n,return_token_type_ids:l}))}else{if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:l})]}if(o===null?o=this.model_max_length:a===null&&(s===!0?(ce.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),o=this.model_max_length):s===!1&&(ce.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),a=!0)),s===!0&&(o=Math.min(Ge(u.map(f=>f.input_ids.length))[0],o??1/0)),o=Math.min(o,this.model_max_length??1/0),s||a)for(let f=0;f<u.length;++f)u[f].input_ids.length!==o&&(u[f].input_ids.length>o?a&&pB(u[f],o):s&&dB(u[f],o,m=>m==="input_ids"?this.pad_token_id:0,this.padding_side));let p={};if(i){if(!(s&&a)&&u.some(m=>{for(let y of Object.keys(m))if(m[y].length!==u[0][y]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let f=[u.length,u[0].input_ids.length];for(let m of Object.keys(u[0]))p[m]=new q("int64",BigInt64Array.from(u.flatMap(y=>y[m]).map(BigInt)),f)}else{for(let f of Object.keys(u[0]))p[f]=u.map(m=>m[f]);if(!c)for(let f of Object.keys(p))p[f]=p[f][0]}return p}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){let{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s??this.return_token_type_ids});return{input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:n})}encode(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s}).ids}batch_decode(t,r={}){return t instanceof q&&(t=t.tolist()),t.map(n=>this.decode(n,r))}decode(t,r={}){if(t instanceof q&&(t=tb(t)),!Array.isArray(t)||t.length===0||!_L(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let n=this.chat_template;if(t!==null&&Object.hasOwn(n,t))t=n[t];else if(t===null)if(r!==null&&"tool_use"in n)t=n.tool_use;else if("default"in n)t=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}else if(t===null)if(this.chat_template)t=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return t}apply_chat_template(t,{tools:r=null,documents:n=null,chat_template:s=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:u=!0,return_dict:p=!0,tokenizer_kwargs:f={},...m}={}){if(s=this.get_chat_template({chat_template:s,tools:r}),typeof s!="string")throw Error(`chat_template must be a string, but got ${typeof s}`);let y=this._compiled_template_cache.get(s);y===void 0&&(y=new TD(s),this._compiled_template_cache.set(s,y));let v=Object.create(null);for(let M of uB){let T=sn(this.config,M);T&&(v[M]=T)}let x=y.render({messages:t,add_generation_prompt:a,tools:r,documents:n,...v,...m});if(o){let M=this._call(x,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:u,...f});return p?M:M.input_ids}return x}};rb={};cs(rb,{AlbertTokenizer:()=>nb,AutoTokenizer:()=>Ae,BartTokenizer:()=>sb,BertTokenizer:()=>ab,BlenderbotSmallTokenizer:()=>ob,BlenderbotTokenizer:()=>ib,BloomTokenizer:()=>lb,CLIPTokenizer:()=>ub,CamembertTokenizer:()=>cb,CodeGenTokenizer:()=>pb,CodeLlamaTokenizer:()=>db,CohereTokenizer:()=>hb,ConvBertTokenizer:()=>fb,DebertaTokenizer:()=>_b,DebertaV2Tokenizer:()=>mb,DistilBertTokenizer:()=>gb,ElectraTokenizer:()=>wb,EsmTokenizer:()=>yb,FalconTokenizer:()=>vb,GPT2Tokenizer:()=>xb,GPTNeoXTokenizer:()=>Mb,GemmaTokenizer:()=>bb,HerbertTokenizer:()=>Tb,LlamaTokenizer:()=>Eb,M2M100Tokenizer:()=>kb,MBart50Tokenizer:()=>Ab,MBartTokenizer:()=>oh,MPNetTokenizer:()=>Pb,MarianTokenizer:()=>Cb,MgpstrTokenizer:()=>Sb,MobileBertTokenizer:()=>Ib,NllbTokenizer:()=>Rb,NougatTokenizer:()=>Ob,PreTrainedTokenizer:()=>le,Qwen2Tokenizer:()=>Lb,RoFormerTokenizer:()=>Nb,RobertaTokenizer:()=>Fb,SiglipTokenizer:()=>Db,SpeechT5Tokenizer:()=>Bb,SqueezeBertTokenizer:()=>Ub,T5Tokenizer:()=>zb,TokenizersBackend:()=>le,VitsTokenizer:()=>$b,Wav2Vec2CTCTokenizer:()=>Vb,WhisperTokenizer:()=>jb,XLMRobertaTokenizer:()=>qb,XLMTokenizer:()=>Wb});nb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},sb=class extends le{},ab=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},ob=class extends le{},ib=class extends le{},lb=class extends le{},cb=class extends le{},ub=class extends le{},db=class extends le{},pb=class extends le{},hb=class extends le{},fb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},mb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},_b=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},gb=class extends le{},wb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},yb=class extends le{},vb=class extends le{},bb=class extends le{},Mb=class extends le{},xb=class extends le{},Tb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},Eb=class extends le{constructor(){super(...arguments);w(this,"padding_side","left")}},kb=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return ah(this,e,t,r)}},Cb=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),ce.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){let[n,s]=r;return this.supported_language_codes.includes(n)||ce.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),jt([n],super._encode_text(s))}}},oh=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return ah(this,e,t,r)}},Ab=class extends oh{},Sb=class extends le{},Ib=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},Pb=class extends le{},Rb=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return ah(this,e,t,r)}},Ob=class extends le{},Lb=class extends le{},Fb=class extends le{},Nb=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},Db=class extends le{},Bb=class extends le{},Ub=class extends le{constructor(){super(...arguments);w(this,"return_token_type_ids",!0)}},zb=class extends le{},fB=class extends Kt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},$b=class extends le{constructor(e,t){super(e,t),this._tokenizer.decoder=new fB({type:"VitsDecoder"})}},Vb=class extends le{},Gb=[["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"]],oi=new Map(Gb),mB=new Map([...Gb.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"]]);gB="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",rv=new RegExp(`^[${gB}]+$`,"gu"),jb=class extends le{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}let l=[],c=i(),u=0,p=this.timestamp_begin,m=p+1500,y=[],v=[],x=!1,M=null,T=new Set(this.all_special_ids);for(let S of e){let O=S.tokens,E=o?S.token_timestamps:null,K=null,$=p;if("stride"in S){let[G,W,D]=S.stride;if(u-=W,M=G-D,W&&($=W/n+p),D)for(let R=O.length-1;R>=0;--R){let re=Number(O[R]);if(re>=p){if(K!==null&&(re-p)*n<M)break;K=re}}}let V=[],Q=[];for(let G=0;G<O.length;++G){let W=Number(O[G]);if(T.has(W)){let D=this.decode([W]),R=oi.get(D.slice(2,-2));if(R!==void 0){if(a!==null&&R!==a&&!t){y.push(V);let re=this.findLongestCommonSequence(y)[0],ie=this.decode(re);c.text=ie,l.push(c),y=[],V=[],c=i()}a=c.language=R}}else if(W>=p&&W<=m){let D=(W-p)*n+u,R=da(D,2);if(K!==null&&W>=K)x=!0;else if(x||y.length>0&&W<$)x=!1;else if(c.timestamp[0]===null)c.timestamp[0]=R;else if(R!==c.timestamp[0]){c.timestamp[1]=R,y.push(V),o&&v.push(Q);let[re,ie]=this.findLongestCommonSequence(y,v),F=this.decode(re);c.text=F,o&&(c.words=this.collateWordTimestamps(re,ie,a)),l.push(c),y=[],V=[],v=[],Q=[],c=i()}}else if(V.push(W),o){let D=da(E[G]+u,2),R;if(G+1<E.length){R=da(E[G+1]+u,2);let re=this.decode([W]);rv.test(re)&&(R=da(Math.min(D+n,R),2))}else R=null;Q.push([D,R])}}if("stride"in S){let[G,W,D]=S.stride;u+=G-D}V.length>0?(y.push(V),o&&v.push(Q)):y.every(G=>G.length===0)&&(c=i(),y=[],V=[],v=[],Q=[])}if(y.length>0){if(s&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[S,O]=this.findLongestCommonSequence(y,v),E=this.decode(S);c.text=E,o&&(c.words=this.collateWordTimestamps(S,O,a)),l.push(c)}let A=Object.create(null),C=l.map(S=>S.text).join("");if(t||r){for(let S=0;S<l.length;++S){let O=l[S];t||delete O.timestamp,r||delete O.language}if(o){let S=[];for(let O of l)for(let E of O.words)S.push(E);A={chunks:S}}else A={chunks:l}}return[C,A]}findLongestCommonSequence(e,t=null){let r=e[0],n=r.length,s=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){let c=e[l],u=0,p=[n,n,0,0],f=c.length;for(let A=1;A<n+f;++A){let C=Math.max(0,n-A),S=Math.min(n,n+f-A),O=r.slice(C,S),E=Math.max(0,A-n),K=Math.min(f,A),$=c.slice(E,K);if(O.length!==$.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let V;a?V=O.filter((W,D)=>W===$[D]&&i[C+D]<=t[l][E+D]).length:V=O.filter((W,D)=>W===$[D]).length;let Q=A/1e4,G=V/A+Q;V>1&&G>u&&(u=G,p=[C,S,E,K])}let[m,y,v,x]=p,M=Math.floor((y+m)/2),T=Math.floor((x+v)/2);s.push(...r.slice(0,M)),r=c.slice(T),n=r.length,a&&(o.push(...i.slice(0,M)),i=t[l].slice(T))}return s.push(...r),a?(o.push(...i),[s,o]):[s,[]]}collateWordTimestamps(e,t,r){let[n,s,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<n.length;++i){let l=a[i];o.push({text:n[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){t=t??"english";let s,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[s,a,o]=this.splitTokensOnUnicode(e):[s,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(s,a,o,r,n)}decode(e,t){let r;return t?.decode_with_timestamps?(e instanceof q&&(e=tb(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){let r=t?.time_precision??.02,n=this.all_special_ids.at(-1)+1,s=[[]];for(let a of e)if(a=Number(a),a>=n){let o=((a-n)*r).toFixed(2);s.push(`<|${o}|>`),s.push([])}else s[s.length-1].push(a);return s=s.map(a=>typeof a=="string"?a:super.decode(a,t)),s.join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),r="\uFFFD",n=[],s=[],a=[],o=[],i=[],l=0;for(let c=0;c<e.length;++c){let u=e[c];o.push(u),i.push(c);let p=this.decode(o,{decode_with_timestamps:!0});(!p.includes(r)||t[l+p.indexOf(r)]===r)&&(n.push(p),s.push(o),a.push(i),o=[],i=[],l+=p.length)}return[n,s,a]}splitTokensOnSpaces(e){let[t,r,n]=this.splitTokensOnUnicode(e),s=[],a=[],o=[];for(let i=0;i<t.length;++i){let l=t[i],c=r[i],u=n[i],p=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),f=l.startsWith(" "),m=l.trim(),y=rv.test(m);if(p||f||y||s.length===0)s.push(l),a.push(c),o.push(u);else{let v=s.length-1;s[v]+=l,a[v].push(...c),o[v].push(...u)}}return[s,a,o]}mergePunctuations(e,t,r,n,s){let a=structuredClone(e),o=structuredClone(t),i=structuredClone(r),l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=jt(o[l],o[c]),i[c]=jt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&s.includes(a[c])?(a[l]+=a[c],o[l]=jt(o[l],o[c]),i[l]=jt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(u=>u),o.filter(u=>u.length>0),i.filter(u=>u.length>0)]}},qb=class extends le{},Wb=class extends le{constructor(t,r){super(t,r);w(this,"return_token_type_ids",!0);ce.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Ae=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){let[o,i]=await eb(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",c=rb[l];return c||(ce.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=le),new c(o,i)}},Ci="https://github.com/huggingface/transformers.js/issues/new/choose",ih="preprocessor_config.json",_a=ih,wB="processor_config.json",yB="chat_template.jinja",Se=(Zs=class extends Dt{constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(let r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){let[r,n,s]=await Promise.all([this.uses_processor_config?yr(e,wB,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?Nv(e,yB,!0,t):null]);return new this(r,n,s)}},w(Zs,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),w(Zs,"uses_processor_config",!1),w(Zs,"uses_chat_template_file",!1),Zs),Rp={};cs(Rp,{ChatterboxProcessor:()=>pM,Florence2Processor:()=>ax,Gemma3nProcessor:()=>ox,Glm46VProcessor:()=>ix,GraniteSpeechProcessor:()=>lx,GroundingDinoProcessor:()=>cx,Idefics3Processor:()=>Fp,JinaCLIPProcessor:()=>dx,Lfm2VlProcessor:()=>px,LlavaProcessor:()=>hx,MgpstrProcessor:()=>fx,MoonshineProcessor:()=>mx,OwlViTProcessor:()=>_x,PaliGemmaProcessor:()=>gx,Phi3VProcessor:()=>wx,PixtralProcessor:()=>yx,Processor:()=>Se,PyAnnoteProcessor:()=>vx,Qwen2VLProcessor:()=>Ri,Qwen2_5_VLProcessor:()=>Ah,Qwen3VLProcessor:()=>bx,Sam2Processor:()=>Ih,Sam2VideoProcessor:()=>Mx,SamProcessor:()=>Sh,SmolVLMProcessor:()=>Fp,SpeechT5Processor:()=>xx,UltravoxProcessor:()=>Tx,VLChatProcessor:()=>ux,VoxtralProcessor:()=>Ex,VoxtralRealtimeProcessor:()=>kx,Wav2Vec2Processor:()=>Cx,Wav2Vec2ProcessorWithLM:()=>Ax,WhisperProcessor:()=>Sx});ct=class extends Dt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let r=await yr(e,ih,!0,t);return new this(r)}};lh={};cs(lh,{ASTFeatureExtractor:()=>Yb,ChatterboxFeatureExtractor:()=>Zb,ClapFeatureExtractor:()=>eM,DacFeatureExtractor:()=>uh,EncodecFeatureExtractor:()=>ch,FeatureExtractor:()=>ct,Gemma3nAudioFeatureExtractor:()=>tM,GraniteSpeechFeatureExtractor:()=>rM,MoonshineFeatureExtractor:()=>nM,ParakeetFeatureExtractor:()=>sM,PyAnnoteFeatureExtractor:()=>dh,SeamlessM4TFeatureExtractor:()=>aM,SnacFeatureExtractor:()=>oM,SpeechT5FeatureExtractor:()=>iM,VoxtralRealtimeFeatureExtractor:()=>uM,Wav2Vec2FeatureExtractor:()=>lM,WeSpeakerFeatureExtractor:()=>cM,WhisperFeatureExtractor:()=>dM});vB=()=>{},bB={fromWeb:vB},MB=()=>{},xB=MB;EB={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,n=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*n:3*e/200};kB={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,n=Math.log(6.4)/27)=>e>=r?t*Math.exp(n*(e-r)):200*e/3};Xb=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,s)=>n+s.length,0),t=new Float32Array(e),r=0;for(let n of this.audio)t.set(n,r),r+=n.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),RB(e,this.sampling_rate)}async save(e){return Hb(e,this.toBlob())}},Yb=class extends ct{constructor(e){super(e);let t=this.config.sampling_rate,r=or(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=br(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return vr(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){bt(e,"ASTFeatureExtractor");let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,n=t.data;for(let s=0;s<n.length;++s)n[s]=(n[s]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},ch=class extends ct{async _call(e){bt(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let 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}).`);let r=[1,t,e.length/t];return{input_values:new q("float32",e,r)}}},Zb=class extends ct{async _call(e){bt(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new q("float32",e,t)}}},eM=class extends ct{constructor(e){super(e),this.mel_filters=or(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=or(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=br(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,n){let s,a=!1,o=e.length-t;if(o>0)if(r==="rand_trunc"){a=!0;let i=Math.floor(ba.random()*(o+1));e=e.subarray(i,i+t),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(o<0){let i=new Float64Array(t);if(i.set(e),n==="repeat")for(let l=e.length;l<t;l+=e.length)i.set(e.subarray(0,Math.min(e.length,t-l)),l);else if(n==="repeatpad")for(let l=e.length;l<-o;l+=e.length)i.set(e,l);e=i}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return s.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return vr(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return bt(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},uh=class extends ch{},tM=class extends ct{constructor(e){super(e);let{fft_length:t,feature_size:r,min_frequency:n,max_frequency:s,sampling_rate:a,frame_length:o}=this.config,i=or(Math.floor(1+t/2),r,n,s,a,null,"htk",!1);this.mel_filters=i,this.window=br(o,"hann")}async _extract_fbank_features(e,t){return vr(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:r=!0,padding:n=!0,pad_to_multiple_of:s=128}={}){if(bt(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),n&&e.length%s!==0){let i=s-e.length%s,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}let a=await this._extract_fbank_features(e,this.config.max_length),o=lt([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},rM=class extends ct{constructor(e){super(e);let{n_fft:t,win_length:r,n_mels:n,sample_rate:s}=e.melspec_kwargs;this.mel_filters=or(Math.floor(1+t/2),n,0,s/2,s,null,"htk");let a=br(r,"hann");this.window=new Float64Array(t);let o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){bt(e,"GraniteSpeechFeatureExtractor");let{n_fft:t,hop_length:r,n_mels:n}=this.config.melspec_kwargs,s=1+Math.floor((e.length-1)/r),a=s-s%2;return{input_features:(await vr(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}},nM=class extends ct{async _call(e){bt(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new q("float32",e,t)}}},OB=1e-5,sM=class extends ct{constructor(e){var n;super(e),(n=this.config).mel_filters??(n.mel_filters=or(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));let t=br(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await vr(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){bt(e,"ParakeetFeatureExtractor");let t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,r*t.dims[1]);let[s,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let u=0;u<r;++u){let p=u*a;for(let f=0;f<a;++f){let m=n[p+f];o[f]+=m,i[f]+=m*m}}let l=r>1?r-1:1;for(let u=0;u<a;++u){let p=o[u]/r,f=(i[u]-r*p*p)/l,y=1/(Math.sqrt(f)+OB);for(let v=0;v<r;++v){let x=v*a+u;n[x]=(n[x]-p)*y}}let c=new BigInt64Array(s);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new q("int64",c,[1,s])}}},dh=class extends ct{async _call(e){bt(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new q("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let r=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(let s of e.tolist()){let a=[],o=-1;for(let i=0;i<s.length;++i){let l=rt(s[i]),[c,u]=Ge(l),[p,f]=[i,i+1];u!==o?(o=u,a.push({id:u,start:p,end:f,score:c})):(a.at(-1).end=f,a.at(-1).score+=c)}n.push(a.map(({id:i,start:l,end:c,score:u})=>({id:i,start:l*r,end:c*r,confidence:u/(c-l)})))}return n}},aM=class extends ct{constructor(e){super(e);let t=this.config.sampling_rate,r=or(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=br(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),vr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:s=!0}={}){bt(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[m,y]=a.dims,v=a.data;for(let x=0;x<y;++x){let M=0;for(let S=0;S<m;++S)M+=v[S*y+x];let T=M/m,A=0;for(let S=0;S<m;++S)A+=(v[S*y+x]-T)**2;A/=m-1;let C=Math.sqrt(A+1e-7);for(let S=0;S<m;++S){let O=S*y+x;v[O]=(v[O]-T)/C}}}let o;if(t){let[m,y]=a.dims,v=a.data,x=m%r;if(x>0){let M=new Float32Array(y*(m+x));M.set(v),M.fill(this.config.padding_value,v.length);let T=m+x;a=new q(a.type,M,[T,y]),s&&(o=new q("int64",new BigInt64Array(T),[1,T]),o.data.fill(1n,0,m))}}let[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}).`);let p=a.view(1,Math.floor(i/c),l*c),f={input_features:p};if(s){let m=p.dims[1],y=new BigInt64Array(m);if(o){let v=o.data;for(let x=1,M=0;x<i;x+=c,++M)y[M]=v[x]}else y.fill(1n);f.attention_mask=new q("int64",y,[1,m])}return f}},oM=class extends uh{},iM=class extends ct{},lM=class extends ct{_zero_mean_unit_var_norm(e){let r=e.reduce((s,a)=>s+a,0)/e.length,n=e.reduce((s,a)=>s+(a-r)**2,0)/e.length;return e.map(s=>(s-r)/Math.sqrt(n+1e-7))}async _call(e){bt(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let r=[1,t.length];return{input_values:new q("float32",t,r),attention_mask:new q("int64",new BigInt64Array(t.length).fill(1n),r)}}},cM=class extends ct{constructor(e){super(e);let t=this.config.sampling_rate,r=or(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=br(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),vr(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){bt(e,"WeSpeakerFeatureExtractor");let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=t.mean(1).data,n=t.data,[s,a,o]=t.dims;for(let i=0;i<s;++i){let l=i*a*o,c=i*o;for(let u=0;u<a;++u){let p=l+u*o;for(let f=0;f<o;++f)n[p+f]-=r[c+f]}}}return{input_features:t}}},uM=class extends ct{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=or(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=br(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:r,hop_length:n,mel_filters:s,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/n:(e.length-r)/n);return await vr(e,this.window,r,n,{power:2,mel_filters:s,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return bt(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},dM=class extends ct{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=or(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=br(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await vr(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}={}){bt(e,"WhisperFeatureExtractor");let r,n=t??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&ce.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Bt=class{static async from_pretrained(e,t={}){let r=await yr(e,ih,!0,t),n=r.feature_extractor_type,s=lh[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Ci}.`);return new s(r)}},pM=(jo=class extends Se{async _call(e,t=null){let r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},w(jo,"tokenizer_class",Ae),w(jo,"feature_extractor_class",Bt),jo),Op={};if(pe.IS_WEB_ENV)ln=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Or=self.createImageBitmap,hM=self.ImageData;else if(Op)Or=async e=>{let r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new Mt(new Uint8ClampedArray(n),s.width,s.height,s.channels);return r!==void 0&&r!==s.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");LB={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},FB=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Mt=class nr{constructor(t,r,n,s){this.data=t,this.width=r,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(t){if(t instanceof nr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!pe.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new nr(n,t.width,t.height,4)}static async fromURL(t){let r=await ma(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);let n=await r.blob();return this.fromBlob(n)}static async fromBlob(t){if(pe.IS_WEB_ENV){let r=await Or(t),n=ln(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Op(await t.arrayBuffer());return await Or(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new nr(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;let t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r<this.data.length;r+=this.channels){let s=this.data[r],a=this.data[r+1],o=this.data[r+2];t[n++]=Math.round(.2989*s+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r];break;case 4:for(let r=0,n=0;r<this.data.length;r+=4)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2];break;default:throw 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;let t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=255;break;case 3:for(let r=0,n=0;r<this.data.length;r+=3)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2],t[n++]=255;break;default:throw 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}`);let r=this.data,n=t.data,s=this.width*this.height;if(this.channels===3){let a=new Uint8ClampedArray(s*4);for(let o=0,i=0,l=0;o<s;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=n[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<s;++a)r[4*a+3]=n[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:n=2}={}){if(this.width===t&&this.height===r)return this;let s=LB[n]??n,a=xy(t),o=xy(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),pe.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=ln(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new nr(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(s){case"box":case"hamming":(s==="box"||s==="hamming")&&(ce.warn(`Resampling method ${s} is not yet supported. Using bilinear instead.`),s="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:s});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${s} is not supported.`)}return await Or(i)}}async pad([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.max(n,0),s=Math.max(s,0),t===0&&r===0&&n===0&&s===0)return this;if(pe.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+n+s,c=ln(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new nr(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{let a=this.toSharp().extend({left:t,right:r,top:n,bottom:s});return await Or(a)}}async crop([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.min(n,this.width-1),s=Math.min(s,this.height-1),t===0&&r===0&&n===this.width-1&&s===this.height-1)return this;let a=n-t+1,o=s-r+1;if(pe.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=ln(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new nr(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{let i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await Or(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;let n=(this.width-t)/2,s=(this.height-r)/2;if(pe.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=ln(t,r).getContext("2d"),l=0,c=0,u=0,p=0;return n>=0?l=n:u=-n,s>=0?c=s:p=-s,i.drawImage(o,l,c,t,r,u,p,t,r),new nr(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(n>=0&&s>=0)a=a.extract({left:Math.floor(n),top:Math.floor(s),width:t,height:r});else if(n<=0&&s<=0){let o=Math.floor(-s),i=Math.floor(-n);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;s<0?(o[0]=Math.floor(-s),o[1]=r-this.height-o[0]):i=Math.floor(s);let l=[0,0],c=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):c=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await Or(a)}}async toBlob(t="image/png",r=1){if(!pe.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new q("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!pe.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let t=this.clone().rgba(),r=ln(t.width,t.height),n=new hM(t.data,t.width,t.height);return r.getContext("2d").putImageData(n,0,0),r}split(){let{data:t,width:r,height:n,channels:s}=this,a=t.constructor,o=t.length/s,i=Array.from({length:s},()=>new a(o));for(let l=0;l<o;++l){let c=s*l;for(let u=0;u<s;++u)i[u][l]=t[c+u]}return i.map(l=>new nr(l,r,n,1))}_update(t,r,n,s=null){return this.data=t,this.width=r,this.height=n,s!==null&&(this.channels=s),this}clone(){return new nr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(pe.IS_WEB_ENV){if(pe.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=t.split(".").pop().toLowerCase(),n=FB.get(r)??"image/png",s=await this.toBlob(n);return Hb(t,s)}else if(pe.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(pe.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Op(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},NB=Mt.read.bind(Mt);ue=class extends Dt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){let n=e.height,s=e.width,a=t.height,o=t.width,i=Math.min(n,a),l=Math.min(s,o);return i===n&&l===s?e:(n>s?l=Math.floor(s*i/n):s>n&&(i=Math.floor(n*l/s)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){let r=e.clone().grayscale(),n=Sp(r.data)[0],a=Ge(r.data)[0]-n;if(a===0)return e;let o=t/255,i=r.width,l=r.height,c=0,u=0,p=r.data;for(let f=0;f<r.height;++f){let m=f*r.width;for(let y=0;y<r.width;++y)(p[m+y]-n)/a<o&&(i=Math.min(i,y),l=Math.min(l,f),c=Math.max(c,y),u=Math.max(u,f))}return e=await e.crop([i,l,c,u]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){let[o,i,l]=t,c,u;if(typeof r=="number"?(c=r,u=r):r==="square"?c=u=Math.max(o,i):(c=r.width,u=r.height),c!==i||u!==o){let p=new Float32Array(c*u*l);if(Array.isArray(a))for(let y=0;y<p.length;++y)p[y]=a[y%l];else a!==0&&p.fill(a);let[f,m]=s?[Math.floor((c-i)/2),Math.floor((u-o)/2)]:[0,0];for(let y=0;y<o;++y){let v=(y+m)*c,x=y*i;for(let M=0;M<i;++M){let T=(v+M+f)*l,A=(x+M)*l;for(let C=0;C<l;++C)p[T+C]=e[A+C]}}if(n==="symmetric"){if(s)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let y=o-1,v=i-1;for(let x=0;x<u;++x){let M=x*c,T=pi(x,y)*i;for(let A=0;A<c;++A){if(x<o&&A<i)continue;let C=(M+A)*l,S=(T+pi(A,v))*l;for(let O=0;O<l;++O)p[C+O]=e[S+O]}}}e=p,t=[u,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){let[r,n]=e.size,s,a;if(this.do_thumbnail){let{height:o,width:i}=t;s=Math.min(o,i)}else Number.isInteger(t)?(s=t,a=this.config.max_size??s):t!==void 0&&(s=t.shortest_edge,a=t.longest_edge);if(s!==void 0||a!==void 0){let o=s===void 0?1:Math.max(s/r,s/n),i=r*o,l=n*o,c=a===void 0?1:Math.min(a/i,a/l),u=Math.floor(Number((i*c).toFixed(2))),p=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([u,p]=ov([u,p],this.size_divisibility)),[u,p]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/n,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=av(l*n,this.config.ensure_multiple_of),o=av(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return ov([r,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){let[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:n=null,do_convert_grayscale:s=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[o,i]=e.size;if(n??this.do_convert_rgb?e=e.rgb():s&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let f,m;Number.isInteger(this.crop_size)?(f=this.crop_size,m=this.crop_size):(f=this.crop_size.width,m=this.crop_size.height),e=await e.center_crop(f,m)}let l=[e.height,e.width],c=Float32Array.from(e.data),u=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(e.channels).fill(f));let m=this.image_std;if(Array.isArray(this.image_std)||(m=new Array(e.channels).fill(m)),f.length!==e.channels||m.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${f.length}) and \`image_std\` (${m.length}) must match the number of channels in the image (${e.channels}).`);for(let y=0;y<c.length;y+=e.channels)for(let v=0;v<e.channels;++v)c[y+v]=(c[y+v]-f[v])/m[v]}if(r??this.do_pad){if(this.pad_size)[c,u]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let f=Math.ceil(u[1]/this.size_divisibility)*this.size_divisibility,m=Math.ceil(u[0]/this.size_divisibility)*this.size_divisibility;[c,u]=this.pad_image(c,u,{width:f,height:m})}}if(a??this.do_flip_channel_order){if(u[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let f=0;f<c.length;f+=3){let m=c[f];c[f]=c[f+2],c[f+2]=m}}let p=new q("float32",c,u).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:p}}async _call(e,...t){Array.isArray(e)||(e=[e]);let r=await Promise.all(e.map(s=>this.preprocess(s)));return{pixel_values:Fr(r.map(s=>s.pixel_values),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}static async from_pretrained(e,t={}){let r=await yr(e,_a,!0,t);return new this(r)}},gi={};cs(gi,{BeitFeatureExtractor:()=>wM,BitImageProcessor:()=>yM,CHMv2ImageProcessor:()=>bM,CLIPFeatureExtractor:()=>MM,CLIPImageProcessor:()=>hh,ChineseCLIPFeatureExtractor:()=>vM,ConvNextFeatureExtractor:()=>xM,ConvNextImageProcessor:()=>fh,DINOv3ViTImageProcessor:()=>kM,DPTFeatureExtractor:()=>AM,DPTImageProcessor:()=>gh,DeiTFeatureExtractor:()=>TM,DeiTImageProcessor:()=>mh,DetrFeatureExtractor:()=>EM,DetrImageProcessor:()=>_h,DonutFeatureExtractor:()=>CM,DonutImageProcessor:()=>Si,EfficientNetImageProcessor:()=>SM,GLPNFeatureExtractor:()=>PM,Glm46VImageProcessor:()=>IM,GroundingDinoImageProcessor:()=>RM,Idefics3ImageProcessor:()=>Lp,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,JinaCLIPImageProcessor:()=>LM,Lfm2VlImageProcessor:()=>FM,LlavaOnevisionImageProcessor:()=>NM,Mask2FormerImageProcessor:()=>BM,MaskFormerFeatureExtractor:()=>DM,MaskFormerImageProcessor:()=>Ii,MobileNetV1FeatureExtractor:()=>UM,MobileNetV1ImageProcessor:()=>yh,MobileNetV2FeatureExtractor:()=>zM,MobileNetV2ImageProcessor:()=>vh,MobileNetV3FeatureExtractor:()=>$M,MobileNetV3ImageProcessor:()=>bh,MobileNetV4FeatureExtractor:()=>VM,MobileNetV4ImageProcessor:()=>Mh,MobileViTFeatureExtractor:()=>GM,MobileViTImageProcessor:()=>xh,NougatImageProcessor:()=>jM,OwlViTFeatureExtractor:()=>qM,OwlViTImageProcessor:()=>Pi,Owlv2ImageProcessor:()=>WM,Phi3VImageProcessor:()=>HM,PixtralImageProcessor:()=>KM,PvtImageProcessor:()=>QM,Qwen2VLImageProcessor:()=>wh,RTDetrImageProcessor:()=>JM,Sam2ImageProcessor:()=>ii,Sam3ImageProcessor:()=>ii,SamImageProcessor:()=>ii,SapiensFeatureExtractor:()=>XM,SapiensImageProcessor:()=>Th,SegformerFeatureExtractor:()=>YM,SegformerImageProcessor:()=>Eh,SiglipImageProcessor:()=>ZM,SmolVLMImageProcessor:()=>Lp,Swin2SRImageProcessor:()=>ex,VLMImageProcessor:()=>OM,ViTFeatureExtractor:()=>tx,ViTImageProcessor:()=>kh,VitMatteImageProcessor:()=>rx,VitPoseImageProcessor:()=>nx,YolosFeatureExtractor:()=>sx,YolosImageProcessor:()=>Ch});wM=class extends ue{},yM=class extends ue{},vM=class extends ue{},bM=class extends ue{},hh=class extends ue{},MM=class extends hh{},fh=class extends ue{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let r=Math.floor(t/this.crop_pct),[n,s]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,s,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},xM=class extends fh{},mh=class extends ue{},TM=class extends mh{},_h=class extends ue{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=lt(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Ai(...e)}post_process_panoptic_segmentation(...e){return _M(...e)}post_process_instance_segmentation(...e){return gM(...e)}},EM=class extends _h{},kM=class extends ue{},Si=class extends ue{pad_image(e,t,r,n={}){let[s,a,o]=t,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));let c=i.map((u,p)=>-u/l[p]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...n})}},CM=class extends Si{},gh=class extends ue{},AM=class extends gh{},SM=class extends ue{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))}},wh=class extends ue{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size;return ph(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:r,original_sizes:n,reshaped_input_sizes:s}=await super._call(e,...t),a=r,{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=Fe(Array.from({length:o},()=>a),0));let c=a.dims[0]/o,u=a.dims[1],p=Math.floor(a.dims[2]/l),f=Math.floor(a.dims[3]/l),m=a.view(c,o,u,Math.floor(p/i),i,l,Math.floor(f/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*p*f,u*o*l*l),y=new q("int64",[c,p,f],[1,3]);return{pixel_values:m,image_grid_thw:y,original_sizes:n,reshaped_input_sizes:s}}},IM=class extends wh{get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return ph(e.height,e.width,r,this.min_pixels,this.max_pixels,n)}},PM=class extends ue{},RM=class extends ue{async _call(e){let t=await super._call(e),r=t.pixel_values.dims,n=xt([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},Lp=class extends ue{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,n]=e.dims.slice(-2),s=n/r;return n>=r?(n=Math.ceil(n/t)*t,r=Math.floor(n/s),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,n=Math.floor(r*s),n=Math.ceil(n/t)*t),{height:r,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let s=[],a=[],o=[],i=[],l=[];for(let x of n){let M=await Promise.all(x.map(C=>this.preprocess(C)));i.push(...M.map(C=>C.original_size)),l.push(...M.map(C=>C.reshaped_input_size)),M.forEach(C=>C.pixel_values.unsqueeze_(0));let{longest_edge:T}=this.max_image_size,A;if(t??this.do_image_splitting){let C=new Array(M.length),S=new Array(M.length);A=await Promise.all(M.map(async(O,E)=>{let K=this.get_resize_for_vision_encoder(O.pixel_values,T),$=await Nt(O.pixel_values,{size:[K.height,K.width]}),{frames:V,num_splits_h:Q,num_splits_w:G}=await this.split_image($,this.max_image_size);return C[E]=Q,S[E]=G,Fe(V,0)})),a.push(C),o.push(S)}else{let C=[T,T];A=await Promise.all(M.map(S=>Nt(S.pixel_values,{size:C}))),a.push(new Array(M.length).fill(0)),o.push(new Array(M.length).fill(0))}s.push(Fe(A,0))}let c=s.length,[u,p,f,m]=s[0].dims,y,v;if(c===1)y=s[0].unsqueeze_(0),v=lt([c,u,f,m],!0);else{let x=Math.max(...s.map(A=>A.dims.at(0)));v=lt([c,x,f,m],!0);let M=v.data,T=x*f*m;for(let A=0;A<c;++A){let C=s[A].dims[0];if(C<x){s[A]=Fe([s[A],lt([x-C,p,f,m],0)],0);let S=A*T+C*f*m,O=(A+1)*T;M.fill(!1,S,O)}}y=Fr(s,0)}return{pixel_values:y,pixel_attention_mask:v,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){let r=t,n=t,s=[],[a,o]=e.dims.slice(-2),i=0,l=0;if(a>r||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);let c=Math.ceil(a/i),u=Math.ceil(o/l);for(let m=0;m<i;++m)for(let y=0;y<l;++y){let v,x,M,T;m===i-1?(x=a-c,T=a):(x=m*c,T=(m+1)*c),y===l-1?(v=o-u,M=o):(v=y*u,M=(y+1)*u);let S=await Yp(e,[x,v],[T,M],[2,3]);s.push(S)}let p=r,f=n;(a!==p||o!==f)&&(e=await Nt(e,{size:[p,f]}))}return s.push(e),{frames:s,num_splits_h:i,num_splits_w:l}}},OM=class extends ue{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},LM=class extends ue{constructor(e){let{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,o=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},i=n==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:s,do_normalize:!0})}};FM=class extends ue{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r)}_is_image_too_large(e,t){let r=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,iv(e,r)),s=Math.max(this.encoder_patch_size,iv(t,r));return n*s>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let r=$B(this.min_tiles,this.max_tiles),[n,s]=zB(t/e,r,t,e,this.tile_size);return{grid_width:n,grid_height:s,target_width:this.tile_size*n,target_height:this.tile_size*s}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];let n=[],s=[],a=[],o=[],i=[],l=[];for(let u of r){let p=await Promise.all(u.map(f=>this.preprocess(f,{do_pad:!1})));for(let{pixel_values:f}of p){let[,m,y]=f.dims,v=f.unsqueeze_(0),x=this.encoder_patch_size*this.downsample_factor,M=x**2,[T,A]=ph(Math.max(x,m),Math.max(x,y),x,this.min_image_tokens*M,this.max_image_tokens*M).map($=>Math.max(x,$)),C,S=1,O=1,E=this._is_image_too_large(m,y),K=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(E&&K){let{grid_width:$,grid_height:V,target_width:Q,target_height:G}=this._get_grid_layout(m,y);S=V,O=$;let W=await Nt(v,{size:[G,Q]});C=[];for(let D=0;D<V;++D)for(let R=0;R<$;++R){let re=D*this.tile_size,ie=R*this.tile_size;C.push(W.slice(null,null,[re,re+this.tile_size],[ie,ie+this.tile_size]))}this.use_thumbnail&&$*V!==1&&C.push(await Nt(v,{size:[A,T]}))}else C=[await Nt(v,{size:[A,T]})];for(let $ of C){let[,,V,Q]=$.dims,G=VB($,this.encoder_patch_size),{padded:W,mask:D}=GB(G,this.max_num_patches);n.push(W),s.push(D),a.push([Math.floor(V/this.encoder_patch_size),Math.floor(Q/this.encoder_patch_size)])}o.push(S),i.push(O),l.push([A,T])}}let c={pixel_values:Fe(n,0),pixel_attention_mask:Fr(s,0),spatial_shapes:new q("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}},NM=class extends ue{},Ii=class extends ue{post_process_panoptic_segmentation(...e){return _M(...e)}post_process_instance_segmentation(...e){return gM(...e)}},DM=class extends Ii{},BM=class extends Ii{},yh=class extends ue{},UM=class extends yh{},vh=class extends ue{},zM=class extends vh{},bh=class extends ue{},$M=class extends bh{},Mh=class extends ue{},VM=class extends Mh{},xh=class extends ue{},GM=class extends xh{},jM=class extends Si{},Pi=class extends ue{post_process_object_detection(...e){return Ai(...e)}},qM=class extends Pi{},WM=class extends Pi{},Ct=336,jB=[2,3],{ceil:Gd,floor:Xn,sqrt:jd}=Math,HM=class extends ue{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){let{num_img_tokens:r}=this.config;return Xn((Xn(t/Ct)*Xn(e/Ct)+1)*r+1+(Xn(t/Ct)+1)*jd(r))}get_resize_output_image_size(e,t){let r=this._num_crops,[n,s]=e.size,a=n/s,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;let i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,n={}){let[s,a]=t,o=Ct*Gd(s/Ct),i=Ct*Gd(a/Ct),l=[1,1,1].map((c,u)=>(c-this.image_mean[u])/this.image_std[u]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??(t=this.config.num_crops),t<4||jd(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let r=e.length,n=await Promise.all(e.map(p=>this.preprocess(p))),s=n.map(p=>p.original_size),a=n.map(p=>p.reshaped_input_size),o=[];for(let{pixel_values:p}of n){p.unsqueeze_(0);let[f,m]=p.dims.slice(-2),y=await Nt(p,{size:[Ct,Ct],mode:"bicubic"});if(t>0){let v=[],x=jd(t),M=Xn(m/x),T=Xn(f/x);for(let C=0;C<x;++C)for(let S=0;S<x;++S){let O,E,K,$;C===x-1?(E=f-T,$=f):(E=C*T,$=(C+1)*T),S===x-1?(O=m-M,K=m):(O=S*M,K=(S+1)*M);let G=await Yp(p,[E,O],[$,K],jB);v.push(G)}let A=await Nt(Fe(v,0),{size:[Ct,Ct],mode:"bicubic"});o.push(Fe([y,A],0))}else o.push(y)}let i=Fr(o,0),l=a.map(p=>p.map(f=>Ct*Gd(f/Ct))),c=new q("int64",l.flat(),[r,2]),u=l.map(([p,f])=>this.calc_num_image_tokens_from_image_size(f,p));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:u}}},KM=class extends ue{get_resize_output_image_size(e,t){let{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");let[n,s]=e.size,a=Math.max(n,s)/r,o=n,i=s;a>1&&(o=Math.floor(n/a),i=Math.floor(s/a));let{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");let u=l*c,p=Math.floor((o-1)/u)+1,f=Math.floor((i-1)/u)+1;return[p*u,f*u]}},QM=class extends ue{},JM=class extends ue{post_process_object_detection(...e){return Ai(...e)}},ii=class extends ue{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=Ty(e);if(s.length===3)n||(s=[1,...s]),e=[e];else if(s.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[o,i]=t[a],[l,c]=r[a],u=[c/i,l/o];for(let p=0;p<e[a].length;++p)for(let f=0;f<e[a][p].length;++f)for(let m=0;m<e[a][p][f].length;++m)e[a][p][f][m]*=u[m%2]}return new q("float32",Float32Array.from(e.flat(1/0)),s)}add_input_labels(e,t){let r=Ty(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((n,s)=>n!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new q("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:n=null}={}){let s=await super._call(e);if(t&&(s.input_points=this.reshape_input_points(t,s.original_sizes,s.reshaped_input_sizes)),r){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(r,s.input_points)}return n&&(s.input_boxes=this.reshape_input_points(n,s.original_sizes,s.reshaped_input_sizes,!0)),s}async post_process_masks(e,t,r,{mask_threshold:n=0,binarize:s=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let i=[a.height,a.width];for(let l=0;l<t.length;++l){let c=t[l],u=r[l],p=await Nt(e[l],{mode:"bilinear",size:i});if(p=p.slice(null,null,[0,u[0]],[0,u[1]]),p=await Nt(p,{mode:"bilinear",size:c}),s){let f=p.data,m=new Uint8Array(f.length);for(let y=0;y<f.length;++y)f[y]>n&&(m[y]=1);p=new q("bool",m,p.dims)}o.push(p)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:s=32,crop_n_points_downscale_factor:a=1}={}){}},Th=class extends ue{post_process_semantic_segmentation(...e){return mM(...e)}},XM=class extends Th{},Eh=class extends ue{post_process_semantic_segmentation(...e){return mM(...e)}},YM=class extends Eh{},ZM=class extends ue{},ex=class extends ue{pad_image(e,t,r,n={}){let[s,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}},kh=class extends ue{},tx=class extends kh{},rx=class extends ue{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Fr(r.map((a,o)=>Fe([a.pixel_values,n[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},nx=class extends ue{post_process_pose_estimation(e,t,{threshold:r=null}={}){let n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let c=0;c<s;++c){let u=n[c],p=t[c],f=[];for(let m=0;m<p.length;++m){let y=p[m],v=[],x=[],M=[],T=y.at(-2)/i,A=y.at(-1)/o;for(let C=0;C<u.length;++C){let[S,O]=[0,0],E=0,K=-1/0,$=u[C];for(let Q=0;Q<$.length;++Q){let G=$[Q];for(let W=0;W<G.length;++W){let D=G[W];E+=D,K=Math.max(K,D),S+=(W+.5)*D,O+=Q*D}}if(r!=null&&K<r)continue;let V=[T*S/E,A*O/E];v.push(V),M.push(C),x.push(K)}f.push({bbox:y,scores:x,labels:M,keypoints:v})}l.push(f)}return l}},Ch=class extends ue{post_process_object_detection(...e){return Ai(...e)}},sx=class extends Ch{},mt=class{static async from_pretrained(e,t={}){let r=await yr(e,_a,!0,t),n=r.image_processor_type??r.feature_extractor_type,s=gi[n?.replace(/Fast$/,"")];return s||(n!==void 0&&ce.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Ci}.`),s=ue),new s(r)}},ax=(qo=class extends Se{constructor(e,t,r){super(e,t,r);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:s,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(s??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let t=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(let[n,s]of this.task_prompts_with_input)if(r.includes(n)){t.push(s.replaceAll("{input}",r).replaceAll(n,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){let n=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let s;switch(n){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(let[c,u,...p]of o)i.push(u?u.trim():i.at(-1)??""),l.push(p.map((f,m)=>(Number(f)+.5)/this.size_per_bin*r[m%2]));s={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:s}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,r),s=t?this.tokenizer(this.construct_prompts(t),r):{};return{...n,...s}}},w(qo,"tokenizer_class",Ae),w(qo,"image_processor_class",mt),qo),ox=(an=class extends Se{constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:s,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:u}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;let p=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
17
+
18
+ ${s}${p}${o}
19
+
20
+ `,this.image_token_id=i,this.boi_token=l,this.image_token=c;let f=c.repeat(this.image_seq_length);this.full_image_sequence=`
21
+
22
+ ${l}${f}${u}
23
+
24
+ `}async _call(e,t=null,r=null,n={}){typeof e=="string"&&(e=[e]);let s;r&&(s=await this.feature_extractor(r,n),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,n),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...s}}},w(an,"image_processor_class",mt),w(an,"feature_extractor_class",Bt),w(an,"tokenizer_class",Ae),w(an,"uses_processor_config",!0),w(an,"uses_chat_template_file",!0),an),Ri=(ea=class extends Se{async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let n,s;if(t&&(n=await this.image_processor(t),s=n.image_grid_thw),s){let o=this.image_processor.config.merge_size**2,i=0,l=this.constructor.image_token,c=s.tolist();e=e.map(u=>{for(;u.includes(l);){let p=Number(c[i++].reduce((f,m)=>f*m,1n));u=u.replace(l,"<|placeholder|>".repeat(Math.floor(p/o)))}return u.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...n}}},w(ea,"image_processor_class",mt),w(ea,"tokenizer_class",Ae),w(ea,"image_token","<|image_pad|>"),ea),ix=(Qd=class extends Ri{},w(Qd,"image_token","<|image|>"),Qd),lx=(ta=class extends Se{_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:n}=this.feature_extractor.config,s=Math.floor(r/n),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*s}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){let{input_features:a}=await this.feature_extractor(t);n.input_features=a;let o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);n.input_features_mask=new q("bool",i,[1,o]);let l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},w(ta,"tokenizer_class",Ae),w(ta,"feature_extractor_class",Bt),w(ta,"uses_processor_config",!0),ta);cx=(Wo=class extends Se{async _call(e,t,r={}){let n=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:n=.25,target_sizes:s=null}={}){let{logits:a,pred_boxes:o}=e,i=a.dims[0];if(s!==null&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let l=a.dims.at(1),c=a.sigmoid(),u=c.max(-1).tolist(),p=o.tolist().map(m=>m.map(y=>fM(y))),f=[];for(let m=0;m<i;++m){let y=s!==null?s[m]:null;y!==null&&(p[m]=p[m].map(A=>A.map((C,S)=>C*y[(S+1)%2])));let v=u[m],x=[],M=[],T=[];for(let A=0;A<l;++A){let C=v[A];if(C<=r)continue;let S=p[m][A],O=c[m][A];x.push(C),T.push(S);let E=qB(O.gt(n),t[m]);M.push(E)}f.push({scores:x,boxes:T,labels:this.batch_decode(M)})}return f}},w(Wo,"tokenizer_class",Ae),w(Wo,"image_processor_class",mt),Wo);Fp=(ra=class extends Se{constructor(){super(...arguments);w(this,"fake_image_token","<fake_token_around_image>");w(this,"image_token","<image>");w(this,"global_img_token","<global-img>")}async _call(t,r=null,n={}){n.return_row_col_info??(n.return_row_col_info=!0);let s;r&&(s=await this.image_processor(r,n)),Array.isArray(t)||(t=[t]);let a=s.rows??[new Array(t.length).fill(0)],o=s.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let p=0;p<t.length;++p){let f=t[p],m=a[p],y=o[p];l.push(wL(f,this.image_token));let v=m.map((T,A)=>KB(T,y[A],i,this.fake_image_token,this.image_token,this.global_img_token)),x=f.split(this.image_token);if(x.length===0)throw new Error("The image token should be present in the text.");let M=x[0];for(let T=0;T<v.length;++T)M+=v[T]+x[T+1];c.push(M)}return{...this.tokenizer(c),...s}}},w(ra,"image_processor_class",mt),w(ra,"tokenizer_class",Ae),w(ra,"uses_processor_config",!0),ra),ux=(na=class extends Se{constructor(e,t,r){super(e,t,r),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(v=>v.images).flatMap(v=>v.images).map(v=>Mt.read(v)));let n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>n.encode(v,{add_special_tokens:!1}),o=s.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);let[l,c,u]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),p=a(o[0]),f=new Array(p.length).fill(!1);for(let v=1;v<o.length;++v){let x=new Array(this.num_image_tokens).fill(l),M=a(o[v]);p=jt(p,[c],x,[u],M);let T=new Array(this.num_image_tokens).fill(!0);f=jt(f,[!1],T,[!1],new Array(M.length).fill(!1))}let m=[1,p.length],y={input_ids:new q("int64",p,m),attention_mask:new q("int64",new Array(p.length).fill(1),m),images_seq_mask:new q("bool",f,m),images_emb_mask:new q("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){let v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...y,...v}}return y}},w(na,"image_processor_class",mt),w(na,"tokenizer_class",Ae),w(na,"uses_processor_config",!0),na),dx=(Ho=class extends Se{async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,r):{},s=t?await this.image_processor(t,r):{};return{...n,...s}}},w(Ho,"tokenizer_class",Ae),w(Ho,"image_processor_class",mt),Ho),px=(Ko=class extends Se{async _call(e,t=null,r={}){let{image_rows:n,image_cols:s,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){let i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:u=16,use_thumbnail:p=!0}=this.image_processor.config,f=T=>Math.ceil(Math.floor(T/u)/c),m=f(l)**2,y=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",x=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let M=0;t=t.map(T=>{let A=T.split(i);return A[0]+A.slice(1).map(C=>{let S=M++,[O,E]=a[S],K=n[S],$=s[S],V=f(O)*f(E),Q=y;if(K>1||$>1){let G=i.repeat(m);for(let W=0;W<K;++W)for(let D=0;D<$;++D)Q+=`<|img_row_${W+1}_col_${D+1}|>`+G;p&&(Q+=x+i.repeat(V))}else Q+=i.repeat(V);return Q+v+C}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},w(Ko,"tokenizer_class",Ae),w(Ko,"image_processor_class",mt),Ko),hx=(sa=class extends Se{async _call(e,t=null,r={}){let n=await this.image_processor(e,r);if(t){let[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,u=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let p=0;p<t.length;++p)t[p]=t[p].replace(i,i.repeat(u))}let s=t?this.tokenizer(t,r):{};return{...n,...s}}},w(sa,"tokenizer_class",Ae),w(sa,"image_processor_class",mt),w(sa,"uses_processor_config",!0),sa),lv={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},fx=(Qo=class extends Se{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(!lv.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);let[r,n]=lv[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let p=0;p<a;++p){let f=c[p],m=[],y=[];for(let x=1;x<o;++x){let[M,T]=Ge(rt(f[x]));if(y.push(M),T==n)break;m.push(T)}let v=y.length>0?y.reduce((x,M)=>x*M,1):0;l.push(m),i.push(v)}return[s(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){let[n,s]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),c=[],u=[];for(let p=0;p<n.length;++p){let[f,m]=Ge([s[p],o[p],l[p]]);c.push([n[p],a[p],i[p]][m]),u.push(f)}return{generated_text:c,scores:u,char_preds:n,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),r=await Ae.from_pretrained("Xenova/gpt2"),n=await Ae.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:n},t}async _call(e,t=null){let r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},w(Qo,"tokenizer_class",Ae),w(Qo,"image_processor_class",mt),Qo),mx=(Jo=class extends Se{async _call(e){return await this.feature_extractor(e)}},w(Jo,"tokenizer_class",Ae),w(Jo,"feature_extractor_class",Bt),Jo),_x=(Xo=class extends Se{},w(Xo,"tokenizer_class",Ae),w(Xo,"image_processor_class",mt),Xo),Yn="<image>";gx=(aa=class extends Se{async _call(e,t=null,r={}){t||(ce.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]);let n=this.tokenizer.bos_token,s=this.image_processor.config.image_seq_length,a;t.some(l=>l.includes(Yn))?a=t.map(l=>{let c=l.replaceAll(Yn,Yn.repeat(s)),u=c.lastIndexOf(Yn),p=u===-1?0:u+Yn.length;return c.slice(0,p)+n+c.slice(p)+`
25
+ `}):(ce.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(l=>QB(l,n,s,Yn,e.length)));let o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},w(aa,"tokenizer_class",Ae),w(aa,"image_processor_class",mt),w(aa,"uses_processor_config",!1),aa),cv="<|image|>",JB=/<\|image_\d+\|>/g,wx=(Yo=class extends Se{async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:s});let{num_img_tokens:i}=o,l=e.map((u,p)=>u.split(JB).join(cv.repeat(i[p])));a=this.tokenizer(l,{padding:r,truncation:n});let c=this.tokenizer._tokenizer.token_to_id(cv);a.input_ids.map_(u=>u==c?-u:u)}else a=this.tokenizer(e);return{...a,...o}}},w(Yo,"image_processor_class",mt),w(Yo,"tokenizer_class",Ae),Yo),yx=(oa=class extends Se{async _call(e,t=null,r={}){let n=await this.image_processor(e,r);if(t){let[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:u,spatial_merge_size:p}=this.config,f=u*p,m=Math.floor(a/f),y=Math.floor(o/f);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v<t.length;++v){let x=i.repeat(y),M=x+l,T=x+c,A=M.repeat(m-1)+T;t[v]=t[v].replace(i,A)}}let s=t?this.tokenizer(t,r):{};return{...n,...s}}},w(oa,"tokenizer_class",Ae),w(oa,"image_processor_class",mt),w(oa,"uses_processor_config",!0),oa),vx=(Jd=class extends Se{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}},w(Jd,"feature_extractor_class",dh),Jd),Ah=class extends Ri{},bx=class extends Ah{},Sh=(Xd=class extends Se{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)}},w(Xd,"image_processor_class",mt),Xd),Ih=class extends Sh{},Mx=class extends Ih{},xx=(Zo=class extends Se{async _call(e){return await this.feature_extractor(e)}},w(Zo,"tokenizer_class",Ae),w(Zo,"feature_extractor_class",Bt),Zo),Tx=(ia=class extends Se{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){let a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);n.audio_token_len=[l],n.audio_values=o;let c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},w(ia,"tokenizer_class",Ae),w(ia,"feature_extractor_class",Bt),w(ia,"uses_processor_config",!0),ia),$o="[AUDIO]",XB="[BEGIN_AUDIO]",YB=375;Ex=(la=class extends Se{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){if(!e.includes($o))throw new Error(`The input text does not contain the audio token ${$o}.`);Array.isArray(t)||(t=[t]);let a=e.split($o),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}).`);let i=this.feature_extractor.config.n_samples,l=t.map(m=>ZB(m,i)),c=l.map(m=>m.length),u=l.flat(),p=(await Promise.all(u.map(m=>this.feature_extractor(m,r)))).map(m=>m.input_features);n.audio_values=p.length>1?Fe(p,0):p[0];let f=a[0];for(let m=0;m<c.length;++m){f+=XB;for(let y=0;y<c[m];++y)f+=$o.repeat(YB);f+=a[m+1]}e=f}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},w(la,"tokenizer_class",Ae),w(la,"feature_extractor_class",Bt),w(la,"uses_processor_config",!1),la),uv=32,qd=6,Vo=8,eU=10,tU=32,kx=(ca=class extends Se{get num_mel_frames_first_audio_chunk(){return(qd+1)*Vo}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return Vo*e+t}get num_right_pad_tokens(){return qd+1+eU}get audio_length_per_tok(){return Vo}get raw_audio_length_per_tok(){return Vo*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(bt(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){let n=uv*this.raw_audio_length_per_tok,s=new Float32Array(n+e.length);s.set(e,n);let a=await this.feature_extractor(s,{center:!0}),i=1+(uv+qd),l=new BigInt64Array(i).fill(BigInt(tU));return l[0]=1n,{input_ids:new q("int64",l,[1,i]),...a}}else{let n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,s=new Float32Array(e.length+n);return s.set(e),await this.feature_extractor(s,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},w(ca,"tokenizer_class",Ae),w(ca,"feature_extractor_class",Bt),w(ca,"uses_processor_config",!1),ca),Cx=(ei=class extends Se{async _call(e){return await this.feature_extractor(e)}},w(ei,"tokenizer_class",Ae),w(ei,"feature_extractor_class",Bt),ei),Ax=(ti=class extends Se{async _call(e){return await this.feature_extractor(e)}},w(ti,"tokenizer_class",Ae),w(ti,"feature_extractor_class",Bt),ti),Sx=(ri=class extends Se{async _call(e){return await this.feature_extractor(e)}},w(ri,"tokenizer_class",Ae),w(ri,"feature_extractor_class",Bt),ri),Ix=class{static async from_pretrained(e,t={}){let r=await yr(e,_a,!0,t),{image_processor_type:n,feature_extractor_type:s,processor_class:a}=r;if(a&&Rp[a])return Rp[a].from_pretrained(e,t);if(!n&&!s)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let o={};if(n){let l=gi[n.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){let l=gi[s];if(l)o.image_processor=new l(r);else{let c=lh[s];if(!c)throw new Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new c(r)}}let i={};return new Se(i,o,null)}};wi=class Np{constructor(t){w(this,"model_type",null);w(this,"is_encoder_decoder",!1);w(this,"max_position_embeddings");w(this,"transformers.js_config");Object.assign(this,t),this.normalized_config=Zn(this)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){n&&!(n instanceof Np)&&(n=new Np(n));let i=n??await rU(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},ls=class{static async from_pretrained(...e){return wi.from_pretrained(...e)}};Qe=class{},oe=class extends Qe{constructor({logits:e,...t}){super(),this.logits=e;let r=Object.values(t);r.length>0&&(this.attentions=r)}},je=class extends Qe{constructor({logits:e}){super(),this.logits=e}},Je=class extends Qe{constructor({logits:e}){super(),this.logits=e}},_t=class extends Qe{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},hn=class extends Qe{constructor({logits:e}){super(),this.logits=e}},cU=class extends Qe{constructor({alphas:e}){super(),this.alphas=e}},Jt=class extends Dt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Li=class extends Dt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},yi=class extends Dt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(let n of this.processors)r=n(e,r);return r}[Symbol.iterator](){return this.processors.values()}},Lx=class extends Jt{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){let n=t[r].data;n.fill(-1/0),n[this.bos_token_id]=0}return t}},Fx=class extends Jt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){let n=t[r].data;n.fill(-1/0);for(let s of this.eos_token_id)n[s]=0}return t}},Ph=class extends Jt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){let n=t[r].data;for(let s of this.begin_suppress_tokens)n[s]=-1/0}return t}},Nx=class extends Jt{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data;if(n[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}let s=e[r].slice(this.begin_index),a=s.length>=1&&s[s.length-1]>=this.timestamp_begin,o=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a&&(o?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){let u=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(u+1).fill(-1/0)}let i=Dv(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((u,p)=>u+p)),c=Ge(i.subarray(0,this.timestamp_begin))[0];l>c&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},Dx=class extends Jt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,r=[];for(let s=0;s<t+1-this.no_repeat_ngram_size;++s){let a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[s+o]);r.push(a.map(Number))}let n=new Map;for(let s of r){let a=s.slice(0,s.length-1),o=JSON.stringify(a),i=n.get(o)??[];i.push(s[s.length-1]),n.set(o,i)}return n}getGeneratedNgrams(e,t){let r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data,s=this.calcBannedNgramTokens(e[r]);for(let a of s)n[a]=-1/0}return t}},Bx=class extends Jt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data;for(let s of new Set(e[r])){let a=Number(s);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return t}},Ux=class extends Jt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){let n=t[r].data;for(let s of this.eos_token_id)n[s]=-1/0}return t}},zx=class extends Jt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){let s=t[r].data;for(let a of this.eos_token_id)s[a]=-1/0}return t}},$x=class extends Jt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){let n=t[r].data,s=e[r];for(let a of this.bad_words_ids){if(s.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=s.at(-i)){o=!1;break}o&&(n[a.at(-1)]=-1/0)}}return t}},Vx=class extends Jt{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.`);let r=e.length,n=t.slice([0,r],null),s=t.slice([r,t.dims[0]],null);for(let a=0;a<s.data.length;++a)s.data[a]+=(n.data[a]-s.data[a])*this.guidance_scale;return s}},Gx=class extends Li{constructor(e){if(super(),typeof e!="number"||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){let r=t.data;for(let n=0;n<r.length;++n)r[n]/=this.temperature;return t}},uU=class extends Li{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=r}},dU=class extends Li{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,r),this.filter_value=t}},jx=class{constructor(e){w(this,"max_length",20);w(this,"max_new_tokens",null);w(this,"min_length",0);w(this,"min_new_tokens",null);w(this,"early_stopping",!1);w(this,"max_time",null);w(this,"do_sample",!1);w(this,"num_beams",1);w(this,"num_beam_groups",1);w(this,"penalty_alpha",null);w(this,"use_cache",!0);w(this,"temperature",1);w(this,"top_k",50);w(this,"top_p",1);w(this,"typical_p",1);w(this,"epsilon_cutoff",0);w(this,"eta_cutoff",0);w(this,"diversity_penalty",0);w(this,"repetition_penalty",1);w(this,"encoder_repetition_penalty",1);w(this,"length_penalty",1);w(this,"no_repeat_ngram_size",0);w(this,"bad_words_ids",null);w(this,"force_words_ids",null);w(this,"renormalize_logits",!1);w(this,"constraints",null);w(this,"forced_bos_token_id",null);w(this,"forced_eos_token_id",null);w(this,"remove_invalid_values",!1);w(this,"exponential_decay_length_penalty",null);w(this,"suppress_tokens",null);w(this,"streamer",null);w(this,"begin_suppress_tokens",null);w(this,"forced_decoder_ids",null);w(this,"guidance_scale",null);w(this,"num_return_sequences",1);w(this,"output_attentions",!1);w(this,"output_hidden_states",!1);w(this,"output_scores",!1);w(this,"return_dict_in_generate",!1);w(this,"pad_token_id",null);w(this,"bos_token_id",null);w(this,"eos_token_id",null);w(this,"encoder_no_repeat_ngram_size",0);w(this,"decoder_start_token_id",null);w(this,"generation_kwargs",{});Object.assign(this,ot(e,Object.getOwnPropertyNames(this)))}},hs=class extends Dt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},Rh=class qx extends Dt{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof qx?t=t.criteria:t instanceof hs&&(t=[t]),this.criteria.push(...t)}_call(t,r){let n=new Array(t.length).fill(!1);for(let s of this.criteria){let a=s(t,r);for(let o=0;o<n.length;++o)n[o]||(n[o]=a[o])}return n}[Symbol.iterator](){return this.criteria.values()}},Wx=class extends hs{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)}},Hx=class extends hs{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{let n=r.at(-1);return this.eos_token_id.some(s=>n==s)})}},pU=class extends hs{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}},Fi=class extends Dt{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),n=e.data;if(t===-1)n=n.slice(-r);else{let s=t*r;n=n.slice(s,s+r)}return n}randomSelect(e){return kD(e)}static getSampler(e){if(e.do_sample)return new fU(e);if(e.num_beams>1)return new mU(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 hU(e)}},hU=class extends Fi{async sample(e){let t=Ge(e.data)[1];return[[BigInt(t),0]]}},fU=class extends Fi{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,n]=await pn(e,t),s=rt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},mU=class extends Fi{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,n]=await pn(e,t),s=rt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},_U=class{constructor(e){if(e)for(let t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let r=e[t];if(!(r instanceof q))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){let e=this;for(let 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.")}async dispose(){let e=[];for(let t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},Oh=_U,es=null;J={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,MultimodalLanguageModelOnly:16,VoxtralRealtime:17},ts={[J.DecoderOnly]:{can_generate:!0,forward:_r,prepare_inputs:ha,sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.DecoderOnlyWithoutHead]:{can_generate:!1,forward:_r,prepare_inputs:ha,sessions:(e,t)=>({model:t.model_file_name??"model"})},[J.Seq2Seq]:{can_generate:!0,forward:Go,prepare_inputs:vi,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.Vision2Seq]:{can_generate:!0,forward:Go,prepare_inputs:vi,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.Musicgen]:{can_generate:!0,forward:Go,sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.EncoderDecoder]:{can_generate:!1,forward:Go,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[J.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[J.ImageTextToText]:{can_generate:!0,forward:dv,prepare_inputs:Ys,sessions:e=>{let t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};return e.is_encoder_decoder&&(t.model="encoder_model"),t},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.AudioTextToText]:{can_generate:!0,forward:vU,prepare_inputs:Ys,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ys,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"}),optional_configs:{generation_config:"generation_config.json"}},[J.Phi3V]:{can_generate:!0,prepare_inputs:Ys,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.MultiModality]:{can_generate:!0,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.AutoEncoder]:{can_generate:!1,forward:yU,sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[J.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[J.Chatterbox]:{can_generate:!0,forward:Lr,sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[J.MultimodalLanguageModelOnly]:{can_generate:!0,forward:dv,prepare_inputs:Ys,sessions:()=>({embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[J.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ha,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{can_generate:!1,forward:Lr,sessions:(e,t)=>({model:t.model_file_name??"model"})}};mr=new Map,Lh=new Map,os=new Map,I=class extends Dt{constructor(t,r,n){super();w(this,"main_input_name","input_ids");w(this,"forward_params",["input_ids","attention_mask"]);w(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=n;let s=os.get(this.constructor),a=mr.get(s),o=ts[a]??ts.default;this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let t=[];for(let r of Object.values(this.sessions))t.push(r.release?.());return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:p=null,session_options:f={}}={}){let m={progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:p,session_options:f},y=os.get(this),v=mr.get(y);n=m.config=await ls.from_pretrained(t,m);let x=ts[v]??ts.default;if(v===void 0){let C=y??n?.model_type;C!=="custom"&&ce.warn(`Model type for '${C}' not found, assuming encoder-only architecture. Please report this at ${Ci}.`)}let M=x.sessions(n,m),T=[iU(t,M,m,x.cache_sessions)];x.optional_configs&&T.push(MU(t,x.optional_configs,m));let A=await Promise.all(T);return new this(n,...A)}async _call(t){return await this.forward(t)}async forward(t){return await this._forward(this,t)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(t,r,n=null){let s=new yi;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&s.push(new Bx(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&s.push(new Dx(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&s.push(new $x(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&s.push(new Ux(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&s.push(new zx(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&s.push(new Lx(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&s.push(new Fx(t.max_length,t.forced_eos_token_id)),t.begin_suppress_tokens!==null){let a=r>1||t.forced_bos_token_id===null?r:r+1;s.push(new Ph(t.begin_suppress_tokens,a))}return t.guidance_scale!==null&&t.guidance_scale>1&&s.push(new Vx(t.guidance_scale)),t.temperature===0&&t.do_sample&&(ce.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),t.do_sample=!1),t.do_sample&&t.temperature!==null&&t.temperature!==1&&s.push(new Gx(t.temperature)),n!==null&&s.extend(n),s}_prepare_generation_config(t,r,n=jx){let s={...this.config};for(let o of["decoder","generator","text_config"])o in s&&Object.assign(s,s[o]);let a=new n(s);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,ot(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){let n=new Rh;return t.max_length!==null&&n.push(new Wx(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&n.push(new Hx(t.eos_token_id)),r&&n.extend(r),n}_validate_model_class(){if(!this.can_generate){let t=[es.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,es.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,es.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,es.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=os.get(this.constructor),n=new Set,s=this.config.model_type;for(let o of t){let i=o?.get(s);i&&n.add(i)}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(a+=` Please use the following class instead: ${[...n].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:n,is_encoder_decoder:s}){return n.past_key_values=this.getPastKeyValues(r,n.past_key_values),n.input_ids=new q("int64",t.flat(),[t.length,1]),s?"decoder_attention_mask"in n:n.attention_mask=Fe([n.attention_mask,xt([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:n}){let s=ot(n,this.forward_params),a=this.main_input_name;if(a in s){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[a]=t;return{inputs_tensor:s[a],model_inputs:s,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:n,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:o,pixel_values:i,attention_mask:l,...c}=r,u=await this._prepare_inputs_embeds(r);r={...c,...ot(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await Lr(this,r);if(s.guidance_scale!==null&&s.guidance_scale>1)a=Fe([a,_i(a,0)],0),"attention_mask"in r&&(r.attention_mask=Fe([r.attention_mask,nh(r.attention_mask)],0));else if(r.decoder_input_ids){let o=Dp(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=Fe(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:n,decoder_start_token_id:s,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=n;if(!(i instanceof q)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(s??(s=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==t)throw new Error(`\`decoder_start_token_id\` expcted to have length ${t} but got ${s.length}`);i=s}else i=Array.from({length:t},()=>[s]);i=Dp(i)}return n.decoder_attention_mask=th(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:s=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:t,model_kwargs:o}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let p;u?{input_ids:p,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):p=l[c];let f=p.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=f+r.max_new_tokens);let m=this._get_logits_processor(r,f,n),y=this._get_stopping_criteria(r,s),v=l[c].dims.at(0),x=Fi.getSampler(r),M=new Array(v).fill(0),T=p.tolist();a&&a.put(T);let A,C={},S={};for(;;){if(l=this.prepare_inputs_for_generation(T,l,r),A=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let G=this.getAttentions(A);for(let W in G)W in C||(C[W]=[]),C[W].push(G[W])}else this._return_dict_in_generate_keys&&Object.assign(S,ot(A,this._return_dict_in_generate_keys));let K=A.logits.slice(null,-1,null).to("float32"),$=m(T,K),V=[];for(let G=0;G<$.dims.at(0);++G){let W=$[G],D=await x(W);for(let[R,re]of D){let ie=BigInt(R);M[G]+=re,T[G].push(ie),V.push([ie]);break}}if(a&&a.put(V),y(T).every(G=>G))break;l=this._update_model_kwargs_for_generation({generated_input_ids:V,outputs:A,model_inputs:l,is_encoder_decoder:u})}a&&a.end();let O=this.getPastKeyValues(A,l.past_key_values,!0),E=new q("int64",T.flat(),[T.length,T[0].length]);if(r.return_dict_in_generate)return{sequences:E,past_key_values:O,...C,...S};for(let K of Object.values(A))K.location==="gpu-buffer"&&K.dispose();return E}getPastKeyValues(t,r,n=!1){let s=Object.create(null);for(let a in t)if(a.startsWith("present")){let o=a.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=a.includes("encoder");if(i&&r?s[o]=r[o]:s[o]=t[a],r&&(!i||n)){let l=r[o];l.location==="gpu-buffer"&&l.dispose()}}return new Oh(s)}getAttentions(t){let r={};for(let n of["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in t)s.startsWith(n)&&(n in r||(r[n]=[]),r[n].push(t[s]));return r}addPastKeyValues(t,r){if(r)Object.assign(t,r);else{let n=this.sessions.decoder_model_merged??this.sessions.model,s=(t[this.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=n?.config?.kv_cache_dtype??"float32",o=a==="float16"?is.float16:is.float32,i=Oi(this.config,{batch_size:s});for(let l in i){let c=i[l].reduce((u,p)=>u*p,1);t[l]=new q(a,new o(c),i[l])}}}async _encode_input(t,r,n){if(!Object.hasOwn(this.sessions,t))throw new Error(`Model does not have a ${t} session.`);let s=this.sessions[t];return(await be(s,ot(r,s.inputNames)))[n]}async encode_image(t){return this._encode_input("vision_encoder",t,"image_features")}async encode_text(t){return this._encode_input("embed_tokens",t,"inputs_embeds")}async encode_audio(t){return this._encode_input("audio_encoder",t,"audio_features")}};Nh={};cs(Nh,{ASTForAudioClassification:()=>u0,ASTModel:()=>c0,ASTPreTrainedModel:()=>Ui,AfmoeForCausalLM:()=>o0,AfmoeModel:()=>a0,AfmoePreTrainedModel:()=>Di,AlbertForMaskedLM:()=>r0,AlbertForQuestionAnswering:()=>t0,AlbertForSequenceClassification:()=>e0,AlbertModel:()=>Zx,AlbertPreTrainedModel:()=>fs,ApertusForCausalLM:()=>s0,ApertusModel:()=>n0,ApertusPreTrainedModel:()=>Ni,ArceeForCausalLM:()=>l0,ArceeModel:()=>i0,ArceePreTrainedModel:()=>Bi,BartForConditionalGeneration:()=>p0,BartForSequenceClassification:()=>h0,BartModel:()=>d0,BartPretrainedModel:()=>Ea,BeitForImageClassification:()=>m0,BeitModel:()=>f0,BeitPreTrainedModel:()=>zi,BertForMaskedLM:()=>g0,BertForQuestionAnswering:()=>v0,BertForSequenceClassification:()=>w0,BertForTokenClassification:()=>y0,BertModel:()=>_0,BertPreTrainedModel:()=>fn,BlenderbotForConditionalGeneration:()=>M0,BlenderbotModel:()=>b0,BlenderbotPreTrainedModel:()=>$i,BlenderbotSmallForConditionalGeneration:()=>T0,BlenderbotSmallModel:()=>x0,BlenderbotSmallPreTrainedModel:()=>Vi,BloomForCausalLM:()=>k0,BloomModel:()=>E0,BloomPreTrainedModel:()=>Gi,CHMv2ForDepthEstimation:()=>O0,CHMv2PreTrainedModel:()=>zh,CLIPModel:()=>F0,CLIPPreTrainedModel:()=>Nr,CLIPSegForImageSegmentation:()=>z0,CLIPSegModel:()=>U0,CLIPSegPreTrainedModel:()=>ji,CLIPTextModel:()=>N0,CLIPTextModelWithProjection:()=>Gh,CLIPVisionModel:()=>D0,CLIPVisionModelWithProjection:()=>B0,CamembertForMaskedLM:()=>A0,CamembertForQuestionAnswering:()=>P0,CamembertForSequenceClassification:()=>S0,CamembertForTokenClassification:()=>I0,CamembertModel:()=>C0,CamembertPreTrainedModel:()=>mn,ChatterboxModel:()=>Bh,ChatterboxPreTrainedModel:()=>Dh,ChineseCLIPModel:()=>R0,ChineseCLIPPreTrainedModel:()=>Uh,ClapAudioModelWithProjection:()=>Vh,ClapModel:()=>L0,ClapPreTrainedModel:()=>ka,ClapTextModelWithProjection:()=>$h,CodeGenForCausalLM:()=>V0,CodeGenModel:()=>$0,CodeGenPreTrainedModel:()=>qi,Cohere2ForCausalLM:()=>W0,Cohere2Model:()=>q0,Cohere2PreTrainedModel:()=>Hi,CohereForCausalLM:()=>j0,CohereModel:()=>G0,CoherePreTrainedModel:()=>Wi,ConvBertForMaskedLM:()=>K0,ConvBertForQuestionAnswering:()=>X0,ConvBertForSequenceClassification:()=>Q0,ConvBertForTokenClassification:()=>J0,ConvBertModel:()=>H0,ConvBertPreTrainedModel:()=>_n,ConvNextForImageClassification:()=>Z0,ConvNextModel:()=>Y0,ConvNextPreTrainedModel:()=>Ki,ConvNextV2ForImageClassification:()=>tT,ConvNextV2Model:()=>eT,ConvNextV2PreTrainedModel:()=>Qi,DFineForObjectDetection:()=>aT,DFineModel:()=>sT,DFinePreTrainedModel:()=>Xi,DINOv3ConvNextModel:()=>PT,DINOv3ConvNextPreTrainedModel:()=>Yh,DINOv3ViTModel:()=>RT,DINOv3ViTPreTrainedModel:()=>Zh,DPTForDepthEstimation:()=>zT,DPTModel:()=>UT,DPTPreTrainedModel:()=>nl,DacDecoderModel:()=>Hh,DacDecoderOutput:()=>qh,DacEncoderModel:()=>Wh,DacEncoderOutput:()=>jh,DacModel:()=>oT,DacPreTrainedModel:()=>Ca,DebertaForMaskedLM:()=>lT,DebertaForQuestionAnswering:()=>dT,DebertaForSequenceClassification:()=>cT,DebertaForTokenClassification:()=>uT,DebertaModel:()=>iT,DebertaPreTrainedModel:()=>gn,DebertaV2ForMaskedLM:()=>mT,DebertaV2ForQuestionAnswering:()=>wT,DebertaV2ForSequenceClassification:()=>_T,DebertaV2ForTokenClassification:()=>gT,DebertaV2Model:()=>fT,DebertaV2PreTrainedModel:()=>wn,DecisionTransformerModel:()=>yT,DecisionTransformerPreTrainedModel:()=>Kh,DeepseekV3ForCausalLM:()=>hT,DeepseekV3Model:()=>pT,DeepseekV3PreTrainedModel:()=>Yi,DeiTForImageClassification:()=>bT,DeiTModel:()=>vT,DeiTPreTrainedModel:()=>Zi,DepthAnythingForDepthEstimation:()=>MT,DepthAnythingPreTrainedModel:()=>Qh,DepthProForDepthEstimation:()=>xT,DepthProPreTrainedModel:()=>Jh,DetrForObjectDetection:()=>ET,DetrForSegmentation:()=>kT,DetrModel:()=>TT,DetrObjectDetectionOutput:()=>el,DetrPreTrainedModel:()=>Aa,DetrSegmentationOutput:()=>Xh,Dinov2ForImageClassification:()=>AT,Dinov2Model:()=>CT,Dinov2PreTrainedModel:()=>tl,Dinov2WithRegistersForImageClassification:()=>IT,Dinov2WithRegistersModel:()=>ST,Dinov2WithRegistersPreTrainedModel:()=>rl,DistilBertForMaskedLM:()=>DT,DistilBertForQuestionAnswering:()=>NT,DistilBertForSequenceClassification:()=>LT,DistilBertForTokenClassification:()=>FT,DistilBertModel:()=>OT,DistilBertPreTrainedModel:()=>yn,DonutSwinModel:()=>BT,DonutSwinPreTrainedModel:()=>ef,EdgeTamModel:()=>WC,EfficientNetForImageClassification:()=>VT,EfficientNetModel:()=>$T,EfficientNetPreTrainedModel:()=>sl,ElectraForMaskedLM:()=>jT,ElectraForQuestionAnswering:()=>HT,ElectraForSequenceClassification:()=>qT,ElectraForTokenClassification:()=>WT,ElectraModel:()=>GT,ElectraPreTrainedModel:()=>vn,Ernie4_5ForCausalLM:()=>QT,Ernie4_5Model:()=>KT,Ernie4_5PretrainedModel:()=>al,EsmForMaskedLM:()=>XT,EsmForSequenceClassification:()=>YT,EsmForTokenClassification:()=>ZT,EsmModel:()=>JT,EsmPreTrainedModel:()=>_s,EuroBertForMaskedLM:()=>tE,EuroBertForSequenceClassification:()=>rE,EuroBertForTokenClassification:()=>nE,EuroBertModel:()=>eE,EuroBertPreTrainedModel:()=>gs,ExaoneForCausalLM:()=>aE,ExaoneModel:()=>sE,ExaonePreTrainedModel:()=>ol,FalconForCausalLM:()=>iE,FalconH1ForCausalLM:()=>cE,FalconH1Model:()=>lE,FalconH1PreTrainedModel:()=>ll,FalconModel:()=>oE,FalconPreTrainedModel:()=>il,FastViTForImageClassification:()=>dE,FastViTModel:()=>uE,FastViTPreTrainedModel:()=>cl,Florence2ForConditionalGeneration:()=>pE,Florence2PreTrainedModel:()=>tf,GLPNForDepthEstimation:()=>EE,GLPNModel:()=>TE,GLPNPreTrainedModel:()=>vl,GPT2LMHeadModel:()=>FE,GPT2Model:()=>LE,GPT2PreTrainedModel:()=>El,GPTBigCodeForCausalLM:()=>CE,GPTBigCodeModel:()=>kE,GPTBigCodePreTrainedModel:()=>bl,GPTJForCausalLM:()=>DE,GPTJModel:()=>NE,GPTJPreTrainedModel:()=>kl,GPTNeoForCausalLM:()=>SE,GPTNeoModel:()=>AE,GPTNeoPreTrainedModel:()=>Ml,GPTNeoXForCausalLM:()=>PE,GPTNeoXModel:()=>IE,GPTNeoXPreTrainedModel:()=>xl,Gemma2ForCausalLM:()=>_E,Gemma2Model:()=>mE,Gemma2PreTrainedModel:()=>dl,Gemma3ForCausalLM:()=>wE,Gemma3Model:()=>gE,Gemma3PreTrainedModel:()=>pl,Gemma3nForCausalLM:()=>nf,Gemma3nForConditionalGeneration:()=>hl,Gemma3nPreTrainedModel:()=>rf,GemmaForCausalLM:()=>fE,GemmaModel:()=>hE,GemmaPreTrainedModel:()=>ul,GlmForCausalLM:()=>vE,GlmModel:()=>yE,GlmMoeDsaForCausalLM:()=>ME,GlmMoeDsaModel:()=>bE,GlmMoeDsaPreTrainedModel:()=>ml,GlmOcrForConditionalGeneration:()=>xE,GlmPreTrainedModel:()=>fl,GptOssForCausalLM:()=>OE,GptOssModel:()=>RE,GptOssPreTrainedModel:()=>Tl,GraniteForCausalLM:()=>UE,GraniteModel:()=>BE,GraniteMoeHybridForCausalLM:()=>$E,GraniteMoeHybridModel:()=>zE,GraniteMoeHybridPreTrainedModel:()=>Al,GranitePreTrainedModel:()=>Cl,GraniteSpeechForConditionalGeneration:()=>VE,GroundingDinoForObjectDetection:()=>GE,GroundingDinoPreTrainedModel:()=>of,GroupViTModel:()=>jE,GroupViTPreTrainedModel:()=>lf,HeliumForCausalLM:()=>WE,HeliumModel:()=>qE,HeliumPreTrainedModel:()=>Il,HieraForImageClassification:()=>KE,HieraModel:()=>HE,HieraPreTrainedModel:()=>Pl,HubertForCTC:()=>tk,HubertForSequenceClassification:()=>rk,HubertModel:()=>ek,HubertPreTrainedModel:()=>ZE,HunYuanDenseV1ForCausalLM:()=>sk,HunYuanDenseV1Model:()=>nk,HunYuanDenseV1PreTrainedModel:()=>Rl,IJepaForImageClassification:()=>ck,IJepaModel:()=>lk,IJepaPreTrainedModel:()=>Ol,Idefics3ForConditionalGeneration:()=>ik,JAISLMHeadModel:()=>dk,JAISModel:()=>uk,JAISPreTrainedModel:()=>Ll,JinaCLIPModel:()=>pk,JinaCLIPPreTrainedModel:()=>Sa,JinaCLIPTextModel:()=>uf,JinaCLIPVisionModel:()=>hk,Lfm2ForCausalLM:()=>mk,Lfm2Model:()=>fk,Lfm2MoeForCausalLM:()=>wk,Lfm2MoeModel:()=>gk,Lfm2MoePreTrainedModel:()=>Nl,Lfm2PreTrainedModel:()=>Fl,Lfm2VlForConditionalGeneration:()=>yk,LightOnOcrForConditionalGeneration:()=>_k,LiteWhisperForConditionalGeneration:()=>aS,Llama4ForCausalLM:()=>Mk,Llama4PreTrainedModel:()=>df,LlamaForCausalLM:()=>bk,LlamaModel:()=>vk,LlamaPreTrainedModel:()=>Dl,LlavaForConditionalGeneration:()=>gr,LlavaOnevisionForConditionalGeneration:()=>gr,LlavaPreTrainedModel:()=>cf,LlavaQwen2ForCausalLM:()=>ok,LongT5ForConditionalGeneration:()=>Tk,LongT5Model:()=>xk,LongT5PreTrainedModel:()=>Bl,M2M100ForConditionalGeneration:()=>kk,M2M100Model:()=>Ek,M2M100PreTrainedModel:()=>Ul,MBartForCausalLM:()=>Lk,MBartForConditionalGeneration:()=>Rk,MBartForSequenceClassification:()=>Ok,MBartModel:()=>Pk,MBartPreTrainedModel:()=>ws,MPNetForMaskedLM:()=>v1,MPNetForQuestionAnswering:()=>x1,MPNetForSequenceClassification:()=>b1,MPNetForTokenClassification:()=>M1,MPNetModel:()=>y1,MPNetPreTrainedModel:()=>bn,MT5ForConditionalGeneration:()=>C1,MT5Model:()=>k1,MT5PreTrainedModel:()=>Jl,MarianMTModel:()=>Ak,MarianModel:()=>Ck,MarianPreTrainedModel:()=>zl,MaskFormerForInstanceSegmentation:()=>Ik,MaskFormerModel:()=>Sk,MaskFormerPreTrainedModel:()=>$l,Metric3DForDepthEstimation:()=>Fk,Metric3DPreTrainedModel:()=>pf,Metric3Dv2ForDepthEstimation:()=>Nk,Metric3Dv2PreTrainedModel:()=>hf,MgpstrForSceneTextRecognition:()=>Dk,MgpstrModelOutput:()=>ff,MgpstrPreTrainedModel:()=>mf,MimiDecoderModel:()=>yf,MimiDecoderOutput:()=>gf,MimiEncoderModel:()=>wf,MimiEncoderOutput:()=>_f,MimiModel:()=>Bk,MimiPreTrainedModel:()=>Ia,Mistral4ForCausalLM:()=>Vk,Mistral4Model:()=>$k,Mistral4PreTrainedModel:()=>Gl,MistralForCausalLM:()=>zk,MistralModel:()=>Uk,MistralPreTrainedModel:()=>Vl,MobileBertForMaskedLM:()=>jk,MobileBertForQuestionAnswering:()=>Wk,MobileBertForSequenceClassification:()=>qk,MobileBertModel:()=>Gk,MobileBertPreTrainedModel:()=>ys,MobileLLMForCausalLM:()=>Kk,MobileLLMModel:()=>Hk,MobileLLMPreTrainedModel:()=>jl,MobileNetV1ForImageClassification:()=>Jk,MobileNetV1ForSemanticSegmentation:()=>Xk,MobileNetV1Model:()=>Qk,MobileNetV1PreTrainedModel:()=>Pa,MobileNetV2ForImageClassification:()=>Zk,MobileNetV2ForSemanticSegmentation:()=>e1,MobileNetV2Model:()=>Yk,MobileNetV2PreTrainedModel:()=>Ra,MobileNetV3ForImageClassification:()=>r1,MobileNetV3ForSemanticSegmentation:()=>n1,MobileNetV3Model:()=>t1,MobileNetV3PreTrainedModel:()=>Oa,MobileNetV4ForImageClassification:()=>a1,MobileNetV4ForSemanticSegmentation:()=>o1,MobileNetV4Model:()=>s1,MobileNetV4PreTrainedModel:()=>La,MobileViTForImageClassification:()=>l1,MobileViTModel:()=>i1,MobileViTPreTrainedModel:()=>ql,MobileViTV2ForImageClassification:()=>u1,MobileViTV2Model:()=>c1,MobileViTV2PreTrainedModel:()=>Wl,ModernBertDecoderForCausalLM:()=>_1,ModernBertDecoderModel:()=>m1,ModernBertDecoderPreTrainedModel:()=>Hl,ModernBertForMaskedLM:()=>p1,ModernBertForSequenceClassification:()=>h1,ModernBertForTokenClassification:()=>f1,ModernBertModel:()=>d1,ModernBertPreTrainedModel:()=>vs,Moondream1ForConditionalGeneration:()=>ak,MoonshineForConditionalGeneration:()=>w1,MoonshineModel:()=>g1,MoonshinePreTrainedModel:()=>Kl,MptForCausalLM:()=>E1,MptModel:()=>T1,MptPreTrainedModel:()=>Ql,MultiModalityCausalLM:()=>A1,MultiModalityPreTrainedModel:()=>vf,MusicgenForCausalLM:()=>I1,MusicgenForConditionalGeneration:()=>bf,MusicgenModel:()=>S1,MusicgenPreTrainedModel:()=>Xl,NanoChatForCausalLM:()=>R1,NanoChatModel:()=>P1,NanoChatPreTrainedModel:()=>Yl,NemotronHForCausalLM:()=>L1,NemotronHModel:()=>O1,NemotronHPreTrainedModel:()=>Zl,NeoBertForMaskedLM:()=>N1,NeoBertForQuestionAnswering:()=>U1,NeoBertForSequenceClassification:()=>D1,NeoBertForTokenClassification:()=>B1,NeoBertModel:()=>F1,NeoBertPreTrainedModel:()=>Mn,NomicBertModel:()=>z1,NomicBertPreTrainedModel:()=>Mf,OPTForCausalLM:()=>Y1,OPTModel:()=>X1,OPTPreTrainedModel:()=>ac,Olmo2ForCausalLM:()=>j1,Olmo2Model:()=>G1,Olmo2PreTrainedModel:()=>tc,Olmo3ForCausalLM:()=>W1,Olmo3Model:()=>q1,Olmo3PreTrainedModel:()=>rc,OlmoForCausalLM:()=>V1,OlmoHybridForCausalLM:()=>K1,OlmoHybridModel:()=>H1,OlmoHybridPreTrainedModel:()=>nc,OlmoModel:()=>$1,OlmoPreTrainedModel:()=>ec,OpenELMForCausalLM:()=>J1,OpenELMModel:()=>Q1,OpenELMPreTrainedModel:()=>sc,OwlViTForObjectDetection:()=>rC,OwlViTModel:()=>tC,OwlViTPreTrainedModel:()=>ic,Owlv2ForObjectDetection:()=>eC,Owlv2Model:()=>Z1,Owlv2PreTrainedModel:()=>oc,PaliGemmaForConditionalGeneration:()=>nC,ParakeetForCTC:()=>sC,ParakeetPreTrainedModel:()=>xf,PatchTSMixerForPrediction:()=>oC,PatchTSMixerModel:()=>aC,PatchTSMixerPreTrainedModel:()=>lc,PatchTSTForPrediction:()=>lC,PatchTSTModel:()=>iC,PatchTSTPreTrainedModel:()=>cc,Phi3ForCausalLM:()=>pC,Phi3Model:()=>dC,Phi3PreTrainedModel:()=>dc,Phi3VForCausalLM:()=>Ef,Phi3VPreTrainedModel:()=>Tf,PhiForCausalLM:()=>uC,PhiModel:()=>cC,PhiPreTrainedModel:()=>uc,PreTrainedModel:()=>I,PvtForImageClassification:()=>fC,PvtModel:()=>hC,PvtPreTrainedModel:()=>pc,PyAnnoteForAudioFrameClassification:()=>_C,PyAnnoteModel:()=>mC,PyAnnotePreTrainedModel:()=>hc,Qwen2ForCausalLM:()=>wC,Qwen2Model:()=>gC,Qwen2MoeForCausalLM:()=>vC,Qwen2MoeModel:()=>yC,Qwen2MoePreTrainedModel:()=>mc,Qwen2PreTrainedModel:()=>fc,Qwen2VLForCausalLM:()=>gl,Qwen2VLForConditionalGeneration:()=>_l,Qwen2VLPreTrainedModel:()=>sf,Qwen2_5_VLForCausalLM:()=>yl,Qwen2_5_VLForConditionalGeneration:()=>wl,Qwen3ForCausalLM:()=>MC,Qwen3Model:()=>bC,Qwen3MoeForCausalLM:()=>TC,Qwen3MoeModel:()=>xC,Qwen3MoePreTrainedModel:()=>gc,Qwen3NextForCausalLM:()=>kC,Qwen3NextModel:()=>EC,Qwen3NextPreTrainedModel:()=>wc,Qwen3PreTrainedModel:()=>_c,Qwen3VLForCausalLM:()=>vc,Qwen3VLForConditionalGeneration:()=>yc,Qwen3VLMoeForCausalLM:()=>kf,Qwen3VLMoeForConditionalGeneration:()=>CC,Qwen3_5ForCausalLM:()=>Mc,Qwen3_5ForConditionalGeneration:()=>bc,Qwen3_5MoeForCausalLM:()=>Cf,Qwen3_5MoeForConditionalGeneration:()=>AC,RFDetrForObjectDetection:()=>RC,RFDetrModel:()=>PC,RFDetrObjectDetectionOutput:()=>Af,RFDetrPreTrainedModel:()=>Tc,RTDetrForObjectDetection:()=>nT,RTDetrModel:()=>rT,RTDetrObjectDetectionOutput:()=>ms,RTDetrPreTrainedModel:()=>Ji,RTDetrV2ForObjectDetection:()=>jC,RTDetrV2Model:()=>GC,RTDetrV2ObjectDetectionOutput:()=>Sf,RTDetrV2PreTrainedModel:()=>Ec,ResNetForImageClassification:()=>IC,ResNetModel:()=>SC,ResNetPreTrainedModel:()=>xc,RoFormerForMaskedLM:()=>UC,RoFormerForQuestionAnswering:()=>VC,RoFormerForSequenceClassification:()=>zC,RoFormerForTokenClassification:()=>$C,RoFormerModel:()=>BC,RoFormerPreTrainedModel:()=>Tn,RobertaForMaskedLM:()=>LC,RobertaForQuestionAnswering:()=>DC,RobertaForSequenceClassification:()=>FC,RobertaForTokenClassification:()=>NC,RobertaModel:()=>OC,RobertaPreTrainedModel:()=>xn,Sam2ImageSegmentationOutput:()=>Rf,Sam2Model:()=>kc,Sam2PreTrainedModel:()=>Of,Sam3TrackerModel:()=>HC,SamImageSegmentationOutput:()=>If,SamModel:()=>qC,SamPreTrainedModel:()=>Pf,SapiensForDepthEstimation:()=>QC,SapiensForNormalEstimation:()=>JC,SapiensForSemanticSegmentation:()=>KC,SapiensPreTrainedModel:()=>Fa,SegformerForImageClassification:()=>YC,SegformerForSemanticSegmentation:()=>ZC,SegformerModel:()=>XC,SegformerPreTrainedModel:()=>Na,SiglipModel:()=>eA,SiglipPreTrainedModel:()=>Cc,SiglipTextModel:()=>Lf,SiglipVisionModel:()=>tA,SmolLM3ForCausalLM:()=>nA,SmolLM3Model:()=>rA,SmolLM3PreTrainedModel:()=>Ac,SnacDecoderModel:()=>Nf,SnacEncoderModel:()=>Ff,SnacModel:()=>sA,SnacPreTrainedModel:()=>Da,SolarOpenForCausalLM:()=>oA,SolarOpenModel:()=>aA,SolarOpenPreTrainedModel:()=>Sc,SpeechT5ForSpeechToText:()=>lA,SpeechT5ForTextToSpeech:()=>cA,SpeechT5HifiGan:()=>uA,SpeechT5Model:()=>iA,SpeechT5PreTrainedModel:()=>Ba,SqueezeBertForMaskedLM:()=>pA,SqueezeBertForQuestionAnswering:()=>fA,SqueezeBertForSequenceClassification:()=>hA,SqueezeBertModel:()=>dA,SqueezeBertPreTrainedModel:()=>bs,StableLmForCausalLM:()=>_A,StableLmModel:()=>mA,StableLmPreTrainedModel:()=>Ic,Starcoder2ForCausalLM:()=>wA,Starcoder2Model:()=>gA,Starcoder2PreTrainedModel:()=>Pc,StyleTextToSpeech2Model:()=>yA,StyleTextToSpeech2PreTrainedModel:()=>Df,SupertonicForConditionalGeneration:()=>Uf,SupertonicPreTrainedModel:()=>Bf,Swin2SRForImageSuperResolution:()=>TA,Swin2SRModel:()=>xA,Swin2SRPreTrainedModel:()=>Rc,SwinForImageClassification:()=>bA,SwinForSemanticSegmentation:()=>MA,SwinModel:()=>vA,SwinPreTrainedModel:()=>Ua,T5ForConditionalGeneration:()=>kA,T5Model:()=>EA,T5PreTrainedModel:()=>Oc,TableTransformerForObjectDetection:()=>AA,TableTransformerModel:()=>CA,TableTransformerObjectDetectionOutput:()=>zf,TableTransformerPreTrainedModel:()=>Lc,TrOCRForCausalLM:()=>SA,TrOCRPreTrainedModel:()=>$f,UltravoxModel:()=>Sl,UltravoxPreTrainedModel:()=>af,UniSpeechForCTC:()=>PA,UniSpeechForSequenceClassification:()=>RA,UniSpeechModel:()=>IA,UniSpeechPreTrainedModel:()=>za,UniSpeechSatForAudioFrameClassification:()=>NA,UniSpeechSatForCTC:()=>LA,UniSpeechSatForSequenceClassification:()=>FA,UniSpeechSatModel:()=>OA,UniSpeechSatPreTrainedModel:()=>Ms,VaultGemmaForCausalLM:()=>BA,VaultGemmaModel:()=>DA,VaultGemmaPreTrainedModel:()=>Fc,ViTForImageClassification:()=>$A,ViTMAEModel:()=>VA,ViTMAEPreTrainedModel:()=>Vf,ViTMSNForImageClassification:()=>jA,ViTMSNModel:()=>GA,ViTMSNPreTrainedModel:()=>Dc,ViTModel:()=>zA,ViTPreTrainedModel:()=>Nc,VisionEncoderDecoderModel:()=>UA,VitMatteForImageMatting:()=>qA,VitMattePreTrainedModel:()=>Gf,VitPoseForPoseEstimation:()=>WA,VitPosePreTrainedModel:()=>jf,VitsModel:()=>HA,VitsModelOutput:()=>qf,VitsPreTrainedModel:()=>Wf,VoxtralForConditionalGeneration:()=>KA,VoxtralRealtimeForConditionalGeneration:()=>Kf,VoxtralRealtimePreTrainedModel:()=>Hf,Wav2Vec2BertForCTC:()=>JA,Wav2Vec2BertForSequenceClassification:()=>XA,Wav2Vec2BertModel:()=>QA,Wav2Vec2BertPreTrainedModel:()=>$a,Wav2Vec2ForAudioFrameClassification:()=>YE,Wav2Vec2ForCTC:()=>JE,Wav2Vec2ForSequenceClassification:()=>XE,Wav2Vec2Model:()=>QE,Wav2Vec2PreTrainedModel:()=>Mr,WavLMForAudioFrameClassification:()=>rS,WavLMForCTC:()=>ZA,WavLMForSequenceClassification:()=>eS,WavLMForXVector:()=>tS,WavLMModel:()=>YA,WavLMPreTrainedModel:()=>En,WeSpeakerResNetModel:()=>nS,WeSpeakerResNetPreTrainedModel:()=>Jf,WhisperForConditionalGeneration:()=>Xf,WhisperModel:()=>sS,WhisperPreTrainedModel:()=>Bc,XLMForQuestionAnswering:()=>uS,XLMForSequenceClassification:()=>lS,XLMForTokenClassification:()=>cS,XLMModel:()=>oS,XLMPreTrainedModel:()=>kn,XLMRobertaForMaskedLM:()=>pS,XLMRobertaForQuestionAnswering:()=>mS,XLMRobertaForSequenceClassification:()=>hS,XLMRobertaForTokenClassification:()=>fS,XLMRobertaModel:()=>dS,XLMRobertaPreTrainedModel:()=>Cn,XLMWithLMHeadModel:()=>iS,XVectorOutput:()=>Qf,YolosForObjectDetection:()=>gS,YolosModel:()=>_S,YolosObjectDetectionOutput:()=>Yf,YolosPreTrainedModel:()=>Uc,YoutuForCausalLM:()=>yS,YoutuModel:()=>wS,YoutuPreTrainedModel:()=>zc});fs=class extends I{},Zx=class extends fs{},e0=class extends fs{async _call(e){return new oe(await super._call(e))}},t0=class extends fs{async _call(e){return new _t(await super._call(e))}},r0=class extends fs{async _call(e){return new Je(await super._call(e))}},Ni=class extends I{},n0=class extends Ni{},s0=class extends Ni{},Di=class extends I{},a0=class extends Di{},o0=class extends Di{},Bi=class extends I{},i0=class extends Bi{},l0=class extends Bi{},Ui=class extends I{},c0=class extends Ui{},u0=class extends Ui{},Ea=class extends I{},d0=class extends Ea{},p0=class extends Ea{},h0=class extends Ea{async _call(e){return new oe(await super._call(e))}},zi=class extends I{},f0=class extends zi{},m0=class extends zi{async _call(e){return new oe(await super._call(e))}},fn=class extends I{},_0=class extends fn{},g0=class extends fn{async _call(e){return new Je(await super._call(e))}},w0=class extends fn{async _call(e){return new oe(await super._call(e))}},y0=class extends fn{async _call(e){return new je(await super._call(e))}},v0=class extends fn{async _call(e){return new _t(await super._call(e))}},$i=class extends I{},b0=class extends $i{},M0=class extends $i{},Vi=class extends I{},x0=class extends Vi{},T0=class extends Vi{},Gi=class extends I{},E0=class extends Gi{},k0=class extends Gi{},mn=class extends I{},C0=class extends mn{},A0=class extends mn{async _call(e){return new Je(await super._call(e))}},S0=class extends mn{async _call(e){return new oe(await super._call(e))}},I0=class extends mn{async _call(e){return new je(await super._call(e))}},P0=class extends mn{async _call(e){return new _t(await super._call(e))}},xU=4299n,pv=6561n,Dh=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);w(this,"main_input_name","input_ids");w(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},Bh=class extends Dh{async encode_speech(e){return be(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:c=null,audio_tokens:u=null,speaker_embeddings:p=null,speaker_features:f=null,...m}){let y;if(!a){let x=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(x.includes("exaggeration")){if(!(n instanceof q)){let T=e.dims[0];if(n==null)n=lt([T],.5);else if(typeof n=="number")n=lt([T],n);else if(Array.isArray(n))n=new q("float32",n,[T]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=n}if(x.includes("position_ids")&&(M.position_ids=s),{inputs_embeds:a}=await be(this.sessions.embed_tokens,M),c&&u&&p&&f&&(y={audio_features:c,audio_tokens:u,speaker_embeddings:p,speaker_features:f}),y||r)y??(y=await this.encode_speech(r)),a=Fe([y.audio_features,a],1),t=xt([a.dims[0],a.dims[1]]);else{let T=a.dims[1];if(!o||T!==1)throw new Error("Incorrect state encountered during generation.");let A=o.get_seq_length();t=xt([a.dims[0],A+T])}}return{...await _r(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...y}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){let n=Array.from({length:e.length},(s,a)=>e[a].length-e[a].findLastIndex(o=>o==pv)-1);t.position_ids=new q("int64",n,[e.length,1])}else{let s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=pv?0:o++)});t.position_ids=new q("int64",s.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ha(this,e,t,r)}async generate(e){let{sequences:t,audio_tokens:r,speaker_embeddings:n,speaker_features:s}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=lt([a.dims[0],3],xU),i=Fe([r,a,o],1),{waveform:l}=await be(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:s,speaker_embeddings:n});return l}},Uh=class extends I{},R0=class extends Uh{},zh=class extends I{},O0=class extends zh{},ka=class extends I{},L0=class extends ka{},$h=class extends ka{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Vh=class extends ka{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Nr=class extends I{},F0=class extends Nr{},N0=class extends Nr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Gh=class extends Nr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},D0=class extends Nr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},B0=class extends Nr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},ji=class extends I{},U0=class extends ji{},z0=class extends ji{},qi=class extends I{},$0=class extends qi{},V0=class extends qi{},Wi=class extends I{},G0=class extends Wi{},j0=class extends Wi{},Hi=class extends I{},q0=class extends Hi{},W0=class extends Hi{},_n=class extends I{},H0=class extends _n{},K0=class extends _n{async _call(e){return new Je(await super._call(e))}},Q0=class extends _n{async _call(e){return new oe(await super._call(e))}},J0=class extends _n{async _call(e){return new je(await super._call(e))}},X0=class extends _n{async _call(e){return new _t(await super._call(e))}},Ki=class extends I{},Y0=class extends Ki{},Z0=class extends Ki{async _call(e){return new oe(await super._call(e))}},Qi=class extends I{},eT=class extends Qi{},tT=class extends Qi{async _call(e){return new oe(await super._call(e))}},Ji=class extends I{},rT=class extends Ji{},nT=class extends Ji{async _call(e){return new ms(await super._call(e))}},ms=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Xi=class extends I{},sT=class extends Xi{},aT=class extends Xi{async _call(e){return new ms(await super._call(e))}},jh=class extends Qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},qh=class extends Qe{constructor({audio_values:e}){super(),this.audio_values=e}},Ca=class extends I{constructor(){super(...arguments);w(this,"main_input_name","input_values");w(this,"forward_params",["input_values"])}},oT=class extends Ca{async encode(e){return new jh(await be(this.sessions.encoder_model,e))}async decode(e){return new qh(await be(this.sessions.decoder_model,e))}},Wh=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Hh=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},gn=class extends I{},iT=class extends gn{},lT=class extends gn{async _call(e){return new Je(await super._call(e))}},cT=class extends gn{async _call(e){return new oe(await super._call(e))}},uT=class extends gn{async _call(e){return new je(await super._call(e))}},dT=class extends gn{async _call(e){return new _t(await super._call(e))}},Yi=class extends I{},pT=class extends Yi{},hT=class extends Yi{},wn=class extends I{},fT=class extends wn{},mT=class extends wn{async _call(e){return new Je(await super._call(e))}},_T=class extends wn{async _call(e){return new oe(await super._call(e))}},gT=class extends wn{async _call(e){return new je(await super._call(e))}},wT=class extends wn{async _call(e){return new _t(await super._call(e))}},Kh=class extends I{},yT=class extends Kh{},Zi=class extends I{},vT=class extends Zi{},bT=class extends Zi{async _call(e){return new oe(await super._call(e))}},Qh=class extends I{},MT=class extends Qh{},Jh=class extends I{},xT=class extends Jh{},Aa=class extends I{},TT=class extends Aa{},ET=class extends Aa{async _call(e){return new el(await super._call(e))}},kT=class extends Aa{async _call(e){return new Xh(await super._call(e))}},el=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Xh=class extends Qe{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},tl=class extends I{},CT=class extends tl{},AT=class extends tl{async _call(e){return new oe(await super._call(e))}},rl=class extends I{},ST=class extends rl{},IT=class extends rl{async _call(e){return new oe(await super._call(e))}},Yh=class extends I{},PT=class extends Yh{},Zh=class extends I{},RT=class extends Zh{},yn=class extends I{},OT=class extends yn{},LT=class extends yn{async _call(e){return new oe(await super._call(e))}},FT=class extends yn{async _call(e){return new je(await super._call(e))}},NT=class extends yn{async _call(e){return new _t(await super._call(e))}},DT=class extends yn{async _call(e){return new Je(await super._call(e))}},ef=class extends I{},BT=class extends ef{},nl=class extends I{},UT=class extends nl{},zT=class extends nl{},sl=class extends I{},$T=class extends sl{},VT=class extends sl{async _call(e){return new oe(await super._call(e))}},vn=class extends I{},GT=class extends vn{},jT=class extends vn{async _call(e){return new Je(await super._call(e))}},qT=class extends vn{async _call(e){return new oe(await super._call(e))}},WT=class extends vn{async _call(e){return new je(await super._call(e))}},HT=class extends vn{async _call(e){return new _t(await super._call(e))}},al=class extends I{},KT=class extends al{},QT=class extends al{},_s=class extends I{},JT=class extends _s{},XT=class extends _s{async _call(e){return new Je(await super._call(e))}},YT=class extends _s{async _call(e){return new oe(await super._call(e))}},ZT=class extends _s{async _call(e){return new je(await super._call(e))}},gs=class extends I{},eE=class extends gs{},tE=class extends gs{async _call(e){return new Je(await super._call(e))}},rE=class extends gs{async _call(e){return new oe(await super._call(e))}},nE=class extends gs{async _call(e){return new je(await super._call(e))}},ol=class extends I{},sE=class extends ol{},aE=class extends ol{},il=class extends I{},oE=class extends il{},iE=class extends il{},ll=class extends I{},lE=class extends ll{},cE=class extends ll{},cl=class extends I{},uE=class extends cl{},dE=class extends cl{async _call(e){return new oe(await super._call(e))}},tf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);w(this,"main_input_name","inputs_embeds")}},pE=class extends tf{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Fe([t,e],1),attention_mask:Fe([xt(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:n}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let s,a;return e&&(s=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),s&&a?{inputs_embeds:r,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:s,image_features:a,input_ids:e,attention_mask:n}):r=s||a,{inputs_embeds:r,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:n,decoder_attention_mask:s,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:u}=await Lr(this,{inputs_embeds:i,attention_mask:r});a=u}if(!l){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}return await _r(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},ul=class extends I{},hE=class extends ul{},fE=class extends ul{},dl=class extends I{},mE=class extends dl{},_E=class extends dl{},pl=class extends I{},gE=class extends pl{},wE=class extends pl{},rf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},hl=class extends rf{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:n=null,input_features_mask:s=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:u=null,...p}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await be(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){let{image_features:m}=await be(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:m,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){let{audio_features:m}=await be(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:m,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await _r(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:u},!0)}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Fh({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Yx({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},nf=class extends hl{},fl=class extends I{},yE=class extends fl{},vE=class extends fl{},ml=class extends I{},bE=class extends ml{},ME=class extends ml{},sf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},_l=class extends sf{constructor(){super(...arguments);w(this,"image_grid_thw_name","grid_thw")}_get_text_only_rope_index(t,r){if(r){let{data:n,dims:s}=Jx(r),a=BigInt64Array.from({length:3*n.length},(i,l)=>n[l%n.length]),o=Array.from({length:s[0]},(i,l)=>Ge(n.subarray(s[1]*l,s[1]*(l+1)))[0]+1n+BigInt(s[1]));return[new q("int64",a,[3,...s]),new q("int64",o,[o.length,1])]}else{let[n,s]=t.dims,a=BigInt64Array.from({length:3*n*s},(o,i)=>BigInt(Math.floor(i%s/n)));return[new q("int64",a,[3,...t.dims]),rh([n,1])]}}_reorder_and_write_positions(t,r,n,s){let a=t.reduce((c,u)=>c+u.length,0),o=new Array(a),i=0;for(let c=0;c<3;++c)for(let u of t){let p=u.length/3;for(let f=c*p;f<(c+1)*p;++f)o[i++]=u[f]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let u=0;u<3;++u)n[u][s][c]=o[u*a/3+l];++l}return o}_get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:r,video_grid_thw_list:n,spatial_merge_size:s,state:a}){let{image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,c=t,p=c.reduce((T,A,C)=>(A==l&&T.push(C),T),[]).map(T=>c[T+1]),f=p.filter(T=>T==o).length,m=p.filter(T=>T==i).length,y=[],v=0,x=f,M=m;for(let T=0;T<p.length;++T){let A=c.findIndex((Y,fe)=>fe>v&&Y==o),C=c.findIndex((Y,fe)=>fe>v&&Y==i),S=x>0&&A!==-1?A:c.length+1,O=M>0&&C!==-1?C:c.length+1,E,K,$,V;S<O?([K,$,V]=r[a.image_index],++a.image_index,--x,E=S):([K,$,V]=n[a.video_index],++a.video_index,--M,E=O);let[Q,G,W]=[Number(K),Math.floor(Number($)/s),Math.floor(Number(V)/s)],D=E-v,R=y.length>0?Ge(y.at(-1))[0]+1:0;y.push(Array.from({length:3*D},(Y,fe)=>R+fe%D));let re=D+R,ie=Q*G*W,F=Array.from({length:ie},(Y,fe)=>re+Math.floor(fe/(G*W))),N=Array.from({length:ie},(Y,fe)=>re+Math.floor(fe/W)%G),z=Array.from({length:ie},(Y,fe)=>re+fe%W);y.push([F,N,z].flat()),v=E+ie}if(v<c.length){let T=y.length>0?Ge(y.at(-1))[0]+1:0,A=c.length-v;y.push(Array.from({length:3*A},(C,S)=>T+S%A))}return y}get_rope_index(t,r,n,s){let{vision_config:a}=this.config,o=a.spatial_merge_size??2;if(r||n){let i=t.tolist();s||(s=th(t));let l=s.tolist(),c=Array.from({length:3},()=>Array.from({length:t.dims[0]},()=>Array.from({length:t.dims[1]},()=>0))),u=r?r.tolist():[],p=n?n.tolist():[],f={image_index:0,video_index:0},m=[];for(let y=0;y<i.length;++y){let v=i[y].filter((T,A)=>l[y][A]==1),x=this._get_multimodal_rope_positions({filtered_ids:v,image_grid_thw_list:u,video_grid_thw_list:p,spatial_merge_size:o,state:f}),M=this._reorder_and_write_positions(x,l[y],c,y);m.push(Ge(M)[0]+1-i[y].length)}return[new q("int64",c.flat(1/0),[3,t.dims[0],t.dims[1]]),new q("int64",m,[m.length,1])]}else return this._get_text_only_rope_index(t,s)}async encode_image({pixel_values:t,image_grid_thw:r}){return(await be(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return Fh({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,n){if(r.attention_mask&&!r.position_ids)if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let s=r.past_key_values.get_seq_length();if(s<r.input_ids.dims[1]){let[a,o]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=o,r.position_ids=a.slice(null,null,[s,null]),r.input_ids=r.input_ids.slice(null,[s,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));let a=BigInt(s),o=r.rope_deltas.map(i=>a+i);r.position_ids=Fr([o,o,o],0)}}return r}},gl=class extends _l{},wl=class extends _l{constructor(){super(...arguments);w(this,"image_grid_thw_name","image_grid_thw")}},yl=class extends gl{constructor(){super(...arguments);w(this,"image_grid_thw_name","image_grid_thw")}},xE=class extends wl{get_vision_position_ids(e,t,r,n){let s=Math.floor(t[0]/r),a=Math.floor(t[1]/n),o=Math.floor(t[2]/n),i=a*o*s,l=Array.from({length:i},()=>e),c=Array.from({length:i},(p,f)=>e+Math.floor(f/(o*s))),u=Array.from({length:i},(p,f)=>e+f%o);return[...l,...c,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:n,state:s}){let{image_token_id:a}=this.config,o=[],i=0,l=e[0]==a?1:0;for(let p=1;p<=e.length;++p){let f=p<e.length?e[p]==a?1:0:-1;f!==l&&(o.push([l,i,p]),i=p,l=f)}let c=0,u=[];for(let[p,f,m]of o)if(p===0){let y=m-f;u.push(Array.from({length:3*y},(v,x)=>c+x%y)),c+=y}else{let y=t[s.image_index++].map(Number),v=y[0];u.push(this.get_vision_position_ids(c,y,v,n)),c+=Math.max(y[1],y[2])/n}return u}},vl=class extends I{},TE=class extends vl{},EE=class extends vl{},bl=class extends I{},kE=class extends bl{},CE=class extends bl{},Ml=class extends I{},AE=class extends Ml{},SE=class extends Ml{},xl=class extends I{},IE=class extends xl{},PE=class extends xl{},Tl=class extends I{},RE=class extends Tl{},OE=class extends Tl{},El=class extends I{},LE=class extends El{},FE=class extends El{},kl=class extends I{},NE=class extends kl{},DE=class extends kl{},Cl=class extends I{},BE=class extends Cl{},UE=class extends Cl{},Al=class extends I{},zE=class extends Al{},$E=class extends Al{},af=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}},Sl=class extends af{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Yx({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},VE=class extends Sl{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","input_features","past_key_values"])}},of=class extends I{},GE=class extends of{},lf=class extends I{},jE=class extends lf{},Il=class extends I{},qE=class extends Il{},WE=class extends Il{},Pl=class extends I{},HE=class extends Pl{},KE=class extends Pl{async _call(e){return new oe(await super._call(e))}},Mr=class extends I{},QE=class extends Mr{},JE=class extends Mr{async _call(e){return new hn(await super._call(e))}},XE=class extends Mr{async _call(e){return new oe(await super._call(e))}},YE=class extends Mr{async _call(e){return new je(await super._call(e))}},ZE=class extends I{},ek=class extends Mr{},tk=class extends Mr{async _call(e){return new hn(await super._call(e))}},rk=class extends Mr{async _call(e){return new oe(await super._call(e))}},Rl=class extends I{},nk=class extends Rl{},sk=class extends Rl{},cf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},gr=class extends cf{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return Fh({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},ak=class extends gr{},ok=class extends gr{},ik=class extends gr{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},Ol=class extends I{},lk=class extends Ol{},ck=class extends Ol{async _call(e){return new oe(await super._call(e))}},Ll=class extends I{},uk=class extends Ll{},dk=class extends Ll{},Sa=class extends I{},pk=class extends Sa{async forward(e){let t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=xt([e.pixel_values.dims[0],1])),r){let{image_size:l}=this.config.vision_config;e.pixel_values=lt([0,3,l,l],0)}let{text_embeddings:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=n,i.l2norm_text_embeddings=a),r||(i.image_embeddings=s,i.l2norm_image_embeddings=o),i}},uf=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},hk=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Fl=class extends I{},fk=class extends Fl{},mk=class extends Fl{},_k=class extends gr{},Nl=class extends I{},gk=class extends Nl{},wk=class extends Nl{},yk=class extends gr{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"])}},Dl=class extends I{},vk=class extends Dl{},bk=class extends Dl{},df=class extends I{},Mk=class extends df{},Bl=class extends I{},xk=class extends Bl{},Tk=class extends Bl{},Ul=class extends I{},Ek=class extends Ul{},kk=class extends Ul{},zl=class extends I{},Ck=class extends zl{},Ak=class extends zl{},$l=class extends I{},Sk=class extends $l{},Ik=class extends $l{},ws=class extends I{},Pk=class extends ws{},Rk=class extends ws{},Ok=class extends ws{async _call(e){return new oe(await super._call(e))}},Lk=class extends ws{},pf=class extends I{},Fk=class extends pf{},hf=class extends I{},Nk=class extends hf{},ff=class extends Qe{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},mf=class extends I{},Dk=class extends mf{async _call(e){return new ff(await super._call(e))}},_f=class extends Qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},gf=class extends Qe{constructor({audio_values:e}){super(),this.audio_values=e}},Ia=class extends I{constructor(){super(...arguments);w(this,"main_input_name","input_values");w(this,"forward_params",["input_values"])}},Bk=class extends Ia{async encode(e){return new _f(await be(this.sessions.encoder_model,e))}async decode(e){return new gf(await be(this.sessions.decoder_model,e))}},wf=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},yf=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Vl=class extends I{},Uk=class extends Vl{},zk=class extends Vl{},Gl=class extends I{},$k=class extends Gl{},Vk=class extends Gl{},ys=class extends I{},Gk=class extends ys{},jk=class extends ys{async _call(e){return new Je(await super._call(e))}},qk=class extends ys{async _call(e){return new oe(await super._call(e))}},Wk=class extends ys{async _call(e){return new _t(await super._call(e))}},jl=class extends I{},Hk=class extends jl{},Kk=class extends jl{},Pa=class extends I{},Qk=class extends Pa{},Jk=class extends Pa{async _call(e){return new oe(await super._call(e))}},Xk=class extends Pa{},Ra=class extends I{},Yk=class extends Ra{},Zk=class extends Ra{async _call(e){return new oe(await super._call(e))}},e1=class extends Ra{},Oa=class extends I{},t1=class extends Oa{},r1=class extends Oa{async _call(e){return new oe(await super._call(e))}},n1=class extends Oa{},La=class extends I{},s1=class extends La{},a1=class extends La{async _call(e){return new oe(await super._call(e))}},o1=class extends La{},ql=class extends I{},i1=class extends ql{},l1=class extends ql{async _call(e){return new oe(await super._call(e))}},Wl=class extends I{},c1=class extends Wl{},u1=class extends Wl{async _call(e){return new oe(await super._call(e))}},vs=class extends I{},d1=class extends vs{},p1=class extends vs{async _call(e){return new Je(await super._call(e))}},h1=class extends vs{async _call(e){return new oe(await super._call(e))}},f1=class extends vs{async _call(e){return new je(await super._call(e))}},Hl=class extends I{},m1=class extends Hl{},_1=class extends Hl{},Kl=class extends I{constructor(){super(...arguments);w(this,"requires_attention_mask",!1);w(this,"main_input_name","input_values");w(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},g1=class extends Kl{},w1=class extends Kl{},bn=class extends I{},y1=class extends bn{},v1=class extends bn{async _call(e){return new Je(await super._call(e))}},b1=class extends bn{async _call(e){return new oe(await super._call(e))}},M1=class extends bn{async _call(e){return new je(await super._call(e))}},x1=class extends bn{async _call(e){return new _t(await super._call(e))}},Ql=class extends I{},T1=class extends Ql{},E1=class extends Ql{},Jl=class extends I{},k1=class extends Jl{},C1=class extends Jl{},vf=class extends I{},A1=class extends vf{constructor(...t){super(...t);w(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(t){let r=this._generation_mode??"text",n;if(r==="text"||!t.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=ot(t,l.inputNames);n=await be(l,c)}else{let l=this.sessions.gen_img_embeds,c=ot({image_ids:t.input_ids},l.inputNames);n=await be(l,c)}let s={...t,...n},a=await _r(this,s),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);let i=await be(o,ot(a,o.inputNames));return{...n,...a,...i}}prepare_inputs_for_generation(t,r,n){let s=!!r.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(s?r.input_ids=Fe([r.input_ids,r.input_ids],0):(r.input_ids=Fe([r.input_ids,_i(r.input_ids,BigInt(n.pad_token_id))],0),r.attention_mask=Fe([r.attention_mask,_i(r.attention_mask,0n)],0))),(s||!r.pixel_values)&&(r.pixel_values=lt([0,0,3,384,384],1)),s&&(r.images_seq_mask=new q("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new q("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(t){return this._generation_mode="text",super.generate(t)}async generate_images(t){this._generation_mode="image";let r=(t.inputs??t[this.main_input_name]).dims[1],s=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await be(a,{generated_tokens:s}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let u=Mt.fromTensor(c);l.push(u)}return l}},Xl=class extends I{},S1=class extends Xl{},I1=class extends Xl{},bf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(t){let[r,n]=t.dims,s=this.config.decoder.num_codebooks,a=n-s,o=0;for(let c=0;c<t.size;++c){if(t.data[c]==this.config.decoder.pad_token_id)continue;let u=c%n,p=Math.floor(c/n)%s,f=u-p;f>0&&f<=a&&(t.data[o++]=t.data[c])}let i=Math.floor(r/s),l=o/(i*s);return new q(t.type,t.data.slice(0,o),[i,s,l])}prepare_inputs_for_generation(t,r,n){let s=BigInt(this.config.decoder.pad_token_id),a=structuredClone(t);for(let o=0;o<a.length;++o)for(let i=0;i<a[o].length;++i)o%this.config.decoder.num_codebooks>=i&&(a[o][i]=s);return n.guidance_scale!==null&&n.guidance_scale>1&&(a=a.concat(a)),vi(this,a,r,n)}async generate(t){let r=await super.generate(t),n=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:s}=await be(this.sessions.encodec_decode,{audio_codes:n});return s}},Yl=class extends I{},P1=class extends Yl{},R1=class extends Yl{},Zl=class extends I{},O1=class extends Zl{},L1=class extends Zl{},Mn=class extends I{},F1=class extends Mn{},N1=class extends Mn{async _call(e){return new Je(await super._call(e))}},D1=class extends Mn{async _call(e){return new oe(await super._call(e))}},B1=class extends Mn{async _call(e){return new je(await super._call(e))}},U1=class extends Mn{async _call(e){return new _t(await super._call(e))}},Mf=class extends I{},z1=class extends Mf{},ec=class extends I{},$1=class extends ec{},V1=class extends ec{},tc=class extends I{},G1=class extends tc{},j1=class extends tc{},rc=class extends I{},q1=class extends rc{},W1=class extends rc{},nc=class extends I{},H1=class extends nc{},K1=class extends nc{},sc=class extends I{},Q1=class extends sc{},J1=class extends sc{},ac=class extends I{},X1=class extends ac{},Y1=class extends ac{},oc=class extends I{},Z1=class extends oc{},eC=class extends oc{},ic=class extends I{},tC=class extends ic{},rC=class extends ic{},nC=class extends gr{},xf=class extends I{},sC=class extends xf{async _call(e){return new hn(await super._call(e))}},lc=class extends I{},aC=class extends lc{},oC=class extends lc{},cc=class extends I{},iC=class extends cc{},lC=class extends cc{},uc=class extends I{},cC=class extends uc{},uC=class extends uc{},dc=class extends I{},dC=class extends dc{},pC=class extends dc{},Tf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},Ef=class extends Tf{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!a){let p;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:p}=await be(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{let f=this.config.normalized_config.hidden_size;p=new q("float32",[],[0,f])}({inputs_embeds:a}=await be(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:p}))}return await _r(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l},!1)}},pc=class extends I{},hC=class extends pc{},fC=class extends pc{async _call(e){return new oe(await super._call(e))}},hc=class extends I{},mC=class extends hc{},_C=class extends hc{async _call(e){return new je(await super._call(e))}},fc=class extends I{},gC=class extends fc{},wC=class extends fc{},mc=class extends I{},yC=class extends mc{},vC=class extends mc{},_c=class extends I{},bC=class extends _c{},MC=class extends _c{},gc=class extends I{},xC=class extends gc{},TC=class extends gc{},wc=class extends I{},EC=class extends wc{},kC=class extends wc{},yc=class extends wl{},vc=class extends yl{},CC=class extends yc{},kf=class extends vc{},bc=class extends yc{},Mc=class extends bc{},AC=class extends bc{},Cf=class extends Mc{},xc=class extends I{},SC=class extends xc{},IC=class extends xc{async _call(e){return new oe(await super._call(e))}},Tc=class extends I{},PC=class extends Tc{},RC=class extends Tc{async _call(e){return new Af(await super._call(e))}},Af=class extends ms{},xn=class extends I{},OC=class extends xn{},LC=class extends xn{async _call(e){return new Je(await super._call(e))}},FC=class extends xn{async _call(e){return new oe(await super._call(e))}},NC=class extends xn{async _call(e){return new je(await super._call(e))}},DC=class extends xn{async _call(e){return new _t(await super._call(e))}},Tn=class extends I{},BC=class extends Tn{},UC=class extends Tn{async _call(e){return new Je(await super._call(e))}},zC=class extends Tn{async _call(e){return new oe(await super._call(e))}},$C=class extends Tn{async _call(e){return new je(await super._call(e))}},VC=class extends Tn{async _call(e){return new _t(await super._call(e))}},Ec=class extends I{},GC=class extends Ec{},jC=class extends Ec{async _call(e){return new Sf(await super._call(e))}},Sf=class extends ms{},If=class extends Qe{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Pf=class extends I{},qC=class extends Pf{async get_image_embeddings({pixel_values:e}){return await Lr(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??(e.input_labels=xt(e.input_points.dims.slice(0,-1)));let 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 be(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new If(await super._call(e))}},Rf=class extends Qe{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},Of=class extends I{},kc=class extends Of{async get_image_embeddings({pixel_values:e}){return await Lr(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}: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.");let a=e.input_points.dims;e.input_labels??(e.input_labels=xt(a.slice(0,-1))),e.input_boxes??(e.input_boxes=lt([a[0],0,4],0))}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=lt([a[0],a[1],0],-1n),e.input_points=lt([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,s=ot(e,n.inputNames);return await be(n,s)}async _call(e){return new Rf(await super._call(e))}},WC=class extends kc{},HC=class extends kc{},Fa=class extends I{},KC=class extends Fa{},QC=class extends Fa{},JC=class extends Fa{},Na=class extends I{},XC=class extends Na{},YC=class extends Na{},ZC=class extends Na{},Cc=class extends I{},eA=class extends Cc{},Lf=class extends Cc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},tA=class extends Nr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ac=class extends I{},rA=class extends Ac{},nA=class extends Ac{},Da=class extends I{constructor(){super(...arguments);w(this,"main_input_name","input_values");w(this,"forward_params",["input_values"])}},sA=class extends Da{async encode(e){return await be(this.sessions.encoder_model,e)}async decode(e){return await be(this.sessions.decoder_model,e)}},Ff=class extends Da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Nf=class extends Da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Sc=class extends I{},aA=class extends Sc{},oA=class extends Sc{},Ba=class extends I{},iA=class extends Ba{},lA=class extends Ba{},cA=class extends Ba{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Lr(this,o),c=i.dims[1]/this.config.reduction_factor,u=Math.floor(c*s),p=Math.floor(c*n),f=this.config.num_mel_bins,m=[],y=null,v=null,x=0;for(;;){++x;let A=Kx(!!v),C;v?C=v.output_sequence_out:C=new q("float32",new Float32Array(f),[1,1,f]);let S={use_cache_branch:A,output_sequence:C,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};this.addPastKeyValues(S,y),v=await be(this.sessions.decoder_model_merged,S),y=this.getPastKeyValues(v,y);let{prob:O,spectrum:E}=v;if(m.push(E),x>=p&&(Array.from(O.data).filter(K=>K>=r).length>0||x>=u))break}let M=Fe(m),{waveform:T}=await be(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:T}}},uA=class extends I{constructor(){super(...arguments);w(this,"main_input_name","spectrogram")}},bs=class extends I{},dA=class extends bs{},pA=class extends bs{async _call(e){return new Je(await super._call(e))}},hA=class extends bs{async _call(e){return new oe(await super._call(e))}},fA=class extends bs{async _call(e){return new _t(await super._call(e))}},Ic=class extends I{},mA=class extends Ic{},_A=class extends Ic{},Pc=class extends I{},gA=class extends Pc{},wA=class extends Pc{},Df=class extends I{},yA=class extends Df{},Bf=class extends I{},Uf=class extends Bf{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:n=5,speed:s=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:c,durations:u}=await be(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),p=u.div(s).mul_(a),f=i*o,m=p.data,y=Int32Array.from(m,$=>Math.ceil($/f)),v=Math.max(...y),x=e.dims[0],M=new BigInt64Array(x*v);for(let $=0;$<x;++$)M.fill(1n,$*v,$*v+y[$]);let T=new q("int64",M,[x,v]),A=l*o,C=A*v,S=Yv([x,A,v]),O=S.data;for(let $=0;$<x;++$)if(y[$]!==v)for(let V=0;V<A;++V)O.fill(0,$*C+V*v+y[$],$*C+(V+1)*v);let E=lt([x],n);for(let $=0;$<n;++$){let V=lt([x],$);({denoised_latents:S}=await be(this.sessions.latent_denoiser,{style:r,noisy_latents:S,latent_mask:T,encoder_outputs:c,attention_mask:t,timestep:V,num_inference_steps:E}))}let{waveform:K}=await be(this.sessions.voice_decoder,{latents:S});return{waveform:K,durations:p}}},Ua=class extends I{},vA=class extends Ua{},bA=class extends Ua{async _call(e){return new oe(await super._call(e))}},MA=class extends Ua{},Rc=class extends I{},xA=class extends Rc{},TA=class extends Rc{},Oc=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}},EA=class extends Oc{},kA=class extends Oc{},Lc=class extends I{},CA=class extends Lc{},AA=class extends Lc{async _call(e){return new zf(await super._call(e))}},zf=class extends el{},$f=class extends I{},SA=class extends $f{},za=class extends I{},IA=class extends za{},PA=class extends za{async _call(e){return new hn(await super._call(e))}},RA=class extends za{async _call(e){return new oe(await super._call(e))}},Ms=class extends I{},OA=class extends Ms{},LA=class extends Ms{async _call(e){return new hn(await super._call(e))}},FA=class extends Ms{async _call(e){return new oe(await super._call(e))}},NA=class extends Ms{async _call(e){return new je(await super._call(e))}},Fc=class extends I{},DA=class extends Fc{},BA=class extends Fc{},UA=class extends I{constructor(){super(...arguments);w(this,"main_input_name","pixel_values");w(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}},Nc=class extends I{},zA=class extends Nc{},$A=class extends Nc{async _call(e){return new oe(await super._call(e))}},Vf=class extends I{},VA=class extends Vf{},Dc=class extends I{},GA=class extends Dc{},jA=class extends Dc{async _call(e){return new oe(await super._call(e))}},Gf=class extends I{},qA=class extends Gf{async _call(e){return new cU(await super._call(e))}},jf=class extends I{},WA=class extends jf{},qf=class extends Qe{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Wf=class extends I{},HA=class extends Wf{async _call(e){return new qf(await super._call(e))}},KA=class extends Sl{},hv=2,TU=1,Wd=new WeakMap;SU=class extends hs{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},Hf=class extends I{constructor(){super(...arguments);w(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values"])}},Kf=class extends Hf{async forward({input_ids:e,past_key_values:t,...r}){let n=e.dims[1],s=Wd.get(this);s&&await CU(s,s.audio_consumed+n);let{inputs_embeds:a}=await be(this.sessions.embed_tokens,{input_ids:e});s&&AU(s,a,n);let o={inputs_embeds:a,...r};this.addPastKeyValues(o,t);let i=this.sessions.decoder_model_merged,l=ot(o,i.inputNames);return await be(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=EU(this,e);Wd.set(this,n);let s=new Rh;s.push(new SU(n)),t&&s.extend(t);try{return await super.generate({...r,stopping_criteria:s})}finally{n.enc_kv_cache.dispose(),Wd.delete(this)}}},$a=class extends I{},QA=class extends $a{},JA=class extends $a{async _call(e){return new hn(await super._call(e))}},XA=class extends $a{async _call(e){return new oe(await super._call(e))}},Qf=class extends Qe{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},En=class extends I{},YA=class extends En{},ZA=class extends En{async _call(e){return new hn(await super._call(e))}},eS=class extends En{async _call(e){return new oe(await super._call(e))}},tS=class extends En{async _call(e){return new Qf(await super._call(e))}},rS=class extends En{async _call(e){return new je(await super._call(e))}},Jf=class extends I{},nS=class extends Jf{},IU=class extends jx{constructor(){super(...arguments);w(this,"return_timestamps",null);w(this,"return_token_timestamps",null);w(this,"num_frames",null);w(this,"alignment_heads",null);w(this,"task",null);w(this,"language",null);w(this,"no_timestamps_token_id",null);w(this,"prompt_ids",null);w(this,"is_multilingual",null);w(this,"lang_to_id",null);w(this,"task_to_id",null);w(this,"max_initial_timestamp_index",1)}},Bc=class extends I{constructor(){super(...arguments);w(this,"requires_attention_mask",!1);w(this,"main_input_name","input_features");w(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}},sS=class extends Bc{},Xf=class extends Bc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,IU)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],r=e.language,n=e.task;if(e.is_multilingual){r||(ce.warn("No language specified - defaulting to English (en)."),r="en");let a=`<|${_B(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(r||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(ce.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(s=>s!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,...s}){t=this._prepare_generation_config(t,s);let a=s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new yi),r.push(new Nx(t,a))),t.begin_suppress_tokens&&(r??(r=new yi),r.push(new Ph(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"&&ce.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}let o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames)),o}_extract_token_timestamps(e,t,r=null,n=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&ce.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let s=this.config.median_filter_width;s===void 0&&(ce.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);let a=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(y,v)=>Fe(a.map(x=>x[v]),2)),i=Fr(t.map(([y,v])=>{if(y>=o.length)throw new Error(`Layer index ${y} is out of bounds for cross attentions (length ${o.length}).`);return r?o[y].slice(null,v,null,[0,r]):o[y].slice(null,v)})).transpose(1,0,2,3),[l,c]=Zp(i,-2,0,!0),u=i.clone();for(let y=0;y<u.dims[0];++y){let v=u[y];for(let x=0;x<v.dims[0];++x){let M=v[x],T=l[y][x][0].data,A=c[y][x][0].data;for(let C=0;C<M.dims[0];++C){let S=M[C].data;for(let O=0;O<S.length;++O)S[O]=(S[O]-A[O])/T[O];S.set(WD(S,s))}}}let p=[ki(u,1)],f=e.sequences.dims,m=new q("float32",new Float32Array(f[0]*f[1]),f);for(let y=0;y<f[0];++y){let v=p[y].neg().squeeze_(0),[x,M]=KD(v.tolist()),T=Array.from({length:x.length-1},(S,O)=>x[O+1]-x[O]),A=jt([1],T).map(S=>!!S),C=[];for(let S=0;S<A.length;++S)A[S]&&C.push(M[S]*n);m[y].data.set(C,1)}return m}},aS=class extends Xf{},kn=class extends I{},oS=class extends kn{},iS=class extends kn{async _call(e){return new Je(await super._call(e))}},lS=class extends kn{async _call(e){return new oe(await super._call(e))}},cS=class extends kn{async _call(e){return new je(await super._call(e))}},uS=class extends kn{async _call(e){return new _t(await super._call(e))}},Cn=class extends I{},dS=class extends Cn{},pS=class extends Cn{async _call(e){return new Je(await super._call(e))}},hS=class extends Cn{async _call(e){return new oe(await super._call(e))}},fS=class extends Cn{async _call(e){return new je(await super._call(e))}},mS=class extends Cn{async _call(e){return new _t(await super._call(e))}},Uc=class extends I{},_S=class extends Uc{},gS=class extends Uc{async _call(e){return new Yf(await super._call(e))}},Yf=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},zc=class extends I{},wS=class extends zc{},yS=class extends zc{},PU=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"]]),RU=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),OU=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),LU=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),vS=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),bS=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),MS=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),xS=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"]]),TS=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"]]),ES=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),kS=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_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),FU=new Map([["multi_modality","MultiModalityCausalLM"]]),CS=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"]]),AS=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"]]),SS=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),IS=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"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),PS=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),NU=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),RS=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"]]),OS=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),LS=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),rs=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),FS=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),NS=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),DS=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),BS=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),US=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),zS=new Map([["wavlm","WavLMForXVector"]]),$S=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),VS=new Map([["vitmatte","VitMatteForImageMatting"]]),DU=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),GS=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),jS=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),qS=new Map([["sapiens","SapiensForNormalEstimation"]]),WS=new Map([["vitpose","VitPoseForPoseEstimation"]]),HS=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),KS=[[PU,J.EncoderOnly],[RU,J.EncoderDecoder],[LU,J.DecoderOnlyWithoutHead],[OU,J.AutoEncoder],[xS,J.EncoderOnly],[TS,J.EncoderOnly],[ES,J.Seq2Seq],[vS,J.Seq2Seq],[kS,J.DecoderOnly],[FU,J.MultiModality],[CS,J.EncoderOnly],[AS,J.EncoderOnly],[SS,J.Vision2Seq],[IS,J.ImageTextToText],[PS,J.AudioTextToText],[RS,J.EncoderOnly],[rs,J.EncoderOnly],[NS,J.EncoderOnly],[FS,J.EncoderOnly],[VS,J.EncoderOnly],[DU,J.EncoderOnly],[GS,J.EncoderOnly],[jS,J.EncoderOnly],[qS,J.EncoderOnly],[WS,J.EncoderOnly],[OS,J.EncoderOnly],[LS,J.EncoderOnly],[DS,J.MaskGeneration],[BS,J.EncoderOnly],[US,J.EncoderOnly],[bS,J.Seq2Seq],[MS,J.EncoderOnly],[zS,J.EncoderOnly],[$S,J.EncoderOnly],[HS,J.EncoderOnly]];for(let[e,t]of KS)for(let r of e.values()){mr.set(r,t);let n=Nh[r];os.set(n,r),Lh.set(r,n)}BU=[["MusicgenForConditionalGeneration",bf,J.Musicgen],["Phi3VForCausalLM",Ef,J.Phi3V],["CLIPTextModelWithProjection",Gh,J.EncoderOnly],["SiglipTextModel",Lf,J.EncoderOnly],["JinaCLIPTextModel",uf,J.EncoderOnly],["ClapTextModelWithProjection",$h,J.EncoderOnly],["ClapAudioModelWithProjection",Vh,J.EncoderOnly],["DacEncoderModel",Wh,J.EncoderOnly],["DacDecoderModel",Hh,J.EncoderOnly],["MimiEncoderModel",wf,J.EncoderOnly],["MimiDecoderModel",yf,J.EncoderOnly],["SnacEncoderModel",Ff,J.EncoderOnly],["SnacDecoderModel",Nf,J.EncoderOnly],["Gemma3nForConditionalGeneration",hl,J.ImageAudioTextToText],["SupertonicForConditionalGeneration",Uf,J.Supertonic],["ChatterboxModel",Bh,J.Chatterbox],["Qwen2VLForCausalLM",gl,J.MultimodalLanguageModelOnly],["Qwen2_5_VLForCausalLM",yl,J.MultimodalLanguageModelOnly],["Qwen3VLForCausalLM",vc,J.MultimodalLanguageModelOnly],["Qwen3VLMoeForCausalLM",kf,J.MultimodalLanguageModelOnly],["Qwen3_5ForCausalLM",Mc,J.MultimodalLanguageModelOnly],["Qwen3_5MoeForCausalLM",Cf,J.MultimodalLanguageModelOnly],["Gemma3nForCausalLM",nf,J.MultimodalLanguageModelOnly],["VoxtralRealtimeForConditionalGeneration",Kf,J.VoxtralRealtime]];for(let[e,t,r]of BU)mr.set(e,r),os.set(t,e),Lh.set(e,t);QS=new Map([["modnet",rs],["birefnet",rs],["isnet",rs],["ben",rs]]);for(let[e,t]of QS.entries())t.set(e,"PreTrainedModel"),mr.set(e,J.EncoderOnly),Lh.set(e,I);UU=new Set(QS.keys());mr.set("PreTrainedModel",J.EncoderOnly);os.set(I,"PreTrainedModel");Te={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:xS,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:TS,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:bS,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:MS,MODEL_FOR_MASKED_LM_MAPPING_NAMES:CS,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:AS,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:RS,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:rs,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:FS,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:NS,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:OS,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:LS,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:DS,MODEL_FOR_CTC_MAPPING_NAMES:BS,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:US,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:zS,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:$S,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:NU,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:VS,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:GS,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:jS,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:qS,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:WS,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:HS,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:IS,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:PS,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:ES,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:vS,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:kS,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:SS};gU(Te);Ee=(ni=class{static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:u=null,session_options:p={}}={}){let f={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:u,session_options:p};if(f.config=await ls.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:m}=f.config;for(let y of this.MODEL_CLASS_MAPPINGS){let v=y.get(m);if(!v){for(let x of y.values())if(x[0]===m){v=x;break}if(!v)continue}return await Nh[v].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return UU.has(m)||ce.warn(`Unknown model class "${m}", attempting to construct from base class.`),await I.from_pretrained(e,f);throw Error(`Unsupported model type: ${m}`)}},w(ni,"MODEL_CLASS_MAPPINGS",null),w(ni,"BASE_IF_FAIL",!1),ni),ns=(si=class extends Ee{},w(si,"MODEL_CLASS_MAPPINGS",KS.map(e=>e[0])),w(si,"BASE_IF_FAIL",!0),si),Bp=(Yd=class extends Ee{},w(Yd,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),Yd),JS=(Zd=class extends Ee{},w(Zd,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),Zd),li=(ep=class extends Ee{},w(ep,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),ep),XS=(tp=class extends Ee{},w(tp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),tp),YS=(rp=class extends Ee{},w(rp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),rp),ZS=(np=class extends Ee{},w(np,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),np),eI=(sp=class extends Ee{},w(sp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),sp),tI=(ap=class extends Ee{},w(ap,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),ap),rI=(op=class extends Ee{},w(op,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),op),nI=(ip=class extends Ee{},w(ip,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),ip),sI=(lp=class extends Ee{},w(lp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),lp),Up=(cp=class extends Ee{},w(cp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),cp),zp=(up=class extends Ee{},w(up,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),up),$p=(dp=class extends Ee{},w(dp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),dp),aI=(pp=class extends Ee{},w(pp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),pp),oI=(hp=class extends Ee{},w(hp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),hp),zU=(fp=class extends Ee{},w(fp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]),fp),iI=(mp=class extends Ee{},w(mp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_CTC_MAPPING_NAMES]),mp),lI=(_p=class extends Ee{},w(_p,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),_p),$U=(gp=class extends Ee{},w(gp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]),gp),VU=(wp=class extends Ee{},w(wp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]),wp),cI=(yp=class extends Ee{},w(yp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),yp),GU=(vp=class extends Ee{},w(vp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]),vp),uI=(bp=class extends Ee{},w(bp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),bp),dI=(Mp=class extends Ee{},w(Mp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),Mp),jU=(xp=class extends Ee{},w(xp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]),xp),qU=(Tp=class extends Ee{},w(Tp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]),Tp),pI=(Ep=class extends Ee{},w(Ep,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),Ep),WU=(kp=class extends Ee{},w(kp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]),kp),HU=(Cp=class extends Ee{},w(Cp,"MODEL_CLASS_MAPPINGS",[Te.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]),Cp);$e=class extends Dt{constructor({task:e,model:t,tokenizer:r=null,processor:n=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=n}async dispose(){await this.model.dispose()}},hI=class extends $e{async _call(e,{top_k:t=1}={}){let r=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(r),{problem_type:s,id2label:a}=this.model.config,o=s==="multi_label_classification"?l=>l.sigmoid():l=>new q("float32",rt(l.data),l.dims),i=[];for(let l of n.logits){let c=o(l),u=await pn(c,t),p=u[0].tolist(),m=u[1].tolist().map((y,v)=>({label:a?a[y]:`LABEL_${y}`,score:p[v]}));t===1?i.push(...m):i.push(m)}return Array.isArray(e)||t===1?i:i[0]}},fI=class extends $e{async _call(e,{ignore_labels:t=["O"]}={}){let r=Array.isArray(e),n=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,o=this.model.config.id2label,i=[];for(let l=0;l<a.dims[0];++l){let c=n.input_ids[l],u=a[l],p=[];for(let f=0;f<u.dims[0];++f){let m=u[f],y=Ge(m.data)[1],v=o?o[y]:`LABEL_${y}`;if(t.includes(v))continue;let x=this.tokenizer.decode([c[f].item()],{skip_special_tokens:!0});if(x==="")continue;let M=rt(m.data);p.push({entity:v,score:M[y],index:f,word:x})}i.push(p)}return r?i:i[0]}},mI=class extends $e{async _call(e,t,{top_k:r=1}={}){let n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),s=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(n),i=n.input_ids.tolist(),l=n.attention_mask.tolist(),{all_special_ids:c,sep_token_id:u}=this.tokenizer,p=[];for(let f=0;f<a.dims[0];++f){let m=i[f],y=m.findIndex(S=>S==u),v=a[f].tolist(),x=o[f].tolist();for(let S=1;S<v.length;++S)(l[f]==0||S<=y||c.findIndex(O=>O==m[S])!==-1)&&(v[S]=-1/0,x[S]=-1/0);let M=rt(v).map((S,O)=>[S,O]),T=rt(x).map((S,O)=>[S,O]);M[0][0]=0,T[0][0]=0;let A=gL(M,T).filter(S=>S[0][1]<=S[1][1]).map(S=>[S[0][1],S[1][1],S[0][0]*S[1][0]]).sort((S,O)=>O[2]-S[2]),C=[];for(let S=0;S<Math.min(A.length,r);++S){let[O,E,K]=A[S],$=m.slice(O,E+1),V=this.tokenizer.decode($,{skip_special_tokens:!0});C.push({answer:V,score:K})}r===1?p.push(...C):p.push(C)}return s?p:p[0]}},_I=class extends $e{async _call(e,{top_k:t=5}={}){let{mask_token_id:r,mask_token:n}=this.tokenizer,s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(s),o=[],i=s.input_ids.tolist();for(let l=0;l<i.length;++l){let c=i[l],u=c.findIndex(v=>v==r);if(u===-1)throw Error(`Mask token (${n}) not found in text.`);let p=a[l][u],f=await pn(new q("float32",rt(p.data),p.dims),t),m=f[0].tolist(),y=f[1].tolist();o.push(y.map((v,x)=>{let M=c.slice();return M[u]=v,{score:m[x],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},$c=class extends $e{constructor(){super(...arguments);w(this,"_key","generated_text")}async _call(t,r={}){Array.isArray(t)||(t=[t]),this.model.config.prefix&&(t=t.map(l=>this.model.config.prefix+l));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(t=t.map(l=>n[this.task].prefix+l));let s=this.tokenizer,a={padding:!0,truncation:!0},o;this.task==="translation"&&"_build_translation_inputs"in s?o=s._build_translation_inputs(t,a,r):o=s(t,a);let i=await this.model.generate({...o,...r});return s.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}},gI=class extends $c{constructor(){super(...arguments);w(this,"_key","summary_text")}},wI=class extends $c{constructor(){super(...arguments);w(this,"_key","translation_text")}};yI=class extends $e{async _call(e,t={}){let r=!1,n=!1,s=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=t.tokenizer_encode_kwargs,o;if(typeof e=="string")o=e=[e];else if(Array.isArray(e)&&e.every(m=>typeof m=="string"))r=!0,o=e;else{if(fv(e))e=[e];else if(Array.isArray(e)&&e.every(fv))r=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,o=e.map(m=>this.tokenizer.apply_chat_template(m,{tokenize:!1,add_generation_prompt:!0,...a})),s=!1,a=void 0}let i=n?!1:t.return_full_text??!0;this.tokenizer.padding_side="left";let l=this.tokenizer(o,{add_special_tokens:s,padding:!0,truncation:!0,...a}),c=await this.model.generate({...l,...t}),u=this.tokenizer.batch_decode(c,{skip_special_tokens:!0}),p;!i&&l.input_ids.dims.at(-1)>0&&(p=this.tokenizer.batch_decode(l.input_ids,{skip_special_tokens:!0}).map(m=>m.length));let f=Array.from({length:e.length},m=>[]);for(let m=0;m<u.length;++m){let y=Math.floor(m/c.dims[0]*e.length);p&&(u[m]=u[m].slice(p[y])),f[y].push({generated_text:n?[...e[y],{role:"assistant",content:u[m]}]:u[m]})}return!r&&f.length===1?f[0]:f}},vI=class extends $e{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ce.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&&(ce.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:n=!1}={}){let s=Array.isArray(e);s||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(l=>r.replace("{}",l)),o=n||t.length===1,i=[];for(let l of e){let c=[];for(let f of a){let m=this.tokenizer(l,{text_pair:f,padding:!0,truncation:!0}),y=await this.model(m);o?c.push([y.logits.data[this.contradiction_id],y.logits.data[this.entailment_id]]):c.push(y.logits.data[this.entailment_id])}let p=(o?c.map(f=>rt(f)[1]):rt(c)).map((f,m)=>[f,m]).sort((f,m)=>m[0]-f[0]);i.push({sequence:l,labels:p.map(f=>t[f[1]]),scores:p.map(f=>f[0])})}return s?i:i[0]}},bI=class extends $e{async _call(e,{top_k:t=5}={}){let r=this.processor.feature_extractor.config.sampling_rate,n=await fa(e,r),s=this.model.config.id2label,a=[];for(let o of n){let i=await this.processor(o),c=(await this.model(i)).logits[0],u=await pn(new q("float32",rt(c.data),c.dims),t),p=u[0].tolist(),m=u[1].tolist().map((y,v)=>({label:s?s[y]:`LABEL_${y}`,score:p[v]}));a.push(m)}return Array.isArray(e)?a:a[0]}},MI=class extends $e{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let s=t.map(c=>r.replace("{}",c)),a=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await fa(e,o),l=[];for(let c of i){let u=await this.processor(c),p=await this.model({...a,...u}),f=rt(p.logits_per_audio.data);l.push([...f].map((m,y)=>({score:m,label:t[y]})))}return n?l[0]:l}},xI=class extends $e{async _call(e,t={}){switch(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);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&ce.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&ce.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await fa(n,s),o=[];for(let i of a){let l=await this.processor(i),u=(await this.model(l)).logits[0],p=[];for(let m of u)p.push(Ge(m.data)[1]);let f=this.tokenizer.decode(p,{skip_special_tokens:!0}).trim();o.push({text:f})}return r?o[0]:o}async _call_whisper(e,t){let r=t.return_timestamps??!1,n=t.chunk_length_s??0,s=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};r==="word"&&(o.return_token_timestamps=!0,o.return_timestamps=!1);let i=!Array.isArray(e),l=i?[e]:e,c=this.processor.feature_extractor.config,u=c.chunk_length/this.model.config.max_source_positions,p=c.hop_length,f=c.sampling_rate,m=await fa(l,f),y=[];for(let v of m){let x=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let A=f*n,C=f*a,S=A-2*C,O=0;for(;;){let E=O+A,K=v.subarray(O,E),$=await this.processor(K),V=O===0,Q=E>=v.length;if(x.push({stride:[K.length,V?0:C,Q?0:C],input_features:$.input_features,is_last:Q}),Q)break;O+=S}}else x=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(let A of x){o.num_frames=Math.floor(A.stride[0]/p);let C=await this.model.generate({inputs:A.input_features,...o});r==="word"?(A.tokens=C.sequences.tolist()[0],A.token_timestamps=C.token_timestamps.tolist()[0].map(S=>da(S,2))):A.tokens=C[0].tolist(),A.stride=A.stride.map(S=>S/f)}let[M,T]=this.tokenizer._decode_asr(x,{time_precision:u,return_timestamps:r,force_full_sequences:s});y.push({text:M,...T})}return i?y[0]:y}async _call_moonshine(e,t){let r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await fa(n,s),o=[];for(let i of a){let l=await this.processor(i),c=Math.floor(i.length/s)*6,u=await this.model.generate({max_new_tokens:c,...t,...l}),p=this.processor.batch_decode(u,{skip_special_tokens:!0})[0];o.push({text:p})}return r?o[0]:o}},TI=class extends $e{constructor(t){super(t);w(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=t.vocoder??null}async _prepare_speaker_embeddings(t,r){if((typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await ge.fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new q("float32",t,[t.length]);else if(!(t instanceof q))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(t.dims[0]===1)t=t.repeat(r,1);else if(t.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${t.dims[0]}.`)}return t}_postprocess_waveform(t,r,n,s=null){let a=r.data,[o,i]=r.dims,l=s?s.data:null,c=[];for(let u=0;u<o;++u){let p=l?Math.min(Math.ceil(l[u]),i):i,f=u*i;c.push(new Xb(a.slice(f,f+p),n))}return Array.isArray(t)?c:c[0]}async _call(t,r){return this.processor?this._call_text_to_spectrogram(t,r):this.model.config.model_type==="supertonic"?this._call_supertonic(t,r):this._call_text_to_waveform(t)}async _call_supertonic(t,{speaker_embeddings:r,num_inference_steps:n,speed:s}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:a,style_dim:o}=this.model.config,i=this.tokenizer(t,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,o);let{waveform:c,durations:u}=await this.model.generate_speech({...i,style:r,num_inference_steps:n,speed:s});return this._postprocess_waveform(t,c,a,u)}async _call_text_to_waveform(t){let r=this.tokenizer(t,{padding:!0,truncation:!0}),{waveform:n}=await this.model(r),s=this.model.config.sampling_rate;return this._postprocess_waveform(t,n,s)}async _call_text_to_spectrogram(t,{speaker_embeddings:r}){this.vocoder||(ce.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await ns.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:n}=this.tokenizer(t,{padding:!0,truncation:!0}),s=n.dims[0];r=await this._prepare_speaker_embeddings(r,s),r=r.view(s,-1);let{waveform:a}=await this.model.generate_speech(n,r,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(t,a,o)}},EI=class extends $e{async _call(e,t={}){let r=Array.isArray(e),n=await Xt(e),{pixel_values:s}=await this.processor(n),a=[];for(let o of s){o.dims=[1,...o.dims];let i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(l)}return r?a:a[0]}},kI=class extends $e{async _call(e,{top_k:t=5}={}){let r=await Xt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),{id2label:a}=this.model.config,o=[];for(let i of s.logits){let l=await pn(new q("float32",rt(i.data),i.dims),t),c=l[0].tolist(),p=l[1].tolist().map((f,m)=>({label:a?a[f]:`LABEL_${f}`,score:c[m]}));o.push(p)}return Array.isArray(e)?o:o[0]}},mv={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Zf=class extends $e{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:s=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let l=await Xt(e),c=l.map(M=>[M.height,M.width]),u=await this.processor(l),{inputNames:p,outputNames:f}=this.model.sessions.model;if(!p.includes("pixel_values")){if(p.length!==1)throw Error(`Expected a single input name, but got ${p.length} inputs: ${p}.`);let M=p[0];if(M in u)throw Error(`Input name ${M} already exists in the inputs.`);u[M]=u.pixel_values}let m=await this.model(u),y=null;if(o!==null)y=mv[o];else if(this.processor.image_processor){for(let[M,T]of Object.entries(mv))if(T in this.processor.image_processor){y=this.processor.image_processor[T].bind(this.processor.image_processor),o=M;break}}let v=this.model.config.id2label,x=[];if(o)if(o==="panoptic"||o==="instance"){let M=y(m,t,r,n,s,a??c)[0],T=M.segmentation;for(let A of M.segments_info){let C=new Uint8ClampedArray(T.data.length);for(let O=0;O<T.data.length;++O)T.data[O]===A.id&&(C[O]=255);let S=new Mt(C,T.dims[1],T.dims[0],1);x.push({score:A.score,label:v[A.label_id],mask:S})}}else if(o==="semantic"){let{segmentation:M,labels:T}=y(m,a??c)[0];for(let A of T){let C=new Uint8ClampedArray(M.data.length);for(let O=0;O<M.data.length;++O)M.data[O]===A&&(C[O]=255);let S=new Mt(C,M.dims[1],M.dims[0],1);x.push({score:null,label:v[A],mask:S})}}else throw Error(`Subtask ${o} not supported.`);else{let T=m[f[0]];for(let A=0;A<c.length;++A){let C=c[A],S=T[A];S.data.some(E=>E<-1e-5||E>1+1e-5)&&S.sigmoid_();let O=await Mt.fromTensor(S.mul_(255).to("uint8")).resize(C[1],C[0]);x.push({label:null,score:null,mask:O})}}return x}},CI=class extends Zf{async _call(e,t={}){let r=await Xt(e),n=await super._call(e,t),s=r.map((a,o)=>{let i=a.clone();return i.putAlpha(n[o].mask),i});return Array.isArray(e)?s:s[0]}},AI=class extends $e{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){let n=Array.isArray(e),s=await Xt(e),a=t.map(p=>r.replace("{}",p)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(s),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?p=>p.sigmoid().data:p=>rt(p.data),u=[];for(let p of l.logits_per_image){let m=[...c(p)].map((y,v)=>({score:y,label:t[v]}));m.sort((y,v)=>v.score-y.score),u.push(m)}return n?u:u[0]}},SI=class extends $e{async _call(e,{threshold:t=.9,percentage:r=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let s=await Xt(e),a=r?null:s.map(f=>[f.height,f.width]),{pixel_values:o,pixel_mask:i}=await this.processor(s),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:u}=this.model.config,p=c.map(f=>f.boxes.map((m,y)=>({score:f.scores[y],label:u[f.classes[y]],box:Vp(m,!r)})));return n?p:p[0]}},II=class extends $e{async _call(e,t,{threshold:r=.1,top_k:n=null,percentage:s=!1}={}){let a=Array.isArray(e),o=await Xt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let u=0;u<o.length;++u){let p=o[u],f=s?null:[[p.height,p.width]],m=l.pixel_values[u].unsqueeze_(0),y=await this.model({...i,pixel_values:m}),v;if("post_process_grounded_object_detection"in this.processor){let x=this.processor.post_process_grounded_object_detection(y,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:f})[0];v=x.boxes.map((M,T)=>({score:x.scores[T],label:x.labels[T],box:Vp(M,!s)}))}else{let x=this.processor.image_processor.post_process_object_detection(y,r,f,!0)[0];v=x.boxes.map((M,T)=>({score:x.scores[T],label:t[x.classes[T]],box:Vp(M,!s)}))}v.sort((x,M)=>M.score-x.score),n!==null&&(v=v.slice(0,n)),c.push(v)}return a?c:c[0]}},PI=class extends $e{async _call(e,t,r={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await Xt(e))[0],{pixel_values:s}=await this.processor(n),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,i=await this.model.generate({inputs:s,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...r}),c=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/),u=null;return c&&c.length>=2&&(u=c[1].trim()),[{answer:u}]}},RI=class extends $e{async _call(e){let t=await Xt(e),r=await this.processor(t),n=await this.model(r),s=[];for(let a of n.reconstruction){let o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(Mt.fromTensor(o))}return Array.isArray(e)?s:s[0]}},OI=class extends $e{async _call(e){let t=await Xt(e),r=await this.processor(t),{predicted_depth:n}=await this.model(r),s=[];for(let a=0;a<t.length;++a){let o=n[a],[i,l]=o.dims.slice(-2),[c,u]=t[a].size,p=(await Nt(o.view(1,1,i,l),{size:[u,c],mode:"bilinear"})).view(u,c),f=p.min().item(),m=p.max().item(),y=p.sub(f).div_(m-f).mul_(255).to("uint8").unsqueeze(0),v=Mt.fromTensor(y);s.push({predicted_depth:p,depth:v})}return Array.isArray(e)?s:s[0]}},LI=class extends $e{async _call(e,{pooling:t="none",normalize:r=!1,quantize:n=!1,precision:s="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a),i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=Xv(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),n&&(i=Zv(i,s)),i}},FI=class extends $e{async _call(e,{pool:t=null}={}){let r=await Xt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),a;if(t){if(!("pooler_output"in s))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=s.pooler_output}else a=s.last_hidden_state??s.logits??s.image_embeds;return a}},bi=Object.freeze({"text-classification":{pipeline:hI,model:Bp,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:fI,model:JS,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:mI,model:rI,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:_I,model:tI,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:gI,model:li,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:wI,model:li,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:$c,model:li,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:yI,model:eI,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:vI,model:Bp,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:bI,model:lI,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:MI,model:ns,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:xI,model:[XS,iI],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:TI,model:[ZS,YS],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:EI,model:nI,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:kI,model:sI,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Zf,model:[Up,zp,$p],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:CI,model:[Up,zp,$p],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:AI,model:ns,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:SI,model:aI,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:II,model:oI,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:PI,model:cI,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:RI,model:uI,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:OI,model:dI,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:LI,model:ns,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:FI,model:[pI,ns],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),NI=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});JU=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,UI=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},_v=pe.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),zI=class extends UI{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,skip_special_tokens:s=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??_v,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:s,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let i=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(i,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=jt(this.token_cache,r);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),s;t||n.endsWith(`
26
+ `)?(s=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&JU(n.charCodeAt(n.length-1))?(s=n.slice(this.print_len),this.print_len+=s.length):(s=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=s.length),this.on_finalized_text(s,!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===_v&&pe.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
27
+ `)}},XU=class extends zI{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,on_chunk_start:s=null,on_chunk_end:a=null,on_finalize:o=null,time_precision:i=.02,skip_special_tokens:l=!0,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,skip_special_tokens:l,callback_function:r,token_callback_function:n,decode_kwargs:c}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=s,this.on_chunk_end=a,this.on_finalize=o,this.time_precision=i,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let t=e[0];if(t.length===1){let r=Number(t[0])-this.timestamp_begin;if(r>=0){let n=r*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(t);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}},em=class{constructor(e,t){this.image=e,this.timestamp=t}},$I=class{constructor(e,t){e.length>0&&e[0]instanceof Mt&&(e=e.map((r,n)=>new em(r,(n+1)/(e.length+1)*t))),this.frames=e,this.duration=t}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};az=class{static async get_files(e,t={}){return Va(e,t)}static async get_pipeline_files(e,t,r={}){return Ga(e,t,r)}static async get_model_files(e,t={}){return DI(e,t)}static async get_tokenizer_files(e){return sh(e)}static async get_processor_files(e){return BI(e)}static async is_cached(e,t={}){return ZU(e,t)}static async is_cached_files(e,t={}){return ez(e,t)}static async is_pipeline_cached(e,t,r={}){return tz(e,t,r)}static async is_pipeline_cached_files(e,t,r={}){return rz(e,t,r)}static async get_file_metadata(e,t,r={}){return Ma(e,t,r)}static async clear_cache(e,t={}){return nz(e,t)}static async clear_pipeline_cache(e,t,r={}){return sz(e,t,r)}}});var Fz={};Au(Fz,{ArtifactsClient:()=>xo,AudioTranscriptions:()=>Fn,AuthType:()=>Is,CapabilitiesClient:()=>Dn,ChatClient:()=>Bn,CompatibilityLevel:()=>Zc,ContractModelStatus:()=>Jc,ControlClient:()=>Un,DeviceAuth:()=>Mo,DeviceClass:()=>Xc,DeviceContext:()=>Gr,DevicesClient:()=>yo,ERROR_CODE_MAP:()=>dt,EVENT_REQUIRED_ATTRIBUTES:()=>Nu,EngineRegistry:()=>ja,ErrorCode:()=>Vr,ExperimentsClient:()=>Qc,FederatedAnalyticsClient:()=>Wc,FederatedClient:()=>jc,FinishReason:()=>Yc,GradientCache:()=>Kc,InferenceEngine:()=>zn,ModelManager:()=>$n,ModelsClient:()=>Vn,MonitoringClient:()=>_o,OTLP_RESOURCE_ATTRIBUTES:()=>Ds,OctomilAudio:()=>Nn,OctomilClient:()=>mo,OctomilError:()=>U,OctomilText:()=>qn,PrincipalType:()=>Ps,ResponsesClient:()=>Gn,RoutingClient:()=>jn,Scope:()=>Rs,SecAggPlus:()=>Hc,SecureAggregation:()=>Wa,SettingsClient:()=>go,StreamingInferenceEngine:()=>Gc,SyncManager:()=>bo,TELEMETRY_EVENTS:()=>fr,TelemetryReporter:()=>Hr,TextPredictionsClient:()=>Us,ToolRunner:()=>To,TrainingClient:()=>wo,WeightExtractor:()=>qa,addGaussianNoise:()=>XI,assertModelIntegrity:()=>Eg,benchmarkResultOk:()=>Lz,clipGradients:()=>JI,closeTelemetry:()=>Tg,computeHash:()=>zs,configure:()=>mg,createModelCache:()=>lo,createTransformersJsLocalResponsesRuntime:()=>HI,dequantize:()=>ZI,detectDeviceCapabilities:()=>ho,embed:()=>po,generateResponseId:()=>qr,getDeviceContext:()=>Ns,getInstallId:()=>fo,getPublishableKeyEnvironment:()=>hg,getTelemetry:()=>xg,initTelemetry:()=>Mg,messagesToResponseInput:()=>co,quantize:()=>YI,resetInstallIdCache:()=>bg,shamirReconstruct:()=>sm,shamirSplit:()=>nm,validatePublishableKey:()=>uo,verifyModelIntegrity:()=>Uu});var Is=(s=>(s.OrgApiKey="org_api_key",s.DeviceToken="device_token",s.ServiceToken="service_token",s.PublishableKey="publishable_key",s))(Is||{});var Ps=(s=>(s.User="user",s.OrgApiClient="org_api_client",s.Device="device",s.ServiceWorker="service_worker",s))(Ps||{});var Rs=(m=>(m.CatalogRead="catalog:read",m.ModelsRead="models:read",m.ModelsWrite="models:write",m.DevicesRegister="devices:register",m.DevicesHeartbeat="devices:heartbeat",m.ControlRefresh="control:refresh",m.TelemetryWrite="telemetry:write",m.RolloutsRead="rollouts:read",m.RolloutsWrite="rollouts:write",m.BenchmarksWrite="benchmarks:write",m.EvalsWrite="evals:write",m.CloudInference="cloud:inference",m.CloudCredentials="cloud:credentials",m))(Rs||{});var Vr=(H=>(H.InvalidApiKey="invalid_api_key",H.AuthenticationFailed="authentication_failed",H.Forbidden="forbidden",H.DeviceNotRegistered="device_not_registered",H.TokenExpired="token_expired",H.DeviceRevoked="device_revoked",H.NetworkUnavailable="network_unavailable",H.RequestTimeout="request_timeout",H.ServerError="server_error",H.RateLimited="rate_limited",H.InvalidInput="invalid_input",H.UnsupportedModality="unsupported_modality",H.ContextTooLarge="context_too_large",H.ModelNotFound="model_not_found",H.ModelDisabled="model_disabled",H.VersionNotFound="version_not_found",H.DownloadFailed="download_failed",H.ChecksumMismatch="checksum_mismatch",H.InsufficientStorage="insufficient_storage",H.InsufficientMemory="insufficient_memory",H.RuntimeUnavailable="runtime_unavailable",H.AcceleratorUnavailable="accelerator_unavailable",H.ModelLoadFailed="model_load_failed",H.InferenceFailed="inference_failed",H.StreamInterrupted="stream_interrupted",H.PolicyDenied="policy_denied",H.CloudFallbackDisallowed="cloud_fallback_disallowed",H.CloudCredentialsMissing="cloud_credentials_missing",H.CloudCredentialsRevoked="cloud_credentials_revoked",H.CloudProviderAuthFailed="cloud_provider_auth_failed",H.MaxToolRoundsExceeded="max_tool_rounds_exceeded",H.TrainingFailed="training_failed",H.TrainingNotSupported="training_not_supported",H.WeightUploadFailed="weight_upload_failed",H.ControlSyncFailed="control_sync_failed",H.AssignmentNotFound="assignment_not_found",H.Cancelled="cancelled",H.AppBackgrounded="app_backgrounded",H.Unknown="unknown",H))(Vr||{}),Ln={invalid_api_key:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},authentication_failed:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"reauthenticate"},forbidden:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_permissions"},device_not_registered:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"register_device"},token_expired:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"reauthenticate"},device_revoked:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"register_device"},network_unavailable:{category:"network",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},request_timeout:{category:"network",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},server_error:{category:"network",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry"},rate_limited:{category:"network",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"retry_after"},invalid_input:{category:"input",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},unsupported_modality:{category:"input",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},context_too_large:{category:"input",retryClass:"never",fallbackEligible:!0,suggestedAction:"reduce_input_or_fallback"},model_not_found:{category:"catalog",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_model_id"},model_disabled:{category:"catalog",retryClass:"never",fallbackEligible:!0,suggestedAction:"use_alternate_model"},version_not_found:{category:"catalog",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_version"},download_failed:{category:"download",retryClass:"backoff_safe",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},checksum_mismatch:{category:"download",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"redownload"},insufficient_storage:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"free_storage_or_fallback"},insufficient_memory:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_smaller_model"},runtime_unavailable:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_alternate_runtime"},accelerator_unavailable:{category:"device",retryClass:"never",fallbackEligible:!0,suggestedAction:"try_cpu_or_fallback"},model_load_failed:{category:"runtime",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},inference_failed:{category:"runtime",retryClass:"conditional",fallbackEligible:!0,suggestedAction:"retry_or_fallback"},stream_interrupted:{category:"runtime",retryClass:"immediate_safe",fallbackEligible:!0,suggestedAction:"retry"},policy_denied:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_policy"},cloud_fallback_disallowed:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"change_policy_or_fix_local"},cloud_credentials_missing:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},cloud_credentials_revoked:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},cloud_provider_auth_failed:{category:"auth",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_credentials"},max_tool_rounds_exceeded:{category:"policy",retryClass:"never",fallbackEligible:!1,suggestedAction:"increase_limit_or_simplify"},training_failed:{category:"training",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"retry"},training_not_supported:{category:"training",retryClass:"never",fallbackEligible:!1,suggestedAction:"fix_request"},weight_upload_failed:{category:"training",retryClass:"backoff_safe",fallbackEligible:!1,suggestedAction:"retry"},control_sync_failed:{category:"control",retryClass:"backoff_safe",fallbackEligible:!1,suggestedAction:"retry"},assignment_not_found:{category:"control",retryClass:"never",fallbackEligible:!1,suggestedAction:"check_assignment"},cancelled:{category:"lifecycle",retryClass:"never",fallbackEligible:!1,suggestedAction:"none"},app_backgrounded:{category:"lifecycle",retryClass:"conditional",fallbackEligible:!1,suggestedAction:"resume_on_foreground"},unknown:{category:"unknown",retryClass:"never",fallbackEligible:!1,suggestedAction:"report_bug"}};var dt={network_unavailable:"NETWORK_UNAVAILABLE",request_timeout:"REQUEST_TIMEOUT",server_error:"SERVER_ERROR",invalid_api_key:"INVALID_API_KEY",authentication_failed:"AUTHENTICATION_FAILED",forbidden:"FORBIDDEN",model_not_found:"MODEL_NOT_FOUND",model_disabled:"MODEL_DISABLED",download_failed:"DOWNLOAD_FAILED",checksum_mismatch:"CHECKSUM_MISMATCH",insufficient_storage:"INSUFFICIENT_STORAGE",runtime_unavailable:"RUNTIME_UNAVAILABLE",model_load_failed:"MODEL_LOAD_FAILED",inference_failed:"INFERENCE_FAILED",insufficient_memory:"INSUFFICIENT_MEMORY",rate_limited:"RATE_LIMITED",invalid_input:"INVALID_INPUT",cancelled:"CANCELLED",unknown:"UNKNOWN",device_not_registered:"DEVICE_NOT_REGISTERED",unsupported_modality:"UNSUPPORTED_MODALITY",context_too_large:"CONTEXT_TOO_LARGE",version_not_found:"VERSION_NOT_FOUND",accelerator_unavailable:"ACCELERATOR_UNAVAILABLE",stream_interrupted:"STREAM_INTERRUPTED",policy_denied:"POLICY_DENIED",cloud_fallback_disallowed:"CLOUD_FALLBACK_DISALLOWED",cloud_credentials_missing:"CLOUD_CREDENTIALS_MISSING",cloud_credentials_revoked:"CLOUD_CREDENTIALS_REVOKED",cloud_provider_auth_failed:"CLOUD_PROVIDER_AUTH_FAILED",max_tool_rounds_exceeded:"MAX_TOOL_ROUNDS_EXCEEDED",control_sync_failed:"CONTROL_SYNC_FAILED",assignment_not_found:"ASSIGNMENT_NOT_FOUND",app_backgrounded:"APP_BACKGROUNDED",training_failed:"TRAINING_FAILED",training_not_supported:"TRAINING_NOT_SUPPORTED",weight_upload_failed:"WEIGHT_UPLOAD_FAILED",token_expired:"TOKEN_EXPIRED",device_revoked:"DEVICE_REVOKED"},Os=Object.fromEntries(Object.entries(dt).map(([e,t])=>[t,e])),U=class e extends Error{constructor(r,n,s){super(n);w(this,"code");w(this,"cause");this.name="OctomilError",this.code=r,this.cause=s}get retryable(){let r=Os[this.code];return r!=null&&Ln[r].retryClass!=="never"}get category(){let r=Os[this.code];return r!=null?Ln[r].category:void 0}get retryClass(){let r=Os[this.code];return r!=null?Ln[r].retryClass:void 0}get fallbackEligible(){let r=Os[this.code];return r!=null?Ln[r].fallbackEligible:!1}get suggestedAction(){let r=Os[this.code];return r!=null?Ln[r].suggestedAction:void 0}static fromErrorCode(r,n,s){let a=dt[r];return new e(a,n,s)}static fromHttpStatus(r,n){let s=n||`HTTP ${r}`;switch(r){case 400:return new e(dt.invalid_input,s);case 401:return new e(dt.authentication_failed,s);case 403:return new e(dt.forbidden,s);case 404:return new e(dt.model_not_found,s);case 429:return new e(dt.rate_limited,s);case 500:case 502:case 503:case 504:return new e(dt.server_error,s);default:return r>=500?new e(dt.server_error,s):new e(dt.unknown,s)}}static fromServerResponse(r,n){let s=(typeof n?.message=="string"?n.message:null)??(typeof n?.error=="string"?n.error:null)??`HTTP ${r}`;if(typeof n?.code=="string"&&Object.values(Vr).includes(n.code)){let o=dt[n.code];return new e(o,s)}return e.fromHttpStatus(r,s)}};var Fn=class{constructor(t,r){w(this,"serverUrl");w(this,"apiKey");this.serverUrl=t.replace(/\/+$/,""),this.apiKey=r}async create(t){let r=new FormData;if(r.append("file",t.file),t.model&&r.append("model",t.model),t.language&&r.append("language",t.language),t.responseFormat&&r.append("response_format",t.responseFormat),t.timestampGranularities)for(let u of t.timestampGranularities)r.append("timestamp_granularities[]",u);let n=`${this.serverUrl}/v1/audio/transcriptions`,s;try{s=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:r})}catch(u){throw new U("NETWORK_UNAVAILABLE",`audio.transcriptions.create request failed: ${String(u)}`,u)}if(!s.ok)throw U.fromHttpStatus(s.status,`audio.transcriptions.create failed: HTTP ${s.status}`);let a=await s.json(),o=typeof a.text=="string"?a.text:"",i=typeof a.language=="string"?a.language:void 0,l=typeof a.duration_ms=="number"?a.duration_ms:void 0,c=[];return Array.isArray(a.segments)&&(c=a.segments.map(u=>({text:typeof u.text=="string"?u.text:"",startMs:typeof u.start_ms=="number"?u.start_ms:0,endMs:typeof u.end_ms=="number"?u.end_ms:0,confidence:typeof u.confidence=="number"?u.confidence:void 0}))),{text:o,language:i,durationMs:l,segments:c}}};var Nn=class{constructor(t,r){w(this,"transcriptions");this.transcriptions=new Fn(t,r)}};var Dn=class{async current(){let r=(typeof navigator<"u"&&navigator.deviceMemory||0)*1024,n;r>=16384?n="flagship":r>=8192?n="high":r>=4096?n="mid":n="low";let s=["wasm"],a=typeof navigator<"u"&&"gpu"in navigator;a&&s.push("webgpu");let o=0;try{if(typeof navigator<"u"&&navigator.storage&&navigator.storage.estimate){let l=await navigator.storage.estimate();o=Math.round((l.quota||0)/(1024*1024))}}catch{}let i=[];return a&&i.push("webgpu"),{deviceClass:n,availableRuntimes:s,memoryMb:r,storageMb:o,platform:"browser",accelerators:i}}};var cO="octomil-models-v1",uO="octomil-models",oo="blobs",dO=1,Su=class{async open(){return caches.open(cO)}async get(t){let n=await(await this.open()).match(t);return n?n.arrayBuffer():null}async put(t,r){let n=await this.open(),s=new Response(r,{headers:{"x-octomil-cached-at":new Date().toISOString(),"x-octomil-size":String(r.byteLength)}});await n.put(t,s)}async has(t){return await(await this.open()).match(t)!==void 0}async remove(t){await(await this.open()).delete(t)}async info(t){let n=await(await this.open()).match(t);if(!n)return{cached:!1,sizeBytes:0};let s=n.headers.get("x-octomil-size"),a=n.headers.get("x-octomil-cached-at");return{cached:!0,sizeBytes:s?parseInt(s,10):0,cachedAt:a??void 0}}},io=class{constructor(){w(this,"dbPromise",null)}openDB(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,r)=>{let n=indexedDB.open(uO,dO);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(oo)||s.createObjectStore(oo,{keyPath:"key"})},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error)}),this.dbPromise)}async tx(t){return(await this.openDB()).transaction(oo,t).objectStore(oo)}async get(t){let r=await this.tx("readonly");return new Promise((n,s)=>{let a=r.get(t);a.onsuccess=()=>{let o=a.result;n(o?.data??null)},a.onerror=()=>s(a.error)})}async put(t,r){let n=await this.tx("readwrite"),s={key:t,data:r,sizeBytes:r.byteLength,cachedAt:new Date().toISOString()};return new Promise((a,o)=>{let i=n.put(s);i.onsuccess=()=>a(),i.onerror=()=>o(i.error)})}async has(t){let r=await this.tx("readonly");return new Promise((n,s)=>{let a=r.count(t);a.onsuccess=()=>n(a.result>0),a.onerror=()=>s(a.error)})}async remove(t){let r=await this.tx("readwrite");return new Promise((n,s)=>{let a=r.delete(t);a.onsuccess=()=>n(),a.onerror=()=>s(a.error)})}async info(t){let r=await this.tx("readonly");return new Promise((n,s)=>{let a=r.get(t);a.onsuccess=()=>{let o=a.result;n(o?{cached:!0,sizeBytes:o.sizeBytes,cachedAt:o.cachedAt}:{cached:!1,sizeBytes:0})},a.onerror=()=>s(a.error)})}},Ls=class{async get(t){return null}async put(t,r){}async has(t){return!1}async remove(t){}async info(t){return{cached:!1,sizeBytes:0}}};function lo(e){if(e==="none")return new Ls;if(e==="cache-api")return typeof caches<"u"?new Su:typeof indexedDB<"u"?new io:new Ls;if(e==="indexeddb")return typeof indexedDB<"u"?new io:new Ls;throw new U("INVALID_INPUT",`Unknown cache strategy: ${e}`)}var Pt=class{constructor(t={}){w(this,"serverUrl");w(this,"apiKey");w(this,"orgId");this.serverUrl=(t.serverUrl??"https://api.octomil.com").replace(/\/+$/,""),this.apiKey=t.apiKey,this.orgId=t.orgId}buildUrl(t,r){let n=new URL(t,`${this.serverUrl}/`);for(let[s,a]of Object.entries(r??{}))a==null||a===""||n.searchParams.set(s,String(a));return n.toString()}async requestJson(t,r={},n){let s=await this.request(t,r,n);if(s.status!==204)return await s.json()}async requestVoid(t,r={},n){await this.request(t,r,n)}async request(t,r={},n){let s=new Headers(r.headers);!s.has("Content-Type")&&r.body!==void 0&&s.set("Content-Type","application/json"),this.apiKey&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${this.apiKey}`);let a;try{a=await fetch(this.buildUrl(t,n),{...r,headers:s})}catch(o){throw new U("NETWORK_UNAVAILABLE",`Request failed: ${String(o)}`,o)}if(!a.ok){let o=await a.text().catch(()=>"");throw new U("NETWORK_UNAVAILABLE",`Request failed: HTTP ${a.status}${o?` ${o}`:""}`)}return a}};var Iu=class extends Pt{constructor(t,r){super({serverUrl:t,apiKey:r})}async requestJson(t,r={},n){return super.requestJson(t,r,n)}},Pu=class{constructor(t){this.api=t}async create(t){return this.api.requestJson("/api/v1/chat/threads",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.api.requestJson(`/api/v1/chat/threads/${encodeURIComponent(t)}`,{method:"GET"})}async list(t){return this.api.requestJson("/api/v1/chat/threads",{method:"GET"},t)}},Ru=class{constructor(t,r){this.createTurnInternal=t;this.streamTurnInternal=r}async create(t,r){return this.createTurnInternal(t,r)}async*stream(t,r){yield*this.streamTurnInternal(t,r)}},Bn=class{constructor(t){w(this,"model");w(this,"serverUrl");w(this,"apiKey");w(this,"getResponses");w(this,"ensureReadyFn");w(this,"api");w(this,"threads");w(this,"turn");this.model=t.model,this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.getResponses=t.getResponses,this.ensureReadyFn=t.ensureReady,this.api=new Iu(t.serverUrl,t.apiKey),this.threads=new Pu(this.api),this.turn=new Ru((r,n)=>this.createTurn(r,n),(r,n)=>this.streamTurn(r,n))}async create(t,r={}){this.ensureReadyFn();let n=performance.now(),{instructions:s,input:a}=co(t),o=await this.getResponses().create({model:this.model,input:a,instructions:s,maxOutputTokens:r.maxTokens,temperature:r.temperature,topP:r.topP});return{message:{role:"assistant",content:o.output.filter(l=>l.type==="text"&&l.text).map(l=>l.text).join("")},latencyMs:performance.now()-n,usage:o.usage?{promptTokens:o.usage.promptTokens,completionTokens:o.usage.completionTokens,totalTokens:o.usage.totalTokens}:void 0}}async*stream(t,r={}){this.ensureReadyFn();let{instructions:n,input:s}=co(t),a=0,o=this.getResponses().stream({model:this.model,input:s,instructions:n,maxOutputTokens:r.maxTokens,temperature:r.temperature,topP:r.topP});for await(let i of o)i.type==="text_delta"?yield{index:a++,content:i.delta,done:!1,role:"assistant"}:i.type==="done"&&(yield{index:a,content:"",done:!0,role:"assistant"})}requireServerUrl(t){if(!this.serverUrl)throw new U(dt.invalid_input,`${t} requires serverUrl to be configured.`)}async createTurn(t,r){return this.ensureReadyFn(),this.requireServerUrl("chat.turn.create()"),this.api.requestJson(`/api/v1/chat/threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify({...r,threadId:t})})}async*streamTurn(t,r){this.ensureReadyFn(),this.requireServerUrl("chat.turn.stream()");let n=await fetch(`${this.serverUrl}/api/v1/chat/threads/${encodeURIComponent(t)}/turns`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey?{Authorization:`Bearer ${this.apiKey}`}:{}},body:JSON.stringify({...r,threadId:t,stream:!0})});if(!n.ok||!n.body)throw new U(dt.network_unavailable,`chat.turn.stream() failed: HTTP ${n.status}`);let s=n.body.getReader(),a=new TextDecoder,o="",i=0;for(;;){let{done:l,value:c}=await s.read();o+=a.decode(c??new Uint8Array,{stream:!l});let u=o.indexOf(`
28
+
29
+ `);for(;u>=0;){let p=o.slice(0,u);o=o.slice(u+2);let f=p.split(`
30
+ `).filter(m=>m.startsWith("data:")).map(m=>m.slice(5).trim()).join(`
31
+ `);if(f&&f!=="[DONE]"){let m=JSON.parse(f);m.type==="text_delta"&&(m.delta||m.content)&&(yield{index:i++,content:m.delta??m.content??"",done:!1,role:"assistant"}),m.type==="done"&&(yield{index:i,content:"",done:!0,role:"assistant"})}u=o.indexOf(`
32
+
33
+ `)}if(l)break}}};function co(e){let t=[],r=[];for(let n of e)if(n.role==="system")t.push(n.content);else{let s=n.role==="assistant"?"[assistant] ":"";r.push(s+n.content)}return{instructions:t.length>0?t.join(`
34
+ `):void 0,input:r.join(`
35
+ `)}}var Fs=class Fs{constructor(t){w(this,"installationId");w(this,"orgId");w(this,"appId");w(this,"_registrationState","pending");w(this,"_tokenState",{type:"none"});w(this,"_serverDeviceId",null);this.installationId=t.installationId,this.orgId=t.orgId??null,this.appId=t.appId??null}get registrationState(){return this._registrationState}get tokenState(){return this._tokenState}get serverDeviceId(){return this._serverDeviceId}get isRegistered(){return this._registrationState==="registered"}authHeaders(){return this._tokenState.type==="valid"&&this._tokenState.expiresAt>new Date?{Authorization:`Bearer ${this._tokenState.accessToken}`}:null}telemetryResource(){let t={"device.id":this.installationId,platform:"browser"};return this.orgId&&(t["org.id"]=this.orgId),this.appId&&(t["app.id"]=this.appId),t}_updateRegistered(t,r,n){this._serverDeviceId=t,this._tokenState={type:"valid",accessToken:r,expiresAt:n},this._registrationState="registered"}_updateToken(t,r){this._tokenState={type:"valid",accessToken:t,expiresAt:r}}_markFailed(){this._registrationState="failed"}_markTokenExpired(){this._tokenState={type:"expired"}}static getOrCreateInstallationId(){try{let t=localStorage.getItem(Fs.STORAGE_KEY);if(t)return t;let r=crypto.randomUUID();return localStorage.setItem(Fs.STORAGE_KEY,r),r}catch{return crypto.randomUUID()}}};w(Fs,"STORAGE_KEY","octomil_installation_id");var Gr=Fs;var pO=["oct_pub_test_","oct_pub_live_"];function uo(e){if(!pO.some(t=>e.startsWith(t)))throw new Error("Publishable key must start with 'oct_pub_test_' or 'oct_pub_live_'")}function hg(e){return e.startsWith("oct_pub_test_")?"test":e.startsWith("oct_pub_live_")?"live":null}var fg=null;function Ns(){return fg}async function mg(e={}){e.auth?.type==="publishable_key"&&uo(e.auth.key);let t=Gr.getOrCreateInstallationId(),r=e.auth?.type==="anonymous"?e.auth.appId:e.auth?.appId,n=e.auth?.type==="anonymous"?null:e.auth?.orgId??null,s=new Gr({installationId:t,orgId:n,appId:r??null});return fg=s,e.auth!=null&&e.monitoring?.enabled===!0&&_g(s,e).catch(()=>{}),s}async function _g(e,t,r=0){let a=t.auth?.type==="anonymous"?null:t.auth?.orgId??null;try{let o=t.baseUrl||"https://api.octomil.com",i={"Content-Type":"application/json"};t.auth?.type==="publishable_key"?i.Authorization=`Bearer ${t.auth.key}`:t.auth?.type==="bootstrap_token"&&(i.Authorization=`Bearer ${t.auth.token}`),e.appId&&(i["X-App-Id"]=e.appId);let l=new URL(`${o.replace(/\/+$/,"")}/api/v1/devices/register`);a&&l.searchParams.set("org_id",a);let c=await fetch(l.toString(),{method:"POST",headers:i,body:JSON.stringify({device_identifier:e.installationId,installation_id:e.installationId,platform:"browser",app_id:e.appId})});if(!c.ok){if(c.status===403){console.warn("[Octomil] Registration failed: invalid credentials"),e._markFailed();return}throw new Error(`Registration failed: ${c.status}`)}let u=await c.json(),p=u.device_id??u.id;if(!p||!u.access_token||!u.expires_at)throw new Error("Registration response missing device token fields");e._updateRegistered(p,u.access_token,new Date(u.expires_at)),t.monitoring?.enabled&&hO(e,t)}catch(o){if(console.warn(`[Octomil] Registration attempt ${r+1} failed:`,o),r<10){let i=Math.min(1e3*Math.pow(2,r),3e5),l=i*.1*Math.random(),c=i+l;return await new Promise(u=>setTimeout(u,c)),_g(e,t,r+1)}e._markFailed()}}function hO(e,t){let r=t.monitoring?.heartbeatIntervalMs??3e5;setInterval(async()=>{let n=e.authHeaders();if(n)try{let s=t.baseUrl||"https://api.octomil.com";if(!e.serverDeviceId)return;await fetch(`${s.replace(/\/+$/,"")}/api/v1/devices/${e.serverDeviceId}/heartbeat`,{method:"PUT",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({device_identifier:e.installationId})})}catch{}},r)}var Ou={octomilResponse:"octomil.response",octomilModelLoad:"octomil.model.load",octomilControlRefresh:"octomil.control.refresh",octomilControlHeartbeat:"octomil.control.heartbeat",octomilToolExecute:"octomil.tool.execute",octomilFallbackCloud:"octomil.fallback.cloud",octomilRolloutSync:"octomil.rollout.sync",octomilArtifactDownload:"octomil.artifact.download",octomilArtifactActivation:"octomil.artifact.activation",octomilFederationRound:"octomil.federation.round",octomilTrainingJob:"octomil.training.job",octomilDeviceSync:"octomil.device.sync",octomilTelemetryUpload:"octomil.telemetry.upload"},g3=Object.values(Ou);var gg={modelId:"model.id",modelVersion:"model.version",runtimeExecutor:"runtime.executor",requestMode:"request.mode",locality:"locality",streaming:"streaming",routePolicy:"route.policy",routeDecision:"route.decision",deviceClass:"device.class",fallbackReason:"fallback.reason",errorType:"error.type",toolCallTier:"tool.call_tier",modelSourceFormat:"model.source_format",modelSizeBytes:"model.size_bytes",toolName:"tool.name",toolRound:"tool.round",fallbackProvider:"fallback.provider",assignmentCount:"assignment_count",heartbeatSequence:"heartbeat.sequence",rolloutId:"rollout.id",modelsSynced:"models_synced"};var Un=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"orgId");w(this,"serverDeviceId",null);w(this,"heartbeatTimer",null);w(this,"heartbeatSequence",0);w(this,"deviceContext");w(this,"telemetry");this.serverUrl=(t.serverUrl||"https://api.octomil.com").replace(/\/+$/,""),this.apiKey=t.apiKey,this.orgId=t.orgId,this.deviceContext=t.deviceContext??null,this.serverDeviceId=this.deviceContext?.serverDeviceId??null,this.telemetry=t.telemetry??null}async refresh(){if(!this.serverDeviceId)return{updated:!1,configVersion:"",assignmentsChanged:!1,fetchedAt:new Date().toISOString()};let t={};Object.assign(t,this.resolveAuthHeaders());let r=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/assignments`,{headers:t});if(!r.ok)throw new U("NETWORK_UNAVAILABLE",`Refresh assignments failed: ${r.status}`);let n=await r.json();return{updated:n.updated??!0,configVersion:n.config_version??"",assignmentsChanged:n.assignments_changed??!1,fetchedAt:new Date().toISOString()}}async register(t){let r=t||this.deviceContext?.installationId||await this.generateDeviceId(),n={device_identifier:r,installation_id:this.deviceContext?.installationId??r,app_id:this.deviceContext?.appId??void 0,platform:"browser",os_version:typeof navigator<"u"?navigator.userAgent:"unknown",sdk_version:"1.0.0",locale:typeof navigator<"u"?navigator.language:void 0,timezone:typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0,device_info:this.collectDeviceInfo()},s={"Content-Type":"application/json"};Object.assign(s,this.resolveAuthHeaders()),this.deviceContext?.appId&&(s["X-App-Id"]=this.deviceContext.appId);let a=new URL(`${this.serverUrl}/api/v1/devices/register`);this.orgId&&a.searchParams.set("org_id",this.orgId);let o;try{o=await fetch(a.toString(),{method:"POST",headers:s,body:JSON.stringify(n)})}catch(l){throw new U("NETWORK_UNAVAILABLE",`Registration request failed: ${String(l)}`,l)}if(!o.ok)throw new U("NETWORK_UNAVAILABLE",`Registration failed: ${o.status}`);let i=await o.json();return this.serverDeviceId=i.device_id??i.id??null,this.serverDeviceId&&this.deviceContext&&i.access_token&&i.expires_at&&this.deviceContext._updateRegistered(this.serverDeviceId,i.access_token,new Date(i.expires_at)),{id:this.serverDeviceId??"",deviceIdentifier:r,orgId:this.orgId||"",status:i.status||"active"}}async heartbeat(){if(!this.serverDeviceId)throw new U("INVALID_INPUT","Device not registered");let t=this.heartbeatSequence++;this.telemetry?.track({name:Ou.octomilControlHeartbeat,timestamp:new Date().toISOString(),attributes:{[gg.heartbeatSequence]:t}});let r={sdk_version:"1.0.0",platform:"browser",os_version:typeof navigator<"u"?navigator.userAgent:"unknown"},n={"Content-Type":"application/json"};Object.assign(n,this.resolveAuthHeaders());let s;try{s=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/heartbeat`,{method:"PUT",headers:n,body:JSON.stringify(r)})}catch(o){throw new U("NETWORK_UNAVAILABLE",`Heartbeat request failed: ${String(o)}`,o)}if(!s.ok)throw new U("NETWORK_UNAVAILABLE",`Heartbeat failed: ${s.status}`);let a=await s.json();return{status:a.status||"ok",serverTime:a.server_time}}async reportObservedState(t=[]){if(!this.serverDeviceId)throw new U("INVALID_INPUT","Device not registered");let r={schemaVersion:"1.4.0",deviceId:this.serverDeviceId,reportedAt:new Date().toISOString(),models:t,active_bindings:t.filter(a=>a.status==="active").map(a=>({binding_key:a.bindingKey??a.useCase??a.modelId,base_model_id:a.modelId,base_version:a.version??"",use_case:a.useCase,deployment_id:a.deploymentId,deployment_key:a.deploymentKey,model_name:a.modelName,model_ref:a.modelRef})),sdkVersion:"1.0.0",osVersion:typeof navigator<"u"?navigator.userAgent:"unknown"},n={"Content-Type":"application/json"};Object.assign(n,this.resolveAuthHeaders());let s;try{s=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/observed-state`,{method:"POST",headers:n,body:JSON.stringify(r)})}catch(a){throw new U("NETWORK_UNAVAILABLE",`Report observed state failed: ${String(a)}`,a)}if(!s.ok)throw new U("NETWORK_UNAVAILABLE",`Report observed state failed: ${s.status}`)}async fetchDesiredState(){if(!this.serverDeviceId)throw new U("INVALID_INPUT","Device not registered");let t={};Object.assign(t,this.resolveAuthHeaders());let r;try{r=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/desired-state`,{headers:t})}catch(n){throw new U("NETWORK_UNAVAILABLE",`Fetch desired state failed: ${String(n)}`,n)}if(!r.ok)throw new U("NETWORK_UNAVAILABLE",`Fetch desired state failed: ${r.status}`);return await r.json()}async sync(t={}){if(!this.serverDeviceId)throw new U("INVALID_INPUT","Device not registered");let r={"Content-Type":"application/json"};Object.assign(r,this.resolveAuthHeaders());let n;try{n=await fetch(`${this.serverUrl}/api/v1/devices/${this.serverDeviceId}/sync`,{method:"POST",headers:r,body:JSON.stringify({schemaVersion:t.schemaVersion??"1.12.0",deviceId:this.serverDeviceId,requestedAt:t.requestedAt??new Date().toISOString(),knownStateVersion:t.knownStateVersion,sdkVersion:t.sdkVersion,platform:t.platform??"browser",appId:t.appId,appVersion:t.appVersion,modelInventory:t.modelInventory??[],activeVersions:t.activeVersions??[],availableStorageBytes:t.availableStorageBytes})})}catch(s){throw new U("NETWORK_UNAVAILABLE",`Device sync failed: ${String(s)}`,s)}if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Device sync failed: ${n.status}`);return await n.json()}startHeartbeat(t=3e5){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.heartbeat().catch(()=>{})},t)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}get registeredDeviceId(){return this.serverDeviceId}async generateDeviceId(){let t=[typeof navigator<"u"?navigator.userAgent:"unknown",typeof screen<"u"?screen.width:0,typeof screen<"u"?screen.height:0,typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC"].join("|"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}collectDeviceInfo(){return{platform:"browser",user_agent:typeof navigator<"u"?navigator.userAgent:"unknown",screen_width:typeof screen<"u"?screen.width:0,screen_height:typeof screen<"u"?screen.height:0,device_memory_gb:typeof navigator<"u"&&navigator.deviceMemory||0,language:typeof navigator<"u"?navigator.language:"unknown"}}resolveAuthHeaders(){return this.deviceContext?.authHeaders()??this.resolveApiKeyHeaders()}resolveApiKeyHeaders(){return this.apiKey?{Authorization:`Bearer ${this.apiKey}`}:{}}};async function po(e,t,r,n,s){if(!e)throw new U("INVALID_INPUT","serverUrl is required for embed()");if(!t)throw new U("INVALID_INPUT","apiKey is required for embed()");let a=`${e.replace(/\/+$/,"")}/api/v1/embeddings`,o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model_id:r,input:n}),signal:s})}catch(l){throw new U("NETWORK_UNAVAILABLE",`embed() request failed: ${String(l)}`,l)}if(!o.ok)throw new U("INFERENCE_FAILED",`embed() failed: HTTP ${o.status}`);let i=await o.json();return{embeddings:i.data.map(l=>l.embedding),model:i.model,usage:{promptTokens:i.usage.prompt_tokens,totalTokens:i.usage.total_tokens}}}var zn=class{constructor(){w(this,"session",null);w(this,"ortModule",null);w(this,"resolvedBackend",null)}async createSession(t,r){let n=await this.loadOrt(),s=await this.resolveProvider(n,r);this.resolvedBackend=s==="webgpu"?"webgpu":"wasm";let a={executionProviders:[s],graphOptimizationLevel:"all"};try{this.session=await n.InferenceSession.create(t,a)}catch(o){if(s==="webgpu")try{this.session=await n.InferenceSession.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.resolvedBackend="wasm"}catch(i){throw new U("MODEL_LOAD_FAILED","Failed to create ONNX session with both WebGPU and WASM backends.",i)}else throw new U("MODEL_LOAD_FAILED",`Failed to create ONNX session: ${String(o)}`,o)}}async run(t){this.ensureSession();let r=this.ortModule,n=this.session,s={};for(let[u,p]of Object.entries(t))s[u]=new r.Tensor(fO(p.data),p.data,p.dims);let a=performance.now(),o;try{o=await n.run(s)}catch(u){throw new U("INFERENCE_FAILED",`Inference run failed: ${String(u)}`,u)}let i=performance.now()-a,l=this.convertOutputs(o),c=this.extractConvenience(l);return{tensors:l,latencyMs:i,...c}}get inputNames(){return this.ensureSession(),this.session.inputNames}get outputNames(){return this.ensureSession(),this.session.outputNames}get activeBackend(){return this.resolvedBackend}dispose(){this.session&&(this.session.release(),this.session=null)}async isAvailable(){try{return await this.loadOrt(),!0}catch{return!1}}async loadOrt(){if(this.ortModule)return this.ortModule;try{return this.ortModule=await Promise.resolve().then(()=>iO(yg(),1)),this.ortModule}catch(t){throw new U("RUNTIME_UNAVAILABLE","Failed to import onnxruntime-web. Make sure the package is installed: npm i onnxruntime-web",t)}}async resolveProvider(t,r){if(r==="wasm")return"wasm";if(r==="webgpu"||r===void 0){if(await this.detectWebGPU())return"webgpu";if(r==="webgpu")throw new U("RUNTIME_UNAVAILABLE","WebGPU was explicitly requested but is not available in this browser.")}return"wasm"}async detectWebGPU(){if(typeof navigator>"u")return!1;try{let t=navigator.gpu;return t?await t.requestAdapter()!==null:!1}catch{return!1}}ensureSession(){if(!this.session)throw new U("CANCELLED","No active session. Call load() before running inference.")}convertOutputs(t){let r={};for(let n of Object.keys(t)){let s=t[n];r[n]={data:s.data,dims:Array.from(s.dims)}}return r}extractConvenience(t){let r=Object.keys(t);if(r.length===0)return{};let s=t[r[0]].data;if(s.length===0)return{};if(s.length===1)return{label:String(Number(s[0])),score:1};if(!(s instanceof Float32Array))return{};let a=Array.from(s),o=0,i=-1/0;for(let l=0;l<a.length;l++)a[l]>i&&(i=a[l],o=l);return{label:String(o),score:i,scores:a}}};function fO(e){return e instanceof Float32Array?"float32":e instanceof Int32Array?"int32":e instanceof BigInt64Array?"int64":e instanceof Uint8Array?"uint8":"float32"}var jr=3,Lu=1e3,$n=class{constructor(t,r){w(this,"modelId");w(this,"serverUrl");w(this,"apiKey");w(this,"onProgress");w(this,"cache");this.modelId=t.model,this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.onProgress=t.onProgress,this.cache=r}async load(){let t=await this.resolveModelUrl(),r=await this.cache.get(t);if(r)return r;let n=await this.download(t);return this.validate(n),await this.cache.put(t,n),n}async isCached(){let t=await this.resolveModelUrl();return this.cache.has(t)}async clearCache(){let t=await this.resolveModelUrl();await this.cache.remove(t)}async getCacheInfo(){let t=await this.resolveModelUrl();return this.cache.info(t)}async resolveModelUrl(){if(this.modelId.startsWith("http://")||this.modelId.startsWith("https://"))return this.modelId;if(!this.serverUrl)throw new U("MODEL_NOT_FOUND",`Cannot resolve model "${this.modelId}": no serverUrl configured.`);return this.fetchResolverUrl(this.modelId)}async fetchResolverUrl(t){let r=`${this.serverUrl}/api/v1/registry/resolve/${encodeURIComponent(t)}`,n={Accept:"application/json"};this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`);let s;try{s=await fetch(r,{headers:n})}catch(i){throw new U("NETWORK_UNAVAILABLE",`Failed to reach model resolver at ${r}`,i)}if(!s.ok)throw s.status===404?new U("MODEL_NOT_FOUND",`Model "${t}" not found in registry.`):new U("NETWORK_UNAVAILABLE",`Model resolver returned HTTP ${s.status}: ${s.statusText}`);let a=await s.json(),o=a.download_url??a.url;if(!o)throw new U("MODEL_LOAD_FAILED",`Model resolver response for "${t}" did not include a download URL`);return o}buildHeaders(t={}){let r={"Accept-Encoding":"gzip, deflate, br",...t};return this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`),r}async download(t){let r=[],n=0,s=0,a=0;for(;a<=jr;){let l=this.buildHeaders(n>0?{Range:`bytes=${n}-`}:{}),c;try{c=await fetch(t,{headers:l})}catch(f){if(a++,a>jr)throw new U("NETWORK_UNAVAILABLE",`Failed to download model from ${t} after ${jr} retries`,f);await this.delay(Lu*a);continue}if(c.status===416){if(r.length=0,n=0,a++,a>jr)throw new U("MODEL_LOAD_FAILED",`Model download failed: range request rejected after ${jr} retries`);await this.delay(Lu*a);continue}if(!c.ok&&c.status!==206)throw new U("MODEL_LOAD_FAILED",`Model download failed: HTTP ${c.status} ${c.statusText}`);if(s===0){let f=c.headers.get("Content-Range");if(f){let m=f.match(/\/(\d+)$/);m&&(s=parseInt(m[1],10))}else s=parseInt(c.headers.get("Content-Length")??"0",10)}if(!c.body)return await c.arrayBuffer();let u=c.body.getReader(),p=!1;try{for(;;){let{done:f,value:m}=await u.read();if(f)break;r.push(m),n+=m.byteLength,this.onProgress?.({loaded:n,total:s,percent:s>0?n/s*100:NaN})}}catch(f){if(p=!0,a++,a>jr)throw new U("NETWORK_UNAVAILABLE",`Model download interrupted after ${jr} retries`,f);await this.delay(Lu*a)}finally{u.releaseLock()}if(!p)break}let o=new Uint8Array(n),i=0;for(let l of r)o.set(l,i),i+=l.byteLength;return o.buffer}delay(t){return new Promise(r=>setTimeout(r,t))}validate(t){if(t.byteLength===0)throw new U("MODEL_LOAD_FAILED","Downloaded model is empty (0 bytes).");if(new Uint8Array(t,0,Math.min(4,t.byteLength))[0]!==8)throw new U("MODEL_LOAD_FAILED","Downloaded file does not appear to be a valid ONNX model.")}};var Vn=class{constructor(t,r,n){this.modelId=t;this.manager=r;this.onLoaded=n;w(this,"downloading",new Set);w(this,"errors",new Map)}async status(t){let r=t??this.modelId;return this.downloading.has(r)?"downloading":this.errors.has(r)?"error":await this.manager.isCached()?"ready":"not_cached"}async load(t){let r=t??this.modelId;this.downloading.add(r),this.errors.delete(r);try{await this.manager.load(),this.downloading.delete(r),this.onLoaded()}catch(n){throw this.downloading.delete(r),this.errors.set(r,String(n)),n}}async unload(t){await this.manager.clearCache()}async list(){let t=await this.manager.getCacheInfo();return t.cached?[{modelRef:this.modelId,cachedAt:t.cachedAt,sizeBytes:t.sizeBytes>0?t.sizeBytes:void 0}]:[]}async clearCache(){await this.manager.clearCache(),this.errors.clear()}getError(t){let r=t??this.modelId;return this.errors.get(r)}};var Gn=class{constructor(t={}){w(this,"serverUrl");w(this,"apiKey");w(this,"telemetry");w(this,"deviceContext");w(this,"localRuntime");w(this,"responseCache",new Map);w(this,"MAX_CACHE",100);this.serverUrl=t.serverUrl||"https://api.octomil.com",this.apiKey=t.apiKey,this.telemetry=t.telemetry??null,this.deviceContext=t.deviceContext??null,this.localRuntime=t.localRuntime??null}async create(t){let r=this.resolveLocalRuntime(t.model);if(r)return this.createLocal(t,r);let n=this.buildRequestBody(t,!1),s=`${this.serverUrl}/v1/chat/completions`,a={"Content-Type":"application/json"},o=this.deviceContext?.authHeaders();o?Object.assign(a,o):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),this.telemetry?.reportInferenceStarted(t.model,{target:"cloud",method:"responses.create",locality:"cloud"});let i=performance.now(),l;try{l=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(n)})}catch(f){throw this.telemetry?.reportInferenceFailed(t.model,"network_error",String(f)),new U("NETWORK_UNAVAILABLE",`Request failed: ${String(f)}`,f)}if(!l.ok)throw this.telemetry?.reportInferenceFailed(t.model,"http_error",`HTTP ${l.status}`),new U("NETWORK_UNAVAILABLE",`HTTP ${l.status}`);let c=await l.json(),u=this.parseResponse(t.model,c),p=performance.now()-i;return this.telemetry?.reportInferenceCompleted(t.model,p,{target:"cloud",method:"responses.create",locality:"cloud"}),this.cacheResponse(u),u}async*stream(t){let r=this.resolveLocalRuntime(t.model);if(r){yield*this.streamLocal(t,r);return}let n=this.buildRequestBody(t,!0),s=`${this.serverUrl}/v1/chat/completions`,a={"Content-Type":"application/json"},o=this.deviceContext?.authHeaders();o?Object.assign(a,o):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),this.telemetry?.reportInferenceStarted(t.model,{target:"cloud",method:"responses.stream",locality:"cloud"});let i=performance.now(),l;try{l=await fetch(s,{method:"POST",headers:a,body:JSON.stringify(n)})}catch(C){throw this.telemetry?.reportInferenceFailed(t.model,"network_error",String(C)),new U("NETWORK_UNAVAILABLE",`Request failed: ${String(C)}`,C)}if(!l.ok)throw this.telemetry?.reportInferenceFailed(t.model,"http_error",`HTTP ${l.status}`),new U("NETWORK_UNAVAILABLE",`HTTP ${l.status}`);if(!l.body)throw new U("NETWORK_UNAVAILABLE","No response body");let c=l.body.getReader(),u=new TextDecoder,p="",f=0,m=[],y=new Map,v;try{for(;;){let{done:C,value:S}=await c.read();if(C)break;p+=u.decode(S,{stream:!0});let O=p.split(`
36
+ `);p=O.pop()||"";for(let E of O){let K=E.trim();if(!K.startsWith("data: "))continue;let $=K.slice(6);if($!=="[DONE]")try{let V=JSON.parse($),Q=V.choices?.[0];if(!Q)continue;let G=Q.delta;if(G?.content&&(m.push(G.content),this.telemetry?.reportChunkProduced(t.model,f),f++,yield{type:"text_delta",delta:G.content}),G?.tool_calls)for(let W of G.tool_calls){let D=y.get(W.index)||{arguments:""};W.id&&(D.id=W.id),W.function?.name&&(D.name=W.function.name),W.function?.arguments&&(D.arguments+=W.function.arguments),y.set(W.index,D),this.telemetry?.reportChunkProduced(t.model,f),f++,yield{type:"tool_call_delta",index:W.index,id:W.id,name:W.function?.name,argumentsDelta:W.function?.arguments}}V.usage&&(v={promptTokens:V.usage.prompt_tokens,completionTokens:V.usage.completion_tokens,totalTokens:V.usage.total_tokens})}catch{}}}}finally{c.releaseLock()}let x=[],M=m.join("");M&&x.push({type:"text",text:M});for(let[,C]of[...y.entries()].sort((S,O)=>S[0]-O[0]))x.push({type:"tool_call",toolCall:{id:C.id||qr(),name:C.name||"",arguments:C.arguments}});let T={id:qr(),model:t.model,output:x,finishReason:y.size>0?"tool_calls":"stop",usage:v},A=performance.now()-i;this.telemetry?.reportInferenceCompleted(t.model,A,{target:"cloud",method:"responses.stream",locality:"cloud"}),this.cacheResponse(T),yield{type:"done",response:T}}resolveLocalRuntime(t){return this.localRuntime?typeof this.localRuntime=="function"?this.localRuntime(t)??null:this.localRuntime:null}cacheResponse(t){if(this.responseCache.size>=this.MAX_CACHE){let r=this.responseCache.keys().next().value;r&&this.responseCache.delete(r)}this.responseCache.set(t.id,t)}async createLocal(t,r){let n=this.buildEffectiveRequest(t);this.telemetry?.reportInferenceStarted(t.model,{target:"device",method:"responses.create",locality:"local"});let s=performance.now();try{let a=await r.create(n);return this.cacheResponse(a),this.telemetry?.reportInferenceCompleted(t.model,performance.now()-s,{target:"device",method:"responses.create",locality:"local"}),a}catch(a){throw this.telemetry?.reportInferenceFailed(t.model,"local_runtime_error",String(a)),a}}async*streamLocal(t,r){let n=this.buildEffectiveRequest(t);this.telemetry?.reportInferenceStarted(t.model,{target:"device",method:"responses.stream",locality:"local"});let s=performance.now(),a=0;try{for await(let o of r.stream(n))o.type!=="done"?(this.telemetry?.reportChunkProduced(t.model,a),a++):(this.cacheResponse(o.response),this.telemetry?.reportInferenceCompleted(t.model,performance.now()-s,{target:"device",method:"responses.stream",locality:"local"})),yield o}catch(o){throw this.telemetry?.reportInferenceFailed(t.model,"local_runtime_error",String(o)),o}}buildEffectiveRequest(t){let r=this.normalizeInput(t.input);if(t.previousResponseId){let n=this.responseCache.get(t.previousResponseId);n&&r.unshift({role:"assistant",content:n.output})}return t.instructions&&r.unshift({role:"system",content:t.instructions}),{...t,input:r,instructions:void 0,previousResponseId:void 0}}buildRequestBody(t,r){let n=this.buildMessages(this.buildEffectiveRequest(t));return{model:t.model,messages:n,max_tokens:t.maxOutputTokens,temperature:t.temperature,top_p:t.topP,stop:t.stop,stream:r,tools:t.tools?.map(s=>({type:"function",function:s.function}))}}buildMessages(t){return this.normalizeInput(t.input).map(n=>this.inputItemToMessage(n))}normalizeInput(t){return typeof t=="string"?[{role:"user",content:t}]:this.isResponseInputItems(t)?t.map(r=>({...r})):[{role:"user",content:t}]}isResponseInputItems(t){return t.every(r=>"role"in r)}inputItemToMessage(t){switch(t.role){case"system":return{role:"system",content:typeof t.content=="string"?t.content:""};case"user":return{role:"user",content:this.inputContentToMessageContent(t.content)};case"assistant":return this.assistantInputToMessage(t);case"tool":return{role:"tool",content:typeof t.content=="string"?t.content:"",tool_call_id:t.toolCallId};default:return{role:t.role,content:typeof t.content=="string"?t.content:""}}}assistantInputToMessage(t){if(typeof t.content=="string"||t.content==null)return{role:"assistant",content:t.content??""};if(this.isResponseOutputItems(t.content)){let r=t.content.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text),n=t.content.filter(s=>s.type==="tool_call"&&!!s.toolCall).map(s=>({id:s.toolCall.id,type:"function",function:{name:s.toolCall.name,arguments:s.toolCall.arguments}}));return{role:"assistant",content:r.join(""),...n.length>0?{tool_calls:n}:{}}}return{role:"assistant",content:this.contentBlocksToParts(t.content)}}isResponseOutputItems(t){return t.every(r=>r.type==="text"||r.type==="tool_call")}inputContentToMessageContent(t){return typeof t=="string"||t==null?t??"":this.isResponseOutputItems(t)?t.filter(r=>r.type==="text"&&typeof r.text=="string").map(r=>r.text).join(""):this.contentBlocksToParts(t)}contentBlocksToParts(t){return t.map(r=>this.contentBlockToPart(r))}contentBlockToPart(t){switch(t.type){case"text":return{type:"text",text:t.text??""};case"image":return t.imageUrl?{type:"image_url",image_url:{url:t.imageUrl}}:t.data?{type:"image_url",image_url:{url:`data:${t.mediaType??"image/png"};base64,${t.data}`}}:{type:"text",text:t.text??"[image]"};case"audio":if(t.data){let n=(t.mediaType??"audio/wav").split("/")[1]??"wav";return{type:"input_audio",input_audio:{data:t.data,format:n}}}return{type:"text",text:t.text??"[audio]"};case"video":return t.data?{type:"image_url",image_url:{url:`data:${t.mediaType??"video/mp4"};base64,${t.data}`}}:{type:"text",text:t.text??"[video]"};case"file":{let r=t.mediaType??"";if(t.data&&r.startsWith("image/"))return{type:"image_url",image_url:{url:`data:${r};base64,${t.data}`}};if(t.data&&r.startsWith("audio/")){let n=r.split("/")[1]??"wav";return{type:"input_audio",input_audio:{data:t.data,format:n}}}return t.data&&r.startsWith("video/")?{type:"image_url",image_url:{url:`data:${r};base64,${t.data}`}}:{type:"text",text:t.text??`[file: ${r||"unknown"}]`}}default:return{type:"text",text:t.text??""}}}parseResponse(t,r){let s=r.choices?.[0],a=[],o=s?.message;if(o?.content&&a.push({type:"text",text:o.content}),o?.tool_calls)for(let l of o.tool_calls){let c=l.function;a.push({type:"tool_call",toolCall:{id:l.id,name:c.name,arguments:c.arguments}})}let i=r.usage;return{id:r.id||qr(),model:t,output:a,finishReason:s?.finish_reason||"stop",usage:i?{promptTokens:i.prompt_tokens,completionTokens:i.completion_tokens,totalTokens:i.total_tokens}:void 0}}};function qr(){return`resp_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}var mO=3e5,Fu="octomil_routing_cache",jn=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"cacheTtlMs");w(this,"prefer");w(this,"cache",new Map);w(this,"lastRouteWasOffline",!1);this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.apiKey=t.apiKey,this.cacheTtlMs=t.cacheTtlMs??mO,this.prefer=t.prefer??"fastest"}async route(t,r,n,s){this.lastRouteWasOffline=!1;let a=this.cache.get(t);if(a&&a.expiresAt>Date.now())return a.decision;let o={model_id:t,model_params:r,model_size_mb:n,device_capabilities:s,prefer:this.prefer},i;try{i=await fetch(`${this.serverUrl}/api/v1/route`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(o)})}catch{return this.offlineFallback(t)}if(!i.ok)return this.offlineFallback(t);let l=await i.json();return this.cache.set(t,{decision:l,expiresAt:Date.now()+this.cacheTtlMs}),this.persistToStorage(t,l),l}async cloudInfer(t,r,n={}){let s={model_id:t,input_data:r,parameters:n},a;try{a=await fetch(`${this.serverUrl}/api/v1/inference`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)})}catch(o){throw new U("NETWORK_UNAVAILABLE",`Cloud inference request failed: ${String(o)}`,o)}if(!a.ok)throw new U("INFERENCE_FAILED",`Cloud inference failed: HTTP ${a.status}`);return await a.json()}clearCache(){this.cache.clear();try{localStorage.removeItem(Fu)}catch{}}invalidate(t){this.cache.delete(t);let r=this.loadPersistentCache();delete r[t],this.savePersistentCache(r)}offlineFallback(t){this.lastRouteWasOffline=!0;let n=this.loadPersistentCache()[t];return n?{...n,cached:!0,offline:!1}:{id:`offline-${t}`,target:"device",format:"onnx",engine:"ort-wasm",fallback_target:null,cached:!1,offline:!0}}persistToStorage(t,r){let n=this.loadPersistentCache();n[t]=r,this.savePersistentCache(n)}loadPersistentCache(){try{let t=localStorage.getItem(Fu);return t?JSON.parse(t):{}}catch{return{}}}savePersistentCache(t){try{localStorage.setItem(Fu,JSON.stringify(t))}catch{}}};async function ho(){let e=await _O(),t=navigator.deviceMemory,r=t?Math.round(t*1024):0,n=["wasm"];return e&&n.push("webgpu"),{platform:"web",model:navigator.userAgent,total_memory_mb:r,gpu_available:e,npu_available:!1,supported_runtimes:n}}async function _O(){if(typeof navigator>"u")return!1;try{let e=navigator.gpu;return e?await e.requestAdapter()!==null:!1}catch{return!1}}var fr={inferenceStarted:"inference.started",inferenceCompleted:"inference.completed",inferenceFailed:"inference.failed",inferenceChunkProduced:"inference.chunk_produced",deployStarted:"deploy.started",deployCompleted:"deploy.completed"},Nu={"inference.started":["model.id"],"inference.completed":["model.id","inference.duration_ms"],"inference.failed":["model.id","error.type","error.message"],"inference.chunk_produced":["model.id","inference.chunk_index"],"deploy.started":["model.id","model.version"],"deploy.completed":["model.id","deploy.duration_ms"]};var Ds={serviceName:"service.name",serviceVersion:"service.version",telemetrySdkName:"telemetry.sdk.name",telemetrySdkLanguage:"telemetry.sdk.language",telemetrySdkVersion:"telemetry.sdk.version",octomilOrgId:"octomil.org.id",octomilDeviceId:"octomil.device.id",octomilPlatform:"octomil.platform",octomilSdkSurface:"octomil.sdk.surface",octomilInstallId:"octomil.install.id",octomilDeviceClass:"octomil.device.class",octomilAvailableRuntimes:"octomil.available_runtimes",octomilAccelerators:"octomil.accelerators"};var vg="octomil_install_id",Bs=null;function fo(){if(Bs!==null)return Bs;try{let t=localStorage.getItem(vg);if(t)return Bs=t,t}catch{}let e=crypto.randomUUID();try{localStorage.setItem(vg,e)}catch{}return Bs=e,e}function bg(){Bs=null}var gO=3e4,wO=50,yO="https://api.octomil.com/v2/telemetry/events",Du="browser",vO="1.0.0",Hr=class{constructor(t={}){w(this,"url");w(this,"flushIntervalMs");w(this,"maxBatchSize");w(this,"apiKey");w(this,"authHeadersProvider");w(this,"resource");w(this,"queue",[]);w(this,"timerId",null);w(this,"disposed",!1);this.url=t.url??yO,this.flushIntervalMs=t.flushIntervalMs??gO,this.maxBatchSize=t.maxBatchSize??wO,this.apiKey=t.apiKey,this.authHeadersProvider=t.authHeadersProvider,this.resource={sdk:Du,sdk_version:t.sdkVersion??vO,device_id:t.deviceId??bO(),platform:Du,org_id:t.orgId??""},this.startAutoFlush()}updateResource(t){for(let[r,n]of Object.entries(t))r==="device.id"?this.resource.device_id=n:r==="org.id"?this.resource.org_id=n:r==="platform"&&(this.resource.platform=n)}track(t){this.disposed||(this.queue.push(t),this.queue.length>=this.maxBatchSize&&this.flush())}async flush(){if(this.queue.length===0)return;let t=this.queue.splice(0,this.maxBatchSize);await this.send(t)}async batch(t){t.length!==0&&await this.send(t)}close(){if(!this.disposed&&(this.disposed=!0,this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.queue.length>0)){let t=this.queue.splice(0),r=this.buildEnvelope(t);this.sendBeaconPayload(r)||this.send(t)}}reportInferenceStarted(t,r){this.track(this.makeEvent(fr.inferenceStarted,{"model.id":t,...r}))}reportInferenceCompleted(t,r,n){this.track(this.makeEvent(fr.inferenceCompleted,{"model.id":t,"inference.duration_ms":r,...n}))}reportInferenceFailed(t,r,n){this.track(this.makeEvent(fr.inferenceFailed,{"model.id":t,"error.type":r,"error.message":n}))}reportInferenceChunk(t,r){this.track(this.makeEvent(fr.inferenceChunkProduced,{"model.id":t,...r}))}reportChunkProduced(t,r,n){this.track(this.makeEvent(fr.inferenceChunkProduced,{"model.id":t,"inference.chunk_index":r,...n}))}reportTrainingStarted(t,r){this.track(this.makeEvent("training.started",{modelId:t,version:r}))}reportTrainingCompleted(t,r,n){this.track(this.makeEvent("training.completed",{modelId:t,version:r,durationMs:n}))}reportTrainingFailed(t,r,n){this.track(this.makeEvent("training.failed",{modelId:t,version:r,errorType:n}))}reportWeightUpload(t,r,n){this.track(this.makeEvent("training.weight_upload",{modelId:t,roundId:r,sampleCount:n}))}reportDeployStarted(t,r){this.track(this.makeEvent("deploy.started",{modelId:t,version:r}))}reportDeployCompleted(t,r,n){this.track(this.makeEvent("deploy.completed",{modelId:t,version:r,durationMs:n}))}reportDeployRollback(t,r,n,s){this.track(this.makeEvent("deploy.rollback",{modelId:t,fromVersion:r,toVersion:n,reason:s}))}reportExperimentAssigned(t,r,n){this.track(this.makeEvent("experiment.assigned",{modelId:t,experimentId:r,variant:n}))}reportExperimentMetric(t,r,n){this.track(this.makeEvent("experiment.metric",{experimentId:t,metricName:r,metricValue:n}))}makeEvent(t,r){return{name:t,timestamp:new Date().toISOString(),traceId:Bu(16),spanId:Bu(8),attributes:r}}startAutoFlush(){typeof setInterval>"u"||(this.timerId=setInterval(()=>{this.flush()},this.flushIntervalMs))}buildEnvelope(t){let r=this.resourceToOtlpAttributes(),n=t.map(s=>this.eventToLogRecord(s));return{resourceLogs:[{resource:{attributes:r},scopeLogs:[{scope:{name:`@octomil/${Du}`,version:this.resource.sdk_version},logRecords:n}]}]}}resourceToOtlpAttributes(){let t=[{key:"sdk",value:{stringValue:this.resource.sdk}},{key:"sdk_version",value:{stringValue:this.resource.sdk_version}},{key:"device_id",value:{stringValue:this.resource.device_id}},{key:"platform",value:{stringValue:this.resource.platform}},{key:"org_id",value:{stringValue:this.resource.org_id}}],r=fo();return r&&t.push({key:Ds.octomilInstallId,value:{stringValue:r}}),t}eventToLogRecord(t){let r=Object.entries(t.attributes).map(([n,s])=>({key:n,value:this.toOtlpValue(s)}));return{timeUnixNano:String(new Date(t.timestamp).getTime()*1e6),severityNumber:9,severityText:"INFO",body:{stringValue:t.name},attributes:r,traceId:t.traceId,spanId:t.spanId}}toOtlpValue(t){return typeof t=="string"?{stringValue:t}:typeof t=="boolean"?{boolValue:t}:Number.isInteger(t)?{intValue:String(t)}:{doubleValue:t}}async send(t){let r=this.buildEnvelope(t),n=JSON.stringify(r),s=this.authHeadersProvider?.()??null;try{if(!s&&this.sendBeaconPayload(r))return;let a={"Content-Type":"application/json"};s?Object.assign(a,s):this.apiKey&&(a.Authorization=`Bearer ${this.apiKey}`),await fetch(this.url,{method:"POST",headers:a,body:n,keepalive:!0})}catch{}}sendBeaconPayload(t){if(typeof navigator>"u"||!navigator.sendBeacon)return!1;try{let r=new Blob([JSON.stringify(t)],{type:"application/json"});return navigator.sendBeacon(this.url,r)}catch{return!1}}};function Bu(e){let t=new Uint8Array(e);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(Math.random()*256);return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}function bO(){return`dev_${Bu(8)}`}var Wr=null;function Mg(e={}){return Wr&&Wr.close(),Wr=new Hr(e),Wr}function xg(){return Wr}function Tg(){Wr?.close(),Wr=null}var Us=class{constructor(t){this.runPrediction=t}async create(t){return{output:await this.runPrediction({text:t.input})}}},qn=class{constructor(t){w(this,"predictions");this.predictions=new Us(t)}async predict(t){return this.predictions.create({input:t}).then(r=>r.output)}};var mo=class{constructor(t){w(this,"options");w(this,"cache");w(this,"loader");w(this,"engine");w(this,"inferenceEngine");w(this,"routingClient",null);w(this,"deviceContext");w(this,"telemetry",null);w(this,"deviceCaps",null);w(this,"_responses",null);w(this,"_chat",null);w(this,"_control",null);w(this,"_capabilities",null);w(this,"_models",null);w(this,"_audio",null);w(this,"_text",null);w(this,"loaded",!1);w(this,"closed",!1);w(this,"_warmedUp",!1);let r=t.auth,n=r?.serverUrl,s=r?.type==="org_api_key"?r.apiKey:r?.type==="device_token"?r.bootstrapToken:void 0,a=r?.type==="org_api_key"?r.orgId:Ns()?.orgId??void 0;this.deviceContext=Ns(),this.options={telemetry:!1,cacheStrategy:"cache-api",...t,serverUrl:n,apiKey:s},this.cache=lo(this.options.cacheStrategy),this.loader=new $n(this.options,this.cache);let o=t.runtime?null:new zn;this.engine=t.runtime??o,this.inferenceEngine=o,n&&s&&this.options.routing&&(this.routingClient=new jn({serverUrl:n,apiKey:s,cacheTtlMs:this.options.routing.cacheTtlMs,prefer:this.options.routing.prefer})),this.options.telemetry&&(this.telemetry=new Hr({url:this.options.telemetryUrl,apiKey:s,authHeadersProvider:()=>this.deviceContext?.authHeaders()??null,orgId:a,deviceId:this.deviceContext?.installationId}),this.deviceContext&&this.telemetry.updateResource(this.deviceContext.telemetryResource()))}async load(){this.ensureNotClosed();let t=performance.now(),r=await this.loader.load();await this.engine.createSession(r,this.options.backend),this.loaded=!0;let n=performance.now()-t;this.telemetry?.reportDeployStarted(this.options.model,"latest"),this.telemetry?.reportDeployCompleted(this.options.model,"latest",n)}async warmup(){if(this.ensureReady(),this._warmedUp)return;let t=this.inferenceEngine?this.inferenceEngine.inputNames[0]:void 0;if(t){let r={[t]:{data:new Float32Array([0]),dims:[1,1]}};try{await this.engine.run(r)}catch{}}this._warmedUp=!0}get isWarmedUp(){return this._warmedUp}async predict(t){if(this.ensureReady(),this.routingClient){let s=await this.tryCloudInference(t);if(s)return s}let r=this.prepareTensors(t);this.telemetry?.reportInferenceStarted(this.options.model,{target:"device"});let n=await this.engine.run(r);return this.telemetry?.reportInferenceCompleted(this.options.model,n.latencyMs,{backend:this.inferenceEngine?.activeBackend??"unknown",target:"device"}),n}async predictBatch(t){this.ensureReady();let r=performance.now(),n=[];for(let a of t){let o=this.prepareTensors(a),i=await this.engine.run(o);n.push(i)}let s=performance.now()-r;return this.telemetry?.reportInferenceCompleted(this.options.model,s,{backend:this.inferenceEngine?.activeBackend??"unknown",batchSize:t.length}),n}async createChat(t,r={}){return this.chat.create(t,r)}async*createChatStream(t,r={}){yield*this.chat.stream(t,r)}async*predictStream(t,r,n,s){if(!this.options.serverUrl||!this.options.apiKey)throw new U("INFERENCE_FAILED","predictStream() requires serverUrl and apiKey to be configured.");let a=`${this.options.serverUrl.replace(/\/+$/,"")}/api/v1/inference/stream`,o={model_id:t};typeof r=="string"?o.input_data=r:o.messages=r,n&&(o.parameters=n);let i={"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.options.apiKey}`},l;try{l=await fetch(a,{method:"POST",headers:i,body:JSON.stringify(o),signal:s})}catch(m){throw new U("NETWORK_UNAVAILABLE",`predictStream request failed: ${String(m)}`,m)}if(!l.ok)throw new U("INFERENCE_FAILED",`predictStream failed: HTTP ${l.status}`);if(!l.body)throw new U("INFERENCE_FAILED","Server did not return a streaming body.");let c=l.body.getReader(),u=new TextDecoder,p="",f=0;try{for(;;){let{done:m,value:y}=await c.read();if(m)break;p+=u.decode(y,{stream:!0});let v=p.split(`
37
+ `);p=v.pop()??"";for(let x of v){if(!x.startsWith("data:"))continue;let M=x.slice(5).trim();if(!M)continue;let T;try{T=JSON.parse(M)}catch{continue}this.telemetry?.reportChunkProduced(t,f),f++,yield{token:T.token??"",done:T.done??!1,provider:T.provider,latencyMs:T.latency_ms,sessionId:T.session_id}}}}finally{c.releaseLock()}}async embed(t,r,n){if(!this.options.serverUrl||!this.options.apiKey)throw new U("NETWORK_UNAVAILABLE","embed() requires serverUrl and apiKey to be configured.");return po(this.options.serverUrl,this.options.apiKey,t,r,n)}async isCached(){return this.ensureNotClosed(),this.loader.isCached()}async clearCache(){return this.ensureNotClosed(),this.loader.clearCache()}async cacheInfo(){return this.ensureNotClosed(),this.loader.getCacheInfo()}get activeBackend(){return this.inferenceEngine?.activeBackend??null}get inputNames(){if(this.ensureReady(),!this.inferenceEngine)throw new U("INVALID_INPUT","inputNames not available with custom runtime");return this.inferenceEngine.inputNames}get outputNames(){if(this.ensureReady(),!this.inferenceEngine)throw new U("INVALID_INPUT","outputNames not available with custom runtime");return this.inferenceEngine.outputNames}get isLoaded(){return this.loaded}get chat(){return this._chat||(this._chat=new Bn({model:this.options.model,serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,getResponses:()=>this.responses,ensureReady:()=>this.ensureReady()})),this._chat}get responses(){return this._responses||(this._responses=new Gn({serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,telemetry:this.telemetry,deviceContext:this.deviceContext,localRuntime:this.options.responsesRuntime})),this._responses}get control(){return this._control||(this._control=new Un({serverUrl:this.options.serverUrl,apiKey:this.options.apiKey,orgId:this.options.auth?.type==="org_api_key"?this.options.auth.orgId:void 0,deviceContext:this.deviceContext,telemetry:this.telemetry})),this._control}get capabilities(){return this._capabilities||(this._capabilities=new Dn),this._capabilities}get models(){return this._models||(this._models=new Vn(this.options.model,this.loader,()=>{})),this._models}get audio(){if(!this._audio){if(!this.options.serverUrl||!this.options.apiKey)throw new U("INVALID_INPUT","audio requires serverUrl and apiKey to be configured.");this._audio=new Nn(this.options.serverUrl,this.options.apiKey)}return this._audio}get text(){return this._text||(this._text=new qn(t=>this.predict(t))),this._text}close(){this.closed||(this.closed=!0,this.loaded=!1,this.engine.dispose(),this.telemetry?.close(),this.telemetry=null,this._responses=null,this._chat=null,this._control?.stopHeartbeat(),this._control=null,this._capabilities=null,this._models=null,this._audio=null,this._text=null,this._warmedUp=!1)}ensureNotClosed(){if(this.closed)throw new U("CANCELLED","This OctomilClient instance has been closed. Create a new one.")}ensureReady(){if(this.ensureNotClosed(),!this.loaded)throw new U("MODEL_LOAD_FAILED","Model not loaded. Call load() before predict() or chat().")}prepareTensors(t){if(this.isNamedTensors(t))return t;if("raw"in t&&"dims"in t){let r=this.inferenceEngine.inputNames[0];if(!r)throw new U("INVALID_INPUT","Model has no input tensors defined.");return{[r]:{data:t.raw,dims:t.dims}}}if("text"in t){let r=this.inferenceEngine.inputNames[0];if(!r)throw new U("INVALID_INPUT","Model has no input tensors defined.");let n=new Int32Array(Array.from(t.text).map(s=>s.codePointAt(0)??0));return{[r]:{data:n,dims:[1,n.length]}}}if("image"in t)return this.imageToTensors(t.image);throw new U("INVALID_INPUT","Unrecognised PredictInput format. Provide named tensors, { text }, { image }, or { raw, dims }.")}isNamedTensors(t){if("text"in t||"image"in t||"raw"in t)return!1;let r=Object.values(t)[0];return r!==void 0&&typeof r=="object"&&"data"in r&&"dims"in r}imageToTensors(t){let r;if(t instanceof ImageData)r=t;else{let c=t instanceof HTMLCanvasElement?t:(()=>{let p=document.createElement("canvas");return p.width=t.naturalWidth||t.width,p.height=t.naturalHeight||t.height,p.getContext("2d").drawImage(t,0,0),p})(),u=c.getContext("2d");if(!u)throw new U("INVALID_INPUT","Could not get 2D context from canvas.");r=u.getImageData(0,0,c.width,c.height)}let{width:n,height:s,data:a}=r,o=n*s,i=new Float32Array(3*o);for(let c=0;c<o;c++)i[c]=a[c*4]/255,i[o+c]=a[c*4+1]/255,i[2*o+c]=a[c*4+2]/255;let l=this.inferenceEngine?.inputNames[0];if(!l)throw new U("INVALID_INPUT","Model has no input tensors defined.");return{[l]:{data:i,dims:[1,3,s,n]}}}async tryCloudInference(t){try{this.deviceCaps||(this.deviceCaps=await ho());let r=this.options.routing,n=await this.routingClient.route(this.options.model,r.modelParams??0,r.modelSizeMb??0,this.deviceCaps);if(!n||n.target!=="cloud")return null;let s=performance.now(),a=await this.routingClient.cloudInfer(this.options.model,t),o=performance.now()-s;return this.telemetry?.reportInferenceCompleted(this.options.model,o,{target:"cloud",provider:a.provider,routingId:n.id}),{tensors:{},latencyMs:o,...typeof a.output=="object"&&a.output!==null?a.output:{label:String(a.output)}}}catch{return null}}};var _o=class extends Pt{constructor(t={}){super(t)}async getAlertRule(t,r){return this.requestJson(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"GET"},{org_id:r??this.orgId})}async updateAlertRule(t,r,n){return this.requestJson(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)},{org_id:n??this.orgId})}async deleteAlertRule(t,r){await this.requestVoid(`/api/v1/monitoring/alerts/${encodeURIComponent(t)}`,{method:"DELETE"},{org_id:r??this.orgId})}};var go=class extends Pt{constructor(t={}){super(t)}async createCheckoutSession(t,r){return this.requestJson("/api/v1/settings/billing/checkout",{method:"POST",body:JSON.stringify(t)},{org_id:r??this.orgId})}async createPortalSession(t,r){return this.requestJson("/api/v1/settings/billing/portal",{method:"POST",body:JSON.stringify(t)},{org_id:r??this.orgId})}async updateBilling(t,r){return this.requestJson("/api/v1/settings/billing",{method:"PATCH",body:JSON.stringify(t)},{org_id:r??this.orgId})}async getUsageLimits(t){return this.requestJson("/api/v1/settings/usage-limits",{method:"GET"},{org_id:t??this.orgId})}async updateUsageLimits(t,r){return this.requestJson("/api/v1/settings/usage-limits",{method:"PUT",body:JSON.stringify(t)},{org_id:r??this.orgId})}async getIntegration(t,r){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"GET"},{org_id:r??this.orgId})}async updateIntegration(t,r,n){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(r)},{org_id:n??this.orgId})}async deleteIntegration(t,r){await this.requestVoid(`/api/v1/settings/integrations/${encodeURIComponent(t)}`,{method:"DELETE"},{org_id:r??this.orgId})}async validateIntegration(t,r){return this.requestJson(`/api/v1/settings/integrations/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify({})},{org_id:r??this.orgId})}};var wo=class extends Pt{constructor(r){super(r);w(this,"getDeviceId");this.getDeviceId=r.getDeviceId}async createJob(r){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs`,{method:"POST",body:JSON.stringify(r)})}async jobStatus(r,n){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs/${encodeURIComponent(r)}/status`,{method:"POST",body:JSON.stringify(n)})}async jobComplete(r,n){return this.requestJson(`/api/v1/devices/${encodeURIComponent(this.requireDeviceId())}/training-jobs/${encodeURIComponent(r)}/complete`,{method:"POST",body:JSON.stringify(n)})}requireDeviceId(){let r=this.getDeviceId();if(!r)throw new U("DEVICE_NOT_REGISTERED","This operation requires a registered device ID.");return r}};var yo=class{constructor(t){this.control=t}async desiredState(){return this.control.fetchDesiredState()}async observedState(t=[]){await this.control.reportObservedState(t)}async sync(t={}){return this.control.sync(t)}};async function zs(e){let t=await crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);return Array.from(r).map(n=>n.toString(16).padStart(2,"0")).join("")}async function Uu(e,t){return await zs(e)===t.toLowerCase()}async function Eg(e,t){if(!await Uu(e,t))throw new U("MODEL_LOAD_FAILED","Model integrity check failed: SHA-256 hash mismatch. The downloaded model may be corrupted or tampered with.")}var MO="octomil-sync-meta",vo="models",xO=1,zu=class{constructor(){w(this,"dbPromise",null)}openDB(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,r)=>{let n=indexedDB.open(MO,xO);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(vo)||s.createObjectStore(vo,{keyPath:"modelId"})},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error)}),this.dbPromise)}async tx(t){return(await this.openDB()).transaction(vo,t).objectStore(vo)}async get(t){let r=await this.tx("readonly");return new Promise((n,s)=>{let a=r.get(t);a.onsuccess=()=>n(a.result??null),a.onerror=()=>s(a.error)})}async put(t){let r=await this.tx("readwrite");return new Promise((n,s)=>{let a=r.put(t);a.onsuccess=()=>n(),a.onerror=()=>s(a.error)})}async getAll(){let t=await this.tx("readonly");return new Promise((r,n)=>{let s=t.getAll();s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}async remove(t){let r=await this.tx("readwrite");return new Promise((n,s)=>{let a=r.delete(t);a.onsuccess=()=>n(),a.onerror=()=>s(a.error)})}},bo=class{constructor(t){w(this,"control");w(this,"cache");w(this,"intervalMs");w(this,"onEvent");w(this,"meta");w(this,"timer",null);w(this,"syncing",!1);this.control=t.control,this.cache=t.cache,this.intervalMs=t.intervalMs??3e5,this.onEvent=t.onEvent,this.meta=new zu}start(){this.stop(),this.sync(),this.intervalMs>0&&(this.timer=setInterval(()=>{this.sync()},this.intervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}get isRunning(){return this.timer!==null}async sync(){if(this.syncing)return;this.syncing=!0;let t=0,r=0,n=0;try{this.emit({type:"sync_start"});let s=await this.control.fetchDesiredState(),a=this.parseDesiredEntries(s);for(let o of a)try{let i=await this.reconcileEntry(o);i.downloaded&&t++,i.activated&&r++}catch(i){n++,this.emit({type:"download_error",modelId:o.modelId,error:String(i)})}await this.garbageCollect(s,a),await this.reportState(),this.emit({type:"sync_complete",downloaded:t,activated:r,errors:n})}catch(s){this.emit({type:"error",error:String(s)})}finally{this.syncing=!1}}async getLocalModels(){return this.meta.getAll()}async getModelMeta(t){return this.meta.get(t)}async activate(t){let r=await this.meta.get(t);if(!r)throw new U("MODEL_NOT_FOUND",`No local model found for ${t}`);r.status!=="active"&&(r.status="active",await this.meta.put(r),this.emit({type:"activate",modelId:t,version:r.modelVersion}))}parseDesiredEntries(t){return t.models}async reconcileEntry(t){let r=await this.meta.get(t.modelId);if(r&&r.modelVersion===t.desiredVersion&&r.status==="active")return{downloaded:!1,activated:!1};if(r&&r.modelVersion===t.desiredVersion&&r.status==="staged")return this.shouldActivate(t.activationPolicy)?(r.status="active",await this.meta.put(r),this.emit({type:"activate",modelId:t.modelId,version:t.desiredVersion}),{downloaded:!1,activated:!0}):{downloaded:!1,activated:!1};if(!t.artifactManifest?.downloadUrl)return{downloaded:!1,activated:!1};this.emit({type:"download_start",modelId:t.modelId});let n=await this.downloadArtifact(t.artifactManifest.downloadUrl);if(t.artifactManifest.sha256){let i=await zs(n);if(i!==t.artifactManifest.sha256.toLowerCase())throw new U("MODEL_LOAD_FAILED",`Integrity check failed for ${t.modelId}: expected ${t.artifactManifest.sha256}, got ${i}`)}let s=t.artifactManifest.downloadUrl;await this.cache.put(s,n),this.emit({type:"download_complete",modelId:t.modelId,sizeBytes:n.byteLength});let a=this.shouldActivate(t.activationPolicy),o={modelId:t.modelId,modelVersion:t.desiredVersion,bindingKey:t.bindingKey,useCase:t.useCase,deploymentId:t.deploymentId,deploymentKey:t.deploymentKey,modelName:t.modelName,modelRef:t.modelRef,artifactUrl:s,sha256:t.artifactManifest.sha256,installedAt:new Date().toISOString(),status:a?"active":"staged",sizeBytes:n.byteLength};return await this.meta.put(o),a&&this.emit({type:"activate",modelId:t.modelId,version:t.desiredVersion}),{downloaded:!0,activated:a}}shouldActivate(t){switch(t){case"immediate":case void 0:return!0;case"manual":return!1;case"next_launch":return!1;case"when_idle":return!0;default:return!0}}async downloadArtifact(t){let r;try{r=await fetch(t)}catch(n){throw new U("NETWORK_UNAVAILABLE",`Failed to download artifact from ${t}: ${String(n)}`,n)}if(!r.ok)throw new U("MODEL_LOAD_FAILED",`Artifact download failed: HTTP ${r.status}`);return r.arrayBuffer()}async garbageCollect(t,r){let n=new Set(t.gcEligibleArtifactIds??[]),s=new Set(r.map(o=>o.modelId)),a=await this.meta.getAll();for(let o of a)(n.has(o.modelId)||!s.has(o.modelId))&&(await this.cache.remove(o.artifactUrl),await this.meta.remove(o.modelId))}async reportState(){let r=(await this.meta.getAll()).map(n=>({modelId:n.modelId,status:n.status,version:n.modelVersion,bindingKey:n.bindingKey,useCase:n.useCase,deploymentId:n.deploymentId,deploymentKey:n.deploymentKey,modelName:n.modelName,modelRef:n.modelRef}));try{await this.control.reportObservedState(r)}catch{}}emit(t){this.onEvent?.(t)}};var kg=3e4,Mo=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"token",null);w(this,"deviceId",null);w(this,"refreshTimer",null);w(this,"disposed",!1);this.serverUrl=t.serverUrl,this.apiKey=t.apiKey}async bootstrap(t){this.ensureNotDisposed(),this.deviceId=await this.generateDeviceId();let r=this.collectDeviceInfo(),n=await this.request("/api/v1/devices/register",{method:"POST",body:JSON.stringify({org_id:t,device_id:this.deviceId,platform:"browser",info:r})});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Device registration failed: HTTP ${n.status}`);let s=await n.json();this.token={accessToken:s.token,refreshToken:s.refresh_token,expiresAt:new Date(s.expires_at).getTime()},this.scheduleRefresh()}async getToken(){if(this.ensureNotDisposed(),!this.token)throw new U("NETWORK_UNAVAILABLE","Not authenticated. Call bootstrap() first.");return this.isTokenExpiringSoon()&&await this.refreshToken(),this.token.accessToken}async refreshToken(){if(this.ensureNotDisposed(),!this.token)throw new U("NETWORK_UNAVAILABLE","No token to refresh. Call bootstrap() first.");let t=await this.request("/api/v1/auth/refresh",{method:"POST",body:JSON.stringify({refresh_token:this.token.refreshToken,device_id:this.deviceId})});if(!t.ok)throw this.token=null,new U("NETWORK_UNAVAILABLE",`Token refresh failed: HTTP ${t.status}`);let r=await t.json();this.token={accessToken:r.token,refreshToken:r.refresh_token,expiresAt:new Date(r.expires_at).getTime()},this.scheduleRefresh()}async revokeToken(){if(this.ensureNotDisposed(),!!this.token)try{await this.request("/api/v1/auth/revoke",{method:"POST",body:JSON.stringify({token:this.token.accessToken,device_id:this.deviceId})})}finally{this.clearState()}}get isAuthenticated(){return this.token!==null&&!this.isTokenExpired()}get currentDeviceId(){return this.deviceId}dispose(){this.disposed||(this.disposed=!0,this.clearRefreshTimer())}async request(t,r){let n={"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`};return fetch(`${this.serverUrl}${t}`,{...r,headers:{...n,...r.headers}})}isTokenExpired(){return this.token?Date.now()>=this.token.expiresAt:!0}isTokenExpiringSoon(){return this.token?Date.now()>=this.token.expiresAt-kg:!0}scheduleRefresh(){if(this.clearRefreshTimer(),!this.token)return;let t=Math.max(0,this.token.expiresAt-Date.now()-kg);this.refreshTimer=setTimeout(()=>{this.refreshToken().catch(()=>{})},t)}clearRefreshTimer(){this.refreshTimer!==null&&(clearTimeout(this.refreshTimer),this.refreshTimer=null)}clearState(){this.token=null,this.clearRefreshTimer()}async generateDeviceId(){let t=[typeof navigator<"u"?navigator.userAgent:"unknown",typeof screen<"u"?`${screen.width}x${screen.height}`:"0x0",typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",typeof navigator<"u"?navigator.language:"en"].join("|"),r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(a=>a.toString(16).padStart(2,"0")).join("")}collectDeviceInfo(){return{userAgent:typeof navigator<"u"?navigator.userAgent:"unknown",language:typeof navigator<"u"?navigator.language:"en",screenWidth:typeof screen<"u"?screen.width:0,screenHeight:typeof screen<"u"?screen.height:0,timezone:typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:"UTC",webgpu:typeof navigator<"u"&&"gpu"in navigator}}ensureNotDisposed(){if(this.disposed)throw new U("CANCELLED","DeviceAuth has been disposed.")}};var xo=class extends Pt{constructor(t={}){super(t)}async manifest(t){return this.requestJson(`/api/v1/artifacts/${encodeURIComponent(t)}/manifest`,{method:"GET"})}async downloadUrls(t,r){return this.requestJson(`/api/v1/artifacts/${encodeURIComponent(t)}/download-urls`,{method:"POST",body:JSON.stringify(r)})}};function TO(e){return e.filter(t=>t.type==="tool_call"&&!!t.toolCall).map(t=>t.toolCall)}function EO(e){return{role:"assistant",content:e.map(t=>({type:"tool_call",toolCall:t}))}}var To=class{constructor(t,r,n=10){w(this,"responses");w(this,"executor");w(this,"maxIterations");this.responses=t,this.executor=r,this.maxIterations=n}async run(t){let r=this.normalizeInput(t.input);for(let n=0;n<this.maxIterations;n++){let s=await this.responses.create({...t,input:r}),a=TO(s.output);if(a.length===0)return s;r.push(EO(a));for(let o of a){let i;try{i=await this.executor.execute(o)}catch(l){i={toolCallId:o.id,content:l instanceof Error?`Error: ${l.message}`:"Error",isError:!0}}r.push({role:"tool",toolCallId:i.toolCallId,content:i.content})}}return this.responses.create({...t,input:r,tools:[]})}normalizeInput(t){return typeof t=="string"?[{role:"user",content:t}]:t.every(r=>"role"in r)?t.map(r=>({...r})):[{role:"user",content:t}]}};var oz="Qwen/Qwen3-0.6B",iz="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.2/dist/",WI=new Map;function HI(e={}){let t=lz(e);return{async create(r){let n=await uz(r,t);return Mz(r,t.model,n)},async*stream(r){let n=await this.create(r),s=n.output[0];s?.type==="tool_call"?yield{type:"tool_call_delta",index:0,id:s.toolCall?.id,name:s.toolCall?.name,argumentsDelta:s.toolCall?.arguments}:s?.type==="text"&&s.text&&(yield{type:"text_delta",delta:s.text}),yield{type:"done",response:n}}}}function lz(e={}){let t=e.model??oz,r=e.runtimeModel??cz(t);return{model:t,runtimeModel:r,device:e.device??"auto",dtype:e.dtype??"q4",maxNewTokens:e.maxNewTokens??128,maxInputChars:e.maxInputChars??4e3,temperature:e.temperature??0,topP:e.topP??.95,repetitionPenalty:e.repetitionPenalty??1.05,ortWasmBaseUrl:_z(e.ortWasmBaseUrl)??iz,useBrowserCache:e.useBrowserCache??!1}}function cz(e){return e.startsWith("onnx-community/")?e:`onnx-community/${e.replace(/^Qwen\//,"")}-ONNX`}async function uz(e,t){let r=await dz(t),n=gz(e,t.maxInputChars),s=mz(r,n),a=await r(s,{max_new_tokens:e.maxOutputTokens??t.maxNewTokens,temperature:e.temperature??t.temperature,top_p:e.topP??t.topP,repetition_penalty:t.repetitionPenalty,do_sample:(e.temperature??t.temperature)>0,return_full_text:!1});return bz(a)}async function dz(e){let t=await hz(e.device),r=JSON.stringify([e.runtimeModel,t,e.dtype]),n=WI.get(r);return n||(n=(async()=>{let{pipeline:s}=await pz(e);return s("text-generation",e.runtimeModel,{device:t,dtype:e.dtype})})(),WI.set(r,n)),n}async function pz(e){let t=await Promise.resolve().then(()=>(qI(),jI));t.env&&(t.env.useBrowserCache=e.useBrowserCache);let r=t.env?.backends?.onnx?.wasm;return r&&(r.wasmPaths=e.ortWasmBaseUrl,r.proxy=!1),t}var tm=null;async function hz(e){if(e==="webgpu"||e==="wasm")return e;if(tm)return tm;let t=await fz();return tm=t,t}async function fz(){try{if(typeof navigator>"u"||!("gpu"in navigator))return"wasm";let t=await navigator.gpu.requestAdapter();if(!t)return"wasm";let r=await t.requestDevice(),n=r.createShaderModule({code:`@group(0) @binding(0) var<storage, read_write> out: array<f32>;
38
+ @compute @workgroup_size(1)
39
+ fn main() { out[0] = 42.0; }`}),s=r.createBuffer({size:4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),a=r.createBuffer({size:4,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),o=r.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),i=r.createPipelineLayout({bindGroupLayouts:[o]}),l=r.createComputePipeline({layout:i,compute:{module:n,entryPoint:"main"}}),c=r.createBindGroup({layout:o,entries:[{binding:0,resource:{buffer:s}}]}),u=r.createCommandEncoder(),p=u.beginComputePass();p.setPipeline(l),p.setBindGroup(0,c),p.dispatchWorkgroups(1),p.end(),u.copyBufferToBuffer(s,0,a,0,4),r.queue.submit([u.finish()]),await a.mapAsync(GPUMapMode.READ);let m=new Float32Array(a.getMappedRange())[0];return a.unmap(),s.destroy(),a.destroy(),r.destroy(),m===42?"webgpu":"wasm"}catch{return"wasm"}}function mz(e,t){let r=e.tokenizer?.apply_chat_template;return r?r.call(e.tokenizer,t,{tokenize:!1,add_generation_prompt:!0,enable_thinking:!1}):t}function _z(e){if(e)return e.endsWith("/")?e:`${e}/`}function gz(e,t){let r=wz(e.tools),s=Tz(e.input).flatMap(a=>yz(a)).filter(a=>a!==null);return s[0]?.role==="system"?s[0]={role:"system",content:`${r}
40
+
41
+ ${s[0].content}`.trim()}:s.unshift({role:"system",content:r}),Ez(s,t)}function wz(e){let t=["You are Octomil's local browser agent runtime.","Do not reveal chain-of-thought or emit <think> tags.","Answer directly when no tool is needed."];return!e||e.length===0?t.join(`
42
+ `):[...t,"When a tool is required, respond with exactly one XML block in this form and no extra prose:",'<tool_call>{"name":"tool_name","arguments":{}}</tool_call>',"Use one of these tools:",...e.map(r=>`- ${r.function.name}: ${r.function.description??"No description provided"}; parameters=${JSON.stringify(r.function.parameters??{})}`)].join(`
43
+ `)}function yz(e){if(!e||typeof e!="object"||!("role"in e))return[];switch(e.role){case"system":return[{role:"system",content:rm(e.content)}];case"user":return[{role:"user",content:rm(e.content)}];case"assistant":return[{role:"assistant",content:vz(e.content)}];case"tool":return[{role:"user",content:`Tool result for ${e.toolCallId??"tool"}:
44
+ ${rm(e.content)}`}];default:return[]}}function vz(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>!t||typeof t!="object"||!("type"in t)?"":t.type==="text"?typeof t.text=="string"?t.text:"":t.type==="tool_call"&&t.toolCall?`<tool_call>${JSON.stringify({name:t.toolCall.name,arguments:KI(t.toolCall.arguments)??t.toolCall.arguments})}</tool_call>`:"").filter(Boolean).join(`
45
+ `):""}function rm(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>!t||typeof t!="object"||!("type"in t)?"":t.type==="text"?t.text??"":t.type==="image"?"[image omitted]":t.type==="audio"?"[audio omitted]":t.type==="video"?"[video omitted]":t.type==="file"?"[file omitted]":"").filter(Boolean).join(`
46
+ `):""}function bz(e){let t=Array.isArray(e)?e[0]:e,r=t?.generated_text??t;if(typeof r=="string")return r;if(Array.isArray(r)){let n=r.at(-1);if(typeof n=="string")return n;if(n&&typeof n=="object"&&"content"in n)return typeof n.content=="string"?n.content:""}return r&&typeof r=="object"&&"content"in r?typeof r.content=="string"?r.content:"":String(r??"")}function Mz(e,t,r){let n=Az(r).trim(),s=xz(n,e.tools),a=s?[{type:"tool_call",toolCall:{id:Sz(),name:s.name,arguments:JSON.stringify(s.arguments)}}]:[{type:"text",text:n}];return{id:qr(),model:t,output:a,finishReason:s?"tool_calls":"stop"}}function xz(e,t){if(!t||t.length===0)return null;let r=new Set(t.map(s=>s.function.name)),n=[...e.matchAll(/<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/gi),...e.matchAll(/```json\s*([\s\S]*?)\s*```/gi)].map(s=>s[1]?.trim()).filter(Boolean);for(let s of n){let a=KI(s);if(!Cz(a))continue;let o=typeof a.name=="string"?a.name:null;if(!o||!r.has(o))continue;let i=a.arguments&&typeof a.arguments=="object"?a.arguments:{};return{name:o,arguments:i}}return null}function KI(e){try{return JSON.parse(e)}catch{return null}}function Tz(e){return typeof e=="string"?[{role:"user",content:e}]:Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&"role"in t)?e:[{role:"user",content:e}]}function Ez(e,t){if(e.length<=1||t<=0)return e;let r=e[0]?.role==="system"?e[0]:null,n=Math.max(t-(r?.content.length??0),512),s=r?e.slice(1):e.slice(),a=[],o=0;for(let i=s.length-1;i>=0;i-=1){let l=s[i];if(!l)continue;let c=l.content.length;if(o+c<=n){a.unshift(l),o+=c;continue}a.length===0&&a.unshift({role:l.role,content:kz(l.content,n)});break}return r?[r,...a]:a}function kz(e,t){return e.length<=t?e:`[truncated]
47
+ ${e.slice(-Math.max(t-32,0)).trim()}`.trim()}function Cz(e){return!!e&&typeof e=="object"}function Az(e){return e.replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<think>[\s\S]*$/gi,"").replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/<thinking>[\s\S]*$/gi,"").trim()}function Sz(){return`call_${Math.random().toString(36).slice(2,10)}`}var Gc=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"telemetry");this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.telemetry=t.telemetry}async*stream(t,r,n={}){let s=new AbortController,a=n.signal?this.combineSignals(n.signal,s.signal):s.signal,o=`${this.serverUrl}/api/v1/models/${encodeURIComponent(t)}/stream`,i={"Content-Type":"application/json",Accept:"text/event-stream"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let l=performance.now(),c=null,u=0,p=0;this.telemetry?.reportInferenceStarted(t,{modality:n.modality??"text"});let f;try{f=await fetch(o,{method:"POST",headers:i,body:JSON.stringify({input:r,modality:n.modality??"text",...n.params}),signal:a})}catch(M){throw this.telemetry?.reportInferenceFailed(t,"network_error",String(M)),new U("NETWORK_UNAVAILABLE",`Streaming request failed: ${String(M)}`,M)}if(!f.ok)throw new U("INFERENCE_FAILED",`Streaming inference failed: HTTP ${f.status}`);if(!f.body)throw new U("INFERENCE_FAILED","Server did not return a streaming body.");let m=f.body.getReader(),y=new TextDecoder,v="";try{for(;;){let{done:M,value:T}=await m.read();if(M)break;v+=y.decode(T,{stream:!0});let A=v.split(`
48
+ `);v=A.pop()??"";for(let C of A){if(!C.startsWith("data: "))continue;let S=C.slice(6).trim();if(S==="[DONE]")break;let O;try{O=JSON.parse(S)}catch{continue}u++,p+=S.length,c===null&&(c=performance.now()-l,this.telemetry?.reportInferenceChunk(t,{chunkIndex:0,ttfc:!0,durationMs:c})),this.telemetry?.reportChunkProduced(t,u-1),yield O}}}finally{m.releaseLock()}let x=performance.now()-l;return this.telemetry?.reportInferenceCompleted(t,x,{chunkCount:u,totalBytes:p,ttfcMs:c??x}),{totalChunks:u,totalBytes:p,durationMs:x,ttfcMs:c??x}}combineSignals(...t){let r=new AbortController;for(let n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>r.abort(n.reason),{once:!0})}return r.signal}};var ja=class{constructor(){w(this,"plugins",new Map)}register(t){this.plugins.set(t.name,t)}remove(t){return this.plugins.delete(t)}get(t){return this.plugins.get(t)}get engines(){return[...this.plugins.keys()]}reset(){this.plugins.clear()}async detectAll(t){let r=[];for(let n of this.sortedPlugins()){let s=await n.detect(),a=t?n.supportsModel(t):!0,o=s?await n.detectInfo():"";r.push({engine:n.name,available:s&&a,info:o})}return r}async benchmarkAll(t,r){let s=(await this.detectAll(t)).filter(o=>o.available),a=[];for(let o of s){let l=await this.plugins.get(o.engine).benchmark(t,r);a.push({engine:o.engine,result:l})}return a.sort((o,i)=>i.result.tokens_per_second-o.result.tokens_per_second),a}selectBest(t){return t.find(r=>r.result.error==null)??null}async autoSelect(t,r){let n=await this.benchmarkAll(t,r);return this.selectBest(n)}sortedPlugins(){return[...this.plugins.values()].sort((t,r)=>t.priority-r.priority)}};var qa=class{static computeDelta(t,r){let n={};for(let s of Object.keys(t)){let a=t[s],o=r[s];if(!a||!o||a.length!==o.length)throw new U("INVALID_INPUT",`Weight dimension mismatch for "${s}".`);let i=new Float32Array(a.length);for(let l=0;l<a.length;l++)i[l]=o[l]-a[l];n[s]=i}return n}static applyDelta(t,r){let n={};for(let s of Object.keys(t)){let a=t[s],o=r[s];if(!a)continue;if(!o||a.length!==o.length){n[s]=new Float32Array(a);continue}let i=new Float32Array(a.length);for(let l=0;l<a.length;l++)i[l]=a[l]+o[l];n[s]=i}return n}static l2Norm(t){let r=0;for(let n of Object.values(t))if(n)for(let s=0;s<n.length;s++)r+=n[s]*n[s];return Math.sqrt(r)}},jc=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"deviceId");w(this,"telemetry");this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.deviceId=t.deviceId,this.telemetry=t.telemetry}async getTrainingRound(t){let r=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/current`);if(!r.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to fetch training round: HTTP ${r.status}`);return await r.json()}async joinRound(t,r){let n=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/${encodeURIComponent(r)}/join`,{method:"POST",body:JSON.stringify({device_id:this.deviceId})});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to join round: HTTP ${n.status}`)}async offers(){let t=await this.request(`/api/v1/federation/rounds/offers?deviceId=${encodeURIComponent(this.deviceId)}`,{method:"GET"});if(!t.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to fetch round offers: HTTP ${t.status}`);return await t.json()}async join(t,r={}){let n=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({deviceId:this.deviceId,...r})});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to join federation round: HTTP ${n.status}`);return await n.json()}async plan(t){let r=await this.request(`/api/v1/federation/plans/${encodeURIComponent(t)}`,{method:"GET"});if(!r.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to fetch federation plan: HTTP ${r.status}`);return await r.json()}async heartbeat(t,r={}){let n=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/heartbeat`,{method:"POST",body:JSON.stringify({deviceId:this.deviceId,...r})});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to send federation heartbeat: HTTP ${n.status}`);return await n.json()}async uploadInitiate(t,r){let n=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/updates/initiate`,{method:"POST",body:JSON.stringify(r)});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to initiate upload: HTTP ${n.status}`);return await n.json()}async uploadComplete(t,r,n){let s=await this.request(`/api/v1/federation/rounds/${encodeURIComponent(t)}/updates/${encodeURIComponent(r)}/complete`,{method:"POST",body:JSON.stringify(n)});if(!s.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to complete upload: HTTP ${s.status}`);return await s.json()}async train(t,r){let n=performance.now(),s=this.cloneWeights(t);for(let l=0;l<r.epochs;l++)s=(await r.onTrainStep(s,{epoch:l,batchSize:r.batchSize,learningRate:r.learningRate})).weights;let a=qa.computeDelta(t,s),o=performance.now()-n,i=r.modelId??"unknown";return this.telemetry?.reportTrainingStarted(i,"local"),this.telemetry?.reportTrainingCompleted(i,"local",o),{finalWeights:s,delta:a}}async submitUpdate(t,r,n,s){let a={};for(let[i,l]of Object.entries(n))l&&(a[i]={data:Array.from(l),shape:[l.length]});let o=await this.request(`/api/v1/federations/${encodeURIComponent(t)}/rounds/${encodeURIComponent(r)}/submit`,{method:"POST",body:JSON.stringify({device_id:this.deviceId,delta:a,metrics:s})});if(!o.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to submit update: HTTP ${o.status}`)}async request(t,r){let n={"Content-Type":"application/json"};return this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`),fetch(`${this.serverUrl}${t}`,{...r,headers:{...n,...r?.headers}})}cloneWeights(t){let r={};for(let[n,s]of Object.entries(t))s&&(r[n]=new Float32Array(s));return r}};var Wc=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.apiKey=t.apiKey}async descriptive(t){return this.post("/api/v1/analytics/descriptive",{variable:t.variable,group_by:t.groupBy??"device_group",group_ids:t.groupIds??null,include_percentiles:t.includePercentiles??!0,filters:t.filters?qc(t.filters):null})}async tTest(t){return this.post("/api/v1/analytics/t-test",{variable:t.variable,group_a:t.groupA,group_b:t.groupB,confidence_level:t.confidenceLevel??.95,filters:t.filters?qc(t.filters):null})}async chiSquare(t){return this.post("/api/v1/analytics/chi-square",{variable_1:t.variable1,variable_2:t.variable2,group_ids:t.groupIds??null,confidence_level:t.confidenceLevel??.95,filters:t.filters?qc(t.filters):null})}async anova(t){return this.post("/api/v1/analytics/anova",{variable:t.variable,group_by:t.groupBy??"device_group",group_ids:t.groupIds??null,confidence_level:t.confidenceLevel??.95,post_hoc:t.postHoc??!0,filters:t.filters?qc(t.filters):null})}async listQueries(t=50,r=0){let n=new URLSearchParams({limit:String(t),offset:String(r)});return this.get(`/api/v1/analytics/queries?${n.toString()}`)}async getQuery(t){return this.get(`/api/v1/analytics/queries/${encodeURIComponent(t)}`)}buildHeaders(){let t={Accept:"application/json","Content-Type":"application/json"};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async post(t,r){let n=`${this.serverUrl}${t}`,s=await fetch(n,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(r)});if(!s.ok)throw new U("NETWORK_UNAVAILABLE",`Analytics request failed: HTTP ${s.status}`);return await s.json()}async get(t){let r=`${this.serverUrl}${t}`,n=await fetch(r,{method:"GET",headers:this.buildHeaders()});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Analytics request failed: HTTP ${n.status}`);return await n.json()}};function qc(e){return{start_time:e.startTime??null,end_time:e.endTime??null,device_platform:e.devicePlatform??null,min_sample_count:e.minSampleCount??null}}var Wa=class{constructor(){w(this,"keyPair",null)}async generateKeyPair(){return this.keyPair=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),{publicKey:await crypto.subtle.exportKey("jwk",this.keyPair.publicKey)}}async deriveSharedSecret(t){if(!this.keyPair)throw new U("INVALID_INPUT","Call generateKeyPair() first.");let r=await crypto.subtle.importKey("jwk",t,{name:"ECDH",namedCurve:"P-256"},!1,[]);return crypto.subtle.deriveBits({name:"ECDH",public:r},this.keyPair.privateKey,256)}async createMask(t,r){let n=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveBits"]),s=r*4*8,a=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:new TextEncoder().encode("octomil-secagg-mask")},n,Math.min(s,8160)),o=new Float32Array(r),i=new Float32Array(a);for(let l=0;l<r;l++)o[l]=i[l%i.length];return o}maskUpdate(t,r){let n={};for(let[s,a]of Object.entries(t)){if(!a)continue;let o=new Float32Array(a),i=r.get(s);if(i)for(let l=0;l<o.length;l++)o[l]=o[l]+(i[l]??0);n[s]=o}return n}unmask(t,r){let n={};for(let[s,a]of Object.entries(t)){if(!a)continue;let o=new Float32Array(a),i=r.get(s);if(i)for(let l=0;l<o.length;l++)o[l]=o[l]-(i[l]??0);n[s]=o}return n}},Ut=2147483647;function QI(e,t,r){let n=1;for(e=e%r;t>0;)t%2===1&&(n=Number(BigInt(n)*BigInt(e)%BigInt(r))),t=Math.floor(t/2),e=Number(BigInt(e)*BigInt(e)%BigInt(r));return n}function Iz(e,t){return QI(e,t-2,t)}function nm(e,t,r){let n=[e%Ut];for(let a=1;a<t;a++){let o=new Uint32Array(1);crypto.getRandomValues(o),n.push(o[0]%Ut)}let s=[];for(let a=1;a<=r;a++){let o=0;for(let i=0;i<n.length;i++)o=Number((BigInt(o)+BigInt(n[i])*BigInt(QI(a,i,Ut)))%BigInt(Ut));s.push({x:a,y:o})}return s}function sm(e){let t=0,r=e.length;for(let n=0;n<r;n++){let s=1,a=1;for(let i=0;i<r;i++)n!==i&&(s=Number(BigInt(s)*BigInt(Ut-e[i].x)%BigInt(Ut)),a=Number(BigInt(a)*BigInt((e[n].x-e[i].x+Ut)%Ut)%BigInt(Ut)));let o=Number(BigInt(s)*BigInt(Iz(a,Ut))%BigInt(Ut));t=Number((BigInt(t)+BigInt(e[n].y)*BigInt(o))%BigInt(Ut))}return t}var Hc=class extends Wa{constructor(r){super();w(this,"threshold");this.threshold=r}splitSecret(r,n){return nm(r,this.threshold,n)}reconstructSecret(r){if(r.length<this.threshold)throw new U("INVALID_INPUT",`Need at least ${this.threshold} shares, got ${r.length}.`);return sm(r.slice(0,this.threshold))}};function JI(e,t){let r=0;for(let o of Object.values(e))if(o)for(let i=0;i<o.length;i++)r+=o[i]*o[i];let n=Math.sqrt(r);if(n<=t)return e;let s=t/n,a={};for(let[o,i]of Object.entries(e)){if(!i)continue;let l=new Float32Array(i.length);for(let c=0;c<i.length;c++)l[c]=i[c]*s;a[o]=l}return a}function XI(e,t,r,n){let s=r*Math.sqrt(2*Math.log(1.25/n))/t,a={};for(let[o,i]of Object.entries(e)){if(!i)continue;let l=new Float32Array(i.length);for(let c=0;c<i.length;c++)l[c]=i[c]+Pz()*s;a[o]=l}return a}function Pz(){let e,t;do e=Math.random(),t=Math.random();while(e===0);return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*t)}function YI(e,t=8){let r=t===8?127:32767,n={};for(let[s,a]of Object.entries(e)){if(!a)continue;let o=0;for(let c=0;c<a.length;c++){let u=Math.abs(a[c]);u>o&&(o=u)}let i=o>0?o/r:1,l=t===8?new Int8Array(a.length):new Int16Array(a.length);for(let c=0;c<a.length;c++)l[c]=Math.round(a[c]/i);n[s]={data:l,scale:i,zeroPoint:0}}return n}function ZI(e){let t={};for(let[r,n]of Object.entries(e)){if(!n)continue;let s=new Float32Array(n.data.length);for(let a=0;a<n.data.length;a++)s[a]=(n.data[a]-n.zeroPoint)*n.scale;t[r]=s}return t}var Rz="octomil-gradients",Dr="gradients";var Kc=class{constructor(){w(this,"dbPromise",null)}openDb(){return this.dbPromise?this.dbPromise:(this.dbPromise=new Promise((t,r)=>{let n=indexedDB.open(Rz,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(Dr)||s.createObjectStore(Dr,{keyPath:"roundId"}).createIndex("submitted","submitted",{unique:!1})},n.onsuccess=()=>t(n.result),n.onerror=()=>r(n.error)}),this.dbPromise)}async store(t){let r=await this.openDb();return new Promise((n,s)=>{let a=r.transaction(Dr,"readwrite");a.objectStore(Dr).put(t),a.oncomplete=()=>n(),a.onerror=()=>s(a.error)})}async get(t){let r=await this.openDb();return new Promise((n,s)=>{let o=r.transaction(Dr,"readonly").objectStore(Dr).get(t);o.onsuccess=()=>n(o.result??null),o.onerror=()=>s(o.error)})}async listPending(){let t=await this.openDb();return new Promise((r,n)=>{let o=t.transaction(Dr,"readonly").objectStore(Dr).index("submitted").getAll(IDBKeyRange.only(!1));o.onsuccess=()=>r(o.result),o.onerror=()=>n(o.error)})}async markSubmitted(t){let r=await this.get(t);r&&(r.submitted=!0,await this.store(r))}};var Qc=class{constructor(t){w(this,"serverUrl");w(this,"apiKey");w(this,"cacheTtlMs");w(this,"telemetry");w(this,"experimentsCache",null);this.serverUrl=t.serverUrl,this.apiKey=t.apiKey,this.cacheTtlMs=t.cacheTtlMs??5*60*1e3,this.telemetry=t.telemetry}async getActiveExperiments(){if(this.experimentsCache&&Date.now()-this.experimentsCache.fetchedAt<this.cacheTtlMs)return this.experimentsCache.experiments;let t=`${this.serverUrl}/api/v1/experiments?status=active`,r={Accept:"application/json"};this.apiKey&&(r.Authorization=`Bearer ${this.apiKey}`);let n=await fetch(t,{headers:r});if(!n.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to fetch experiments: HTTP ${n.status}`);let s=await n.json();return this.experimentsCache={experiments:s.experiments,fetchedAt:Date.now()},s.experiments}async getExperimentConfig(t){let r=`${this.serverUrl}/api/v1/experiments/${encodeURIComponent(t)}`,n={Accept:"application/json"};this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`);let s=await fetch(r,{headers:n});if(!s.ok)throw new U("NETWORK_UNAVAILABLE",`Failed to fetch experiment: HTTP ${s.status}`);return await s.json()}getVariant(t,r){if(t.variants.length===0)return null;let n=Oz(r+t.id),s=0;for(let a of t.variants)if(s+=a.trafficPercentage,n<s)return a;return t.variants[t.variants.length-1]??null}isEnrolled(t,r){return this.getVariant(t,r)!==null}async resolveModelExperiment(t,r){let n=await this.getActiveExperiments();for(let s of n){if(!s.variants.some(i=>i.modelId===t))continue;let o=this.getVariant(s,r);if(o)return{experiment:s,variant:o}}return null}async trackMetric(t,r,n,s){let a=`${this.serverUrl}/api/v1/experiments/${encodeURIComponent(t)}/metrics`,o={"Content-Type":"application/json"};this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`),await fetch(a,{method:"POST",headers:o,body:JSON.stringify({metric_name:r,value:n,device_id:s,timestamp:Date.now()})}),this.telemetry?.reportExperimentMetric(t,r,n)}clearCache(){this.experimentsCache=null}};function Oz(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return Math.abs(t)%100}var Jc=(s=>(s.NotCached="not_cached",s.Downloading="downloading",s.Ready="ready",s.Error="error",s))(Jc||{});var Xc=(s=>(s.Flagship="flagship",s.High="high",s.Mid="mid",s.Low="low",s))(Xc||{});var Yc=(s=>(s.Stop="stop",s.ToolCalls="tool_calls",s.Length="length",s.ContentFilter="content_filter",s))(Yc||{});var Zc=(s=>(s.Stable="stable",s.Beta="beta",s.Experimental="experimental",s.Compatibility="compatibility",s))(Zc||{});function Lz(e){return e.error==null}return lO(Fz);})();
44
49
  /*! Bundled license information:
45
50
 
46
- @huggingface/transformers/dist/transformers.web.js:
47
- (*!*****************************!*\
48
- !*** ./src/transformers.js ***!
49
- \*****************************)
51
+ onnxruntime-web/dist/ort.webgpu.bundle.min.mjs:
52
+ (*!
53
+ * ONNX Runtime Web v1.25.0-dev.20260307-d626b568e0
54
+ * Copyright (c) Microsoft Corporation. All rights reserved.
55
+ * Licensed under the MIT License.
56
+ *)
50
57
  */
51
58
  var Octomil=__Octomil_ns.Octomil;Object.assign(Octomil,__Octomil_ns);
52
59
  //# sourceMappingURL=octomil.min.js.map