@p2arthur/webinference-sdk 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // src/image.worker.js?worker&inline
2
- var e = "(function(){var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)},n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){\n/*!\n* ONNX Runtime Web v1.31.1\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\nif(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of \"`+e+`\" is not supported`)}),s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},l=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},u=e=>l(n({},`__esModule`,{value:!0}),e),d,f,p,m,h,g,_,v=s(()=>{\"use strict\";d=/* @__PURE__ */ new Map,f=[],p=/* @__PURE__ */ new WeakMap,m=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend \"${e}\" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}}else throw TypeError(`not a valid backend`)},h=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{if(!n){let n=t.backend,r=p.get(n);t.initPromise=r?r.then(async()=>n.init(e),async()=>n.init(e)):n.init(e),p.set(n,t.initPromise)}return await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},g=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await h(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider \"${e}\" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]},_=async()=>{let e=[];for(let t of f){if(typeof d.get(t).backend.createLoraAdapterHandler!=`function`)continue;let n=await h(t);if(typeof n!=`string`)return n;e.push({name:t,err:n})}let t=e.length===0?``:` ERR: ${e.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`;throw Error(`no available backend supports LoRA adapters.${t}`)}}),y=s(()=>{\"use strict\";v()}),b,x=s(()=>{\"use strict\";b=`1.31.1`}),S,C,ee=s(()=>{\"use strict\";x(),S=`warning`,C={wasm:{},webgl:{},webgpu:{},versions:{common:b},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},Object.defineProperty(C,\"logLevel\",{enumerable:!0})}),w,te=s(()=>{\"use strict\";ee(),w=C}),ne,re,ie,ae,oe,se,ce=s(()=>{\"use strict\";ee(),ne=(e,t)=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.timeStamp(`${e}::ORT::${t}`)},re=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\\r\\n|\\r|\\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ne(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},ie=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||re(`BEGIN`,e)},ae=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||re(`END`,e)},oe=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.time(`ORT::${e}`)},se=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.timeEnd(`ORT::${e}`)}}),le,ue=s(()=>{\"use strict\";v(),ce(),le=class e{constructor(e,t){this.backend=e,this.handler=t}static async create(t){if(ie(),typeof t!=`string`&&!(t instanceof Uint8Array))throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let n=await _(),r=await n.createLoraAdapterHandler(t);return ae(),new e(n,r)}async release(){return this.handler.dispose()}}}),T,de,fe=s(()=>{\"use strict\";T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},de=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),pe,me,he,ge,_e,ve,ye=s(()=>{\"use strict\";ke(),pe=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new Oe(`float32`,u,[1,4,n,r]):new Oe(`float32`,u,[1,3,n,r])},me=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,pe(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(pe(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return pe(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},he=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Oe({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ge=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Oe({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},_e=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Oe({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ve=(e,t,n)=>new Oe({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),be,xe,Se,Ce,we=s(()=>{\"use strict\";be=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),xe=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Se=!1,Ce=()=>{if(!Se){Se=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(be.set(`int64`,BigInt64Array),xe.set(BigInt64Array,`int64`)),t&&(be.set(`uint64`,BigUint64Array),xe.set(BigUint64Array,`uint64`)),r?(be.set(`float16`,n),xe.set(n,`float16`)):be.set(`float16`,Uint16Array)}}}),Te,Ee,De=s(()=>{\"use strict\";ke(),Te=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},Ee=(e,t)=>{switch(e.location){case`cpu`:return new Oe(e.type,e.data,t);case`cpu-pinned`:return new Oe({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Oe({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Oe({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Oe({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Oe,ke=s(()=>{\"use strict\";fe(),ye(),we(),De(),Oe=class{constructor(e,t,n){Ce();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=be.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=be.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=xe.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Te(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return me(e,t)}static fromTexture(e,t){return he(e,t)}static fromGpuBuffer(e,t){return ge(e,t)}static fromMLTensor(e,t){return _e(e,t)}static fromPinnedBuffer(e,t,n){return ve(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return de(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return Ee(this,e)}}}),Ae,je=s(()=>{\"use strict\";ke(),Ae=Oe}),Me,Ne=s(()=>{\"use strict\";v(),ue(),je(),ce(),Me=class e{constructor(e,t){this.handler=e,this.backend=t}async run(e,t,n){ie(),oe(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof Ae||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof Ae)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof Ae)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o;if(i.activeLoraAdapters!==void 0){if(!Array.isArray(i.activeLoraAdapters))throw TypeError(`'activeLoraAdapters' must be an array.`);o=i.activeLoraAdapters.map(e=>{if(!(e instanceof le))throw TypeError(`'activeLoraAdapters' must be an array of LoraAdapter objects.`);if(e.backend!==this.backend)throw Error(`LoRA adapter was created by a different backend than the session.`);return e.handler})}let s=await this.handler.run(e,r,i,o),c={};for(let e in s)if(Object.hasOwnProperty.call(s,e)){let t=s[e];c[e]=t instanceof Ae?t:new Ae(t.type,t.data,t.dims)}return se(`InferenceSession.run`),ae(),c}async release(){return this.handler.dispose()}static async create(t,n,r,i){ie(),oe(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await g(o),l=await s.createInferenceSessionHandler(a,c);return se(`InferenceSession.create`),ae(),new e(l,s)}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}}}),Pe,Fe=s(()=>{\"use strict\";Ne(),Pe=Me}),Ie,Le=s(()=>{\"use strict\";ue(),Ie=le}),Re=s(()=>{\"use strict\";}),ze=s(()=>{\"use strict\";}),Be=s(()=>{\"use strict\";}),Ve=s(()=>{\"use strict\";});c({},{InferenceSession:()=>Pe,LoraAdapter:()=>Ie,TRACE:()=>ne,TRACE_EVENT_BEGIN:()=>oe,TRACE_EVENT_END:()=>se,TRACE_FUNC_BEGIN:()=>ie,TRACE_FUNC_END:()=>ae,Tensor:()=>Ae,env:()=>w,registerBackend:()=>m});var He=s(()=>{\"use strict\";y(),te(),Fe(),Le(),je(),Re(),ze(),ce(),Be(),Ve()}),Ue=s(()=>{\"use strict\";}),We={};c(We,{default:()=>qe});var Ge,Ke,qe,Je=s(()=>{\"use strict\";Ln(),vt(),lt(),Ge=`ort-wasm-proxy-worker`,Ke=globalThis.self?.name===Ge,Ke&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:_t(n.wasm).then(()=>{bn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;xn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Tn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;En(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Dn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Pn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},In([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Fn(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),qe=Ke?null:e=>new Worker(e??Qe,{type:`module`,name:Ge})}),Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt=s(()=>{\"use strict\";Ue(),Ye=typeof location>`u`?void 0:location.origin,Xe=self.location.href>`file:`&&self.location.href<`file;`,Ze=()=>Xe?new URL(new URL(`ort.webgpu.min.mjs`,self.location.href).href,Ye).href:self.location.href,Qe=Ze(),$e=()=>{if(Qe&&!Qe.startsWith(`blob:`))return Qe.substring(0,Qe.lastIndexOf(`/`)+1)},et=(e,t)=>{try{let n=t??Qe;return(n?new URL(e,n):new URL(e)).origin===Ye}catch{return!1}},tt=(e,t)=>{let n=t??Qe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},nt=(e,t)=>`${t??`./`}${e}`,rt=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},it=async e=>(await import(\n/*webpackIgnore:true*/\n/*@vite-ignore*/\ne)).default,at=(Je(),u(We)).default,ot=async()=>{if(!Qe)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(et(Qe))return[void 0,at()];let e=await rt(Qe);return[e,at(e)]},st=void 0,ct=async(e,t,n,r)=>{let i=st&&!(e||t);if(i){if(Qe)i=et(Qe)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,st];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??tt(r,t),a=n&&i&&!et(i,t),o=a?await rt(i):i??nt(r,t);return[a?o:void 0,await it(o)]}}}),ut,dt,ft,pt,mt,ht,gt,_t,E,vt=s(()=>{\"use strict\";lt(),dt=!1,ft=!1,pt=!1,mt=()=>{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}},ht=()=>{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}},gt=()=>{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}},_t=async e=>{if(dt)return Promise.resolve();if(ft)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(pt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ft=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!gt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!ht())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=mt();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, 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=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await ct(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=$e();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ft=!1,dt=!0,ut=t,e(),d&&URL.revokeObjectURL(d)},e=>{ft=!1,pt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},E=()=>{if(dt&&ut)return ut;throw Error(`WebAssembly is not initialized yet.`)}}),yt,bt,D,xt=s(()=>{\"use strict\";vt(),yt=(e,t)=>{let n=E(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},bt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)bt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},D=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),St,Ct=s(()=>{\"use strict\";vt(),xt(),St=(e,t)=>{let n=E(),r=0,i=[],a=e||{};try{if(e?.logSeverityLevel===void 0)a.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)a.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(a.terminate=!1);let o=0;e?.tag!==void 0&&(o=yt(e.tag,i)),r=n._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),r===0&&D(`Can't create run options.`),e?.extra!==void 0&&bt(e.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{let a=yt(e,i),o=yt(t,i);n._OrtAddRunConfigEntry(r,a,o)!==0&&D(`Can't set a run config entry: ${e} - ${t}.`)});for(let e of t)n._OrtRunOptionsAddActiveLoraAdapter(r,e)!==0&&D(`Can't add an active LoRA adapter.`);return[r,i]}catch(e){throw r!==0&&n._OrtReleaseRunOptions(r),i.forEach(e=>n._free(e)),e}}}),wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,Nt=s(()=>{\"use strict\";vt(),xt(),wt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},Tt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Et=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Dt=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);E()._OrtAddSessionConfigEntry(e,i,a)!==0&&D(`Can't set a session config entry: ${t} - ${n}.`)},Ot=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);e.push([i,a])},kt=9,At=()=>{let e=E(),t=e.stackSave();try{let t=e.stackAlloc(e.PTR_SIZE),n=e.stackAlloc(e.PTR_SIZE),r=e._OrtGetEpDevices(t,n);if(r===kt)return;r!==0&&D(`Can't get execution provider devices.`);let i=Number(e.getValue(t,`*`)),a=Number(e.getValue(n,`*`)),o=/* @__PURE__ */ new Map;for(let t=0;t<a;t++){let n=Number(e.getValue(i+t*e.PTR_SIZE,`*`)),r=e.UTF8ToString(e._OrtEpDevice_EpName(n)),a=o.get(r);a?a.push(n):o.set(r,[n])}return o}finally{e.stackRestore(t)}},jt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[],o;switch(r){case`webnn`:if(r=`WEBNN`,Dt(e,`session.disable_quant_qdq`,`1`,n),Dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Dt(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e=At();if(e!==void 0&&(r=`WebGpuExecutionProvider`,o=e.get(r),o===void 0)){let t=[...e.keys()].join(`, `)||`(none)`;throw Error(`no execution provider device is registered for: ${r}. registered: ${t}.`)}let s;if(typeof i!=`string`){let e=i;if(e.device){if(typeof GPUDevice<`u`&&e.device instanceof GPUDevice)s=e.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:r}=t;if(typeof r==`boolean`&&r&&Ot(a,`enableGraphCapture`,`1`,n),typeof e.preferredLayout==`string`&&Ot(a,`preferredLayout`,e.preferredLayout,n),e.forceCpuNodeNames){let t=Array.isArray(e.forceCpuNodeNames)?e.forceCpuNodeNames:[e.forceCpuNodeNames];Ot(a,`forceCpuNodeNames`,t.join(`\n`),n)}e.validationMode&&Ot(a,`validationMode`,e.validationMode,n),typeof e.enableMatmulFp32Accumulation==`boolean`&&Ot(a,`enableMatmulFp32Accumulation`,e.enableMatmulFp32Accumulation?`1`:`0`,n);for(let t of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let r=e[t];if(r){if(r!==`disabled`&&r!==`lazyRelease`&&r!==`simple`&&r!==`bucket`)throw Error(`${t} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${r}`);Ot(a,t,r,n)}}}let c=E().webgpuRegisterDevice(s);if(c){let[e,t,r]=c;Ot(a,`deviceId`,e.toString(),n),Ot(a,`webgpuInstance`,t.toString(),n),Ot(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let s=a.length,c=0,l=0;if(s>0){c=E()._malloc(s*E().PTR_SIZE),n.push(c),l=E()._malloc(s*E().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)E().setValue(c+e*E().PTR_SIZE,a[e][0],`*`),E().setValue(l+e*E().PTR_SIZE,a[e][1],`*`)}let u;if(o!==void 0){let t=E()._malloc(E().PTR_SIZE);n.push(t),E().setValue(t,o[0],`*`),u=await E()._OrtAppendExecutionProviderV2(e,t,1,c,l,s)}else{let t=yt(r,n);u=await E()._OrtAppendExecutionProvider(e,t,c,l,s)}u!==0&&D(`Can't append execution provider: ${r}.`)}},Mt=async e=>{let t=E(),n=0,r=[],i=e||{};Et(i);try{let e=wt(i.graphOptimizationLevel??`all`),a=Tt(i.executionMode??`sequential`),o=typeof i.logId==`string`?yt(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?yt(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&D(`Can't create session options.`),i.executionProviders&&await jt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=yt(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&D(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&bt(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{Dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&D(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Pt,Ft,It,Lt,Rt,zt,Bt,Vt,Ht=s(()=>{\"use strict\";Pt=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Ft=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},It=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Lt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Rt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},zt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Vt=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ut,Wt=s(()=>{\"use strict\";Ue(),Ut=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<0x40000000)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Gt,Kt=s(()=>{\"use strict\";Ht(),Gt=(e,t)=>new(Lt(t))(e)}),qt,Jt,Yt,Xt,Zt,Qt,$t,en=s(()=>{\"use strict\";Ht(),qt=[`V`,`I`,`W`,`E`,`F`],Jt=(e,t)=>{console.log(`[${qt[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Zt=(e,t)=>{Yt=e,Xt=t},Qt=(e,t)=>{let n=Rt(e);n>=Rt(Yt)&&Jt(n,typeof t==`function`?t():t)},$t=(...e)=>{Xt&&Qt(...e)}}),tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,pn=s(()=>{\"use strict\";Ht(),en(),tn=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),nn=(e,t)=>{if(t===`int32`)return e;let n=tn.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Lt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>0x7fffffff))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},rn=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},an=1,on=()=>an++,sn=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),cn=(e,t)=>{let n=tn.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},ln=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,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 cn(this.dataType,this.tensorShape)}destroy(){$t(`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),n=rn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},un=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,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=sn.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);$t(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==cn(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=nn(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}$t(`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?rn(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}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},dn=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=on();return this.tensorTrackersById.set(e,new un(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,n,r,i){$t(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){$t(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.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,n,r){let i=this.getMLContext(e),a=on(),o=new ln({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new un(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){$t(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}$t(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new ln({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},fn=(...e)=>new dn(...e)}),mn={};c(mn,{WebNNBackend:()=>_n});var hn,gn,_n,vn=s(()=>{\"use strict\";Ht(),vt(),Kt(),pn(),en(),hn=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),gn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},_n=class{constructor(e){this.tensorManager=fn(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Zt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){$t(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){$t(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)$t(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>gn(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.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 n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){$t(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=hn.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){$t(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=hn.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!E().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);$t(`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 n=await this.tensorManager.download(e);return Gt(n,t)}}registerMLTensor(e,t,n,r){let i=hn.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return $t(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=hn.get(Pt(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln=s(()=>{\"use strict\";He(),Ct(),Nt(),Ht(),vt(),xt(),Wt(),yn=(e,t)=>{E()._OrtInit(e,t)!==0&&D(`Can't initialize onnxruntime.`)},bn=async e=>{yn(e.wasm.numThreads,Rt(e.logLevel))},xn=async(e,t)=>{E().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: \"${t}\"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: \"${r}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&E().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(vn(),u(mn)).WebNNBackend(e);E().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Sn=/* @__PURE__ */ new Map,Cn=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&D(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},wn=(e,t)=>{let n=E(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&D(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Tn=e=>{let t=E(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},En=async(e,t)=>{let n,r,i=E();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Tn(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Mt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Ut(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&D(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Cn(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=wn(a,t);e===0&&D(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:Ft(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=wn(a,n+e);r===0&&D(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:Ft(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&D(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Vt(e))}),Sn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&D(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&D(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&D(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Dn=e=>{let t=E(),n=Sn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&D(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&D(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&D(`Can't release session.`),Sn.delete(e)},On=/* @__PURE__ */ new Map,kn=1,An=/* @__PURE__ */ new Map,jn=e=>{let t=E(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a LoRA adapter. failed to allocate a buffer of size ${e.byteLength}.`);try{t.HEAPU8.set(e,n);let r=t._OrtCreateLoraAdapter(n,e.byteLength);r===0&&D(`Can't create a LoRA adapter.`);let i=kn++;return On.set(i,r),i}finally{t._free(n)}},Mn=e=>{let t=E(),n=On.get(e);if(n===void 0)throw Error(`cannot release LoRA adapter. invalid adapter id: ${e}`);if(An.has(e))throw Error(`cannot release LoRA adapter. the adapter is used by a run in progress. adapter id: ${e}`);t._OrtReleaseLoraAdapter(n)!==0&&D(`Can't release LoRA adapter.`),On.delete(e)},Nn=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=E(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=It(Pt(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location \"gpu-buffer\" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=It(Pt(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);p=n(r,t,Pt(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,yt(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=Pt(l);m=It(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Pt(l),p,m,g,u.length,Vt(f));e===0&&D(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Pn=async(e,t,n,r,i,a,o=[])=>{let s=E(),c=s.PTR_SIZE,l=Sn.get(e);if(!l)throw Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],f=l[2],p=l[3],m=l[4],h=l[5],g=[];if(o.length>0){if(p)throw Error(`LoRA adapters are not supported for a session that uses IO binding, e.g. when an output is preferred to be on GPU, or when the WebNN execution provider produces an output.`);for(let e of o){let t=On.get(e);if(t===void 0)throw Error(`cannot run inference. invalid LoRA adapter id: ${e}`);g.push(t)}}let _=t.length,v=r.length,y=0,b=[],x=[],S=[],C=[],ee=[],w=s.stackSave(),te=s.stackAlloc(_*c),ne=s.stackAlloc(_*c),re=s.stackAlloc(v*c),ie=s.stackAlloc(v*c);try{for(let e of o)An.set(e,(An.get(e)??0)+1);[y,b]=St(a,g),oe(`wasm prepareInputOutputTensor`);for(let r=0;r<_;r++)await Nn(n[r],x,C,e,d[t[r]],t[r],m);for(let t=0;t<v;t++)await Nn(i[t],S,C,e,f[r[t]],_+r[t],m);se(`wasm prepareInputOutputTensor`);for(let e=0;e<_;e++)s.setValue(te+e*c,x[e],`*`),s.setValue(ne+e*c,d[t[e]],`*`);for(let e=0;e<v;e++)s.setValue(re+e*c,S[e],`*`),s.setValue(ie+e*c,f[r[e]],`*`);if(p&&!h){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:o}=p;if(d.length!==_)throw Error(`input count from feeds (${_}) is expected to be always equal to model's input count (${d.length}).`);oe(`wasm bindInputsOutputs`);for(let r=0;r<_;r++){let i=t[r];await s._OrtBindInput(n,d[i],x[r])!==0&&D(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<v;t++){let c=r[t];i[t]?.[3]?(ee.push(S[t]),s._OrtBindOutput(n,f[c],S[t],0)!==0&&D(`Can't bind pre-allocated output[${t}] for session=${e}.`)):s._OrtBindOutput(n,f[c],0,o[c])!==0&&D(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}se(`wasm bindInputsOutputs`),Sn.set(e,[u,d,f,p,m,!0])}s.jsepOnRunStart?.(u),s.webnnOnRunStart?.(u);let l;l=p?await s._OrtRunWithBinding(u,p.handle,v,re,y):await s._OrtRun(u,ne,te,_,ie,v,re,y),l!==0&&D(`failed to call OrtRun().`);let w=[],ae=[];oe(`wasm ProcessOutputTensor`);for(let t=0;t<v;t++){let n=Number(s.getValue(re+t*c,`*`));if(n===S[t]||ee.includes(S[t])){w.push(i[t]),n!==S[t]&&s._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`);continue}let a=s.stackSave(),o=s.stackAlloc(4*c),l=!1,u,d=0;try{s._OrtGetTensorData(n,o,o+c,o+2*c,o+3*c)!==0&&D(`Can't access output tensor data on index ${t}.`);let i=c===4?`i32`:`i64`,a=Number(s.getValue(o,i));d=s.getValue(o+c,`*`);let f=s.getValue(o+c*2,`*`),m=Number(s.getValue(o+c*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(s.getValue(f+e*c,i)));s._OrtFree(f)!==0&&D(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=Ft(a);let _=p?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=s.getValue(d+t*c,`*`),r=s.getValue(d+(t+1)*c,`*`),i=t===g-1?void 0:r-n;e.push(s.UTF8ToString(n,i))}w.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=s.webgpuGetBuffer;if(!t)throw Error(`preferredLocation \"gpu-buffer\" is not supported without using WebGPU.`);let r=t(d),i=It(a,g);if(i===void 0||!zt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{s.webgpuRegisterBuffer(r,e,d);let t=s.webgpuCreateDownloader(r,i,e);w.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Lt(u))(e)},dispose:()=>{s._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=s.webnnEnsureTensor,r=s.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation \"ml-tensor\" is not supported without using WebNN.`);if(It(a,g)===void 0||!Bt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation \"ml-tensor\" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,w.push([u,h,{mlTensor:i,download:s.webnnCreateMLTensorDownloader(d,u),dispose:()=>{s.webnnReleaseTensorId(d),s._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=s.webnnCreateMLTensorDownloader(d,u)(),t=w.length;l=!0,ae.push((async()=>{let r=[t,await e];return s.webnnReleaseTensorId(d),s._OrtReleaseTensor(n),r})()),w.push([u,h,[],`cpu`])}else{let e=new(Lt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s.HEAPU8.subarray(d,d+e.byteLength)),w.push([u,h,e,`cpu`])}}finally{s.stackRestore(a),u===`string`&&d&&s._free(d),l||s._OrtReleaseTensor(n)}}p&&!m&&(s._OrtClearBoundOutputs(p.handle)!==0&&D(`Can't clear bound outputs.`),Sn.set(e,[u,d,f,p,m,!1]));for(let[e,t]of await Promise.all(ae))w[e][2]=t;return se(`wasm ProcessOutputTensor`),w}finally{s.webnnOnRunEnd?.(u),s.stackRestore(w),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&s.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&s.webgpuUnregisterBuffer(e[2].gpuBuffer)}),x.forEach(e=>s._OrtReleaseTensor(e)),S.forEach(e=>s._OrtReleaseTensor(e)),C.forEach(e=>s._free(e)),y!==0&&s._OrtReleaseRunOptions(y),b.forEach(e=>s._free(e));for(let e of o){let t=An.get(e)-1;t===0?An.delete(e):An.set(e,t)}}},Fn=e=>{let t=E(),n=Sn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&D(`Can't get an profile file name.`),t._OrtFree(i)},In=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir=s(()=>{\"use strict\";He(),Ln(),vt(),lt(),Wt(),Rn=()=>!!w.wasm.proxy&&typeof document<`u`,Bn=!1,Vn=!1,Hn=!1,Gn=/* @__PURE__ */ new Map,Kn=(e,t)=>{let n=Gn.get(e);n?n.push(t):Gn.set(e,[t])},qn=()=>{if(Bn||!Vn||Hn||!zn)throw Error(`worker not ready`)},Jn=e=>{switch(e.data.type){case`init-wasm`:Bn=!1,e.data.err?(Hn=!0,Wn[1](e.data.err)):(Vn=!0,Wn[0]()),Un&&=(URL.revokeObjectURL(Un),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Gn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Yn=async()=>{if(!Vn){if(Bn)throw Error(`multiple calls to 'initWasm()' detected.`);if(Hn)throw Error(`previous call to 'initWasm()' failed.`);if(Bn=!0,Rn())return new Promise((e,t)=>{zn?.terminate(),ot().then(([n,r])=>{try{zn=r,zn.onerror=e=>t(e),zn.onmessage=Jn,Wn=[e,t];let i={type:`init-wasm`,in:w};if(!i.in.wasm.wasmPaths&&n){let e=$e();e&&(i.in.wasm.wasmPaths=e)}zn.postMessage(i),Un=n}catch(e){t(e)}},t)});try{await _t(w.wasm),await bn(w),Vn=!0}catch(e){throw Hn=!0,e}finally{Bn=!1}}},Xn=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:w}};zn.postMessage(r)});await xn(w,e)},Zn=async e=>Rn()?(qn(),new Promise((t,n)=>{Kn(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};zn.postMessage(r,[e.buffer])})):Tn(e),Qn=async(e,t)=>{if(Rn()){if(t?.preferredOutputLocation)throw Error(`session option \"preferredOutputLocation\" is not supported for proxy.`);return qn(),new Promise((n,r)=>{Kn(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),zn.postMessage(i,a)})}return En(e,t)},$n=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`release`,[t,n]);let r={type:`release`,in:e};zn.postMessage(r)});Dn(e)},er=async e=>{if(Rn())throw Error(`LoRA adapter is not supported for proxy.`);let t=typeof e==`string`?await Ut(e):e;return jn(t)},tr=async e=>{if(Rn())throw Error(`LoRA adapter is not supported for proxy.`);Mn(e)},nr=async(e,t,n,r,i,a,o)=>{if(Rn()){if(o.length>0)throw Error(`LoRA adapter is not supported for proxy.`);if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return qn(),new Promise((i,o)=>{Kn(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};zn.postMessage(c,In(s))})}return Pn(e,t,n,r,i,a,o)},rr=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};zn.postMessage(r)});Fn(e)}}),ar,or=s(()=>{\"use strict\";He(),ir(),ar=class{async loadAdapter(e){ie(),this.adapterId=await er(e),ae()}async dispose(){return tr(this.adapterId)}}}),sr,cr,lr,ur=s(()=>{\"use strict\";He(),or(),ir(),Ht(),Ue(),Wt(),sr=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},cr=e=>{switch(e[3]){case`cpu`:return new Ae(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!zt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Ae.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Bt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return Ae.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},lr=class{async fetchModelAndCopyToWasmMemory(e){return Zn(await Ut(e))}async loadModel(e,t){ie();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qn(n,t),ae()}async dispose(){return $n(this.sessionId)}async run(e,t,n,r=[]){ie();let i=r.map(e=>{if(!(e instanceof ar))throw Error(`LoRA adapter was not created by the WebAssembly backend.`);return e.adapterId}),a=[],o=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],r=this.inputNames.indexOf(t);if(r===-1)throw Error(`invalid input '${t}'`);a.push(n),o.push(r)});let s=[],c=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);s.push(n),c.push(r)});let l=a.map((e,t)=>sr(e,()=>`input \"${this.inputNames[o[t]]}\"`)),u=s.map((e,t)=>e?sr(e,()=>`output \"${this.outputNames[c[t]]}\"`):null),d=await nr(this.sessionId,o,l,c,u,n,i),f={};for(let e=0;e<d.length;e++)f[this.outputNames[c[e]]]=s[e]??cr(d[e]);return ae(),f}startProfiling(){}endProfiling(){rr(this.sessionId)}}}),dr,fr=s(()=>{\"use strict\";dr=e=>{if(e?.epContextDataRead)throw Error(`session option \"epContextDataRead\" is not supported by ONNX Runtime Web`)}}),pr={};c(pr,{OnnxruntimeWebAssemblyBackend:()=>hr,initializeFlags:()=>mr,wasmBackend:()=>gr});var mr,hr,gr,_r=s(()=>{\"use strict\";He(),or(),ir(),ur(),fr(),mr=()=>{(typeof w.wasm.initTimeout!=`number`||w.wasm.initTimeout<0)&&(w.wasm.initTimeout=0);let e=w.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.`),w.wasm.simd=!1),typeof w.wasm.proxy!=`boolean`&&(w.wasm.proxy=!1),typeof w.wasm.trace!=`boolean`&&(w.wasm.trace=!1),typeof w.wasm.numThreads!=`number`||!Number.isInteger(w.wasm.numThreads)||w.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)w.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;w.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},hr=class{async init(e){mr(),await Yn(),await Xn(e)}async createInferenceSessionHandler(e,t){dr(t);let n=new lr;return await n.loadModel(e,t),n}async createLoraAdapterHandler(e){let t=new ar;return await t.loadAdapter(e),t}},gr=new hr});He(),He(),He();var vr=`1.31.1`;{let e=(_r(),u(pr)).wasmBackend;m(`webgpu`,e,5),m(`webnn`,e,5),m(`cpu`,e,10),m(`wasm`,e,10)}Object.defineProperty(w.versions,\"web\",{value:vr,enumerable:!0});var yr=/* @__PURE__ */ t({InferenceSession:()=>yi,TRACE:()=>ui,TRACE_EVENT_BEGIN:()=>mi,TRACE_EVENT_END:()=>hi,TRACE_FUNC_BEGIN:()=>fi,TRACE_FUNC_END:()=>pi,Tensor:()=>ci,default:()=>Wo,env:()=>Br,registerBackend:()=>Ar}),br=Object.defineProperty,xr=Object.getOwnPropertyDescriptor,Sr=Object.getOwnPropertyNames,Cr=Object.prototype.hasOwnProperty,wr=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){\n/*!\n* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\nif(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of \"`+e+`\" is not supported`)}),O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Tr=(e,t)=>{for(var n in t)br(e,n,{get:t[n],enumerable:!0})},Er=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of Sr(t))!Cr.call(e,i)&&i!==n&&br(e,i,{get:()=>t[i],enumerable:!(r=xr(t,i))||r.enumerable});return e},Dr=e=>Er(br({},`__esModule`,{value:!0}),e),Or,kr,Ar,jr,Mr,Nr=O(()=>{\"use strict\";Or=/* @__PURE__ */ new Map,kr=[],Ar=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=Or.get(e);if(r===void 0)Or.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend \"${e}\" using priority ${n}`)}if(n>=0){let t=kr.indexOf(e);t!==-1&&kr.splice(t,1);for(let t=0;t<kr.length;t++)if(Or.get(kr[t]).priority<=n){kr.splice(t,0,e);return}kr.push(e)}}else throw TypeError(`not a valid backend`)},jr=async e=>{let t=Or.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Mr=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?kr:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await jr(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider \"${e}\" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),Pr=O(()=>{\"use strict\";Nr()}),Fr,Ir=O(()=>{\"use strict\";Fr=`1.31.0-dev.20260911-2a43ec07e`}),Lr,Rr,zr=O(()=>{\"use strict\";Ir(),Lr=`warning`,Rr={wasm:{},webgl:{},webgpu:{},versions:{common:Fr},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Lr=e}},get logLevel(){return Lr}},Object.defineProperty(Rr,\"logLevel\",{enumerable:!0})}),Br,Vr=O(()=>{\"use strict\";zr(),Br=Rr}),Hr,Ur,Wr=O(()=>{\"use strict\";Hr=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},Ur=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),Gr,Kr,qr,Jr,Yr,Xr,Zr=O(()=>{\"use strict\";si(),Gr=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new oi(`float32`,u,[1,4,n,r]):new oi(`float32`,u,[1,3,n,r])},Kr=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,Gr(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(Gr(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return Gr(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},qr=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new oi({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Jr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new oi({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Yr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new oi({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},Xr=(e,t,n)=>new oi({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),Qr,$r,ei,ti,ni=O(()=>{\"use strict\";Qr=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),$r=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ei=!1,ti=()=>{if(!ei){ei=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(Qr.set(`int64`,BigInt64Array),$r.set(BigInt64Array,`int64`)),t&&(Qr.set(`uint64`,BigUint64Array),$r.set(BigUint64Array,`uint64`)),r?(Qr.set(`float16`,n),$r.set(n,`float16`)):Qr.set(`float16`,Uint16Array)}}}),ri,ii,ai=O(()=>{\"use strict\";si(),ri=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ii=(e,t)=>{switch(e.location){case`cpu`:return new oi(e.type,e.data,t);case`cpu-pinned`:return new oi({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new oi({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new oi({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new oi({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),oi,si=O(()=>{\"use strict\";Wr(),Zr(),ni(),ai(),oi=class{constructor(e,t,n){ti();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=Qr.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=Qr.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=$r.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=ri(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Kr(e,t)}static fromTexture(e,t){return qr(e,t)}static fromGpuBuffer(e,t){return Jr(e,t)}static fromMLTensor(e,t){return Yr(e,t)}static fromPinnedBuffer(e,t,n){return Xr(e,t,n)}toDataURL(e){return Hr(this,e)}toImageData(e){return Ur(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ii(this,e)}}}),ci,li=O(()=>{\"use strict\";si(),ci=oi}),ui,di,fi,pi,mi,hi,gi=O(()=>{\"use strict\";zr(),ui=(e,t)=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.timeStamp(`${e}::ORT::${t}`)},di=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\\r\\n|\\r|\\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ui(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},fi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||di(`BEGIN`,e)},pi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||di(`END`,e)},mi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.time(`ORT::${e}`)},hi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.timeEnd(`ORT::${e}`)}}),_i,vi=O(()=>{\"use strict\";Nr(),li(),gi(),_i=class e{constructor(e){this.handler=e}async run(e,t,n){fi(),mi(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof ci||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof ci)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof ci)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof ci?t:new ci(t.type,t.data,t.dims)}return hi(`InferenceSession.run`),pi(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){fi(),mi(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await Mr(o),l=await s.createInferenceSessionHandler(a,c);return hi(`InferenceSession.create`),pi(),new e(l)}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}}}),yi,bi=O(()=>{\"use strict\";vi(),yi=_i}),xi=O(()=>{\"use strict\";}),Si=O(()=>{\"use strict\";}),Ci=O(()=>{\"use strict\";}),wi=O(()=>{\"use strict\";}),Ti={};Tr(Ti,{InferenceSession:()=>yi,TRACE:()=>ui,TRACE_EVENT_BEGIN:()=>mi,TRACE_EVENT_END:()=>hi,TRACE_FUNC_BEGIN:()=>fi,TRACE_FUNC_END:()=>pi,Tensor:()=>ci,env:()=>Br,registerBackend:()=>Ar});var Ei=O(()=>{\"use strict\";Pr(),Vr(),bi(),li(),xi(),Si(),gi(),Ci(),wi()}),Di=O(()=>{\"use strict\";}),Oi={};Tr(Oi,{default:()=>ji});var ki,Ai,ji,Mi=O(()=>{\"use strict\";mo(),na(),qi(),ki=`ort-wasm-proxy-worker`,Ai=globalThis.self?.name===ki,Ai&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:ta(n.wasm).then(()=>{to(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;no(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=oo(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;so(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:co(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;uo(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},po([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:fo(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),ji=Ai?null:e=>new Worker(e??Ii,{type:`module`,name:ki})}),Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi=O(()=>{\"use strict\";Di(),Ni=typeof location>`u`?void 0:location.origin,Pi=self.location.href>`file:`&&self.location.href<`file;`,Fi=()=>Pi?new URL(new URL(`ort.webgpu.min.mjs`,self.location.href).href,Ni).href:self.location.href,Ii=Fi(),Li=()=>{if(Ii&&!Ii.startsWith(`blob:`))return Ii.substring(0,Ii.lastIndexOf(`/`)+1)},Ri=(e,t)=>{try{let n=t??Ii;return(n?new URL(e,n):new URL(e)).origin===Ni}catch{return!1}},zi=(e,t)=>{let n=t??Ii;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Bi=(e,t)=>`${t??`./`}${e}`,Vi=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Hi=async e=>(await import(\n/*webpackIgnore:true*/\n/*@vite-ignore*/\ne)).default,Ui=(Mi(),Dr(Oi)).default,Wi=async()=>{if(!Ii)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Ri(Ii))return[void 0,Ui()];let e=await Vi(Ii);return[e,Ui(e)]},Gi=void 0,Ki=async(e,t,n,r)=>{let i=Gi&&!(e||t);if(i){if(Ii)i=Ri(Ii)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,Gi];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??zi(r,t),a=n&&i&&!Ri(i,t),o=a?await Vi(i):i??Bi(r,t);return[a?o:void 0,await Hi(o)]}}}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta,k,na=O(()=>{\"use strict\";qi(),Yi=!1,Xi=!1,Zi=!1,Qi=()=>{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}},$i=()=>{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}},ea=()=>{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}},ta=async e=>{if(Yi)return Promise.resolve();if(Xi)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Zi)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Xi=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!ea())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!$i())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Qi();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, 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=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Ki(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Li();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Xi=!1,Yi=!0,Ji=t,e(),d&&URL.revokeObjectURL(d)},e=>{Xi=!1,Zi=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},k=()=>{if(Yi&&Ji)return Ji;throw Error(`WebAssembly is not initialized yet.`)}}),ra,ia,A,aa=O(()=>{\"use strict\";na(),ra=(e,t)=>{let n=k(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},ia=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)ia(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},A=e=>{let t=k(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),oa,sa=O(()=>{\"use strict\";na(),aa(),oa=e=>{let t=k(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=ra(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&A(`Can't create run options.`),e?.extra!==void 0&&ia(e.extra,``,/* @__PURE__ */ new WeakSet,(e,i)=>{let a=ra(e,r),o=ra(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&A(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ca,la,ua,da,fa,pa,ma,ha=O(()=>{\"use strict\";na(),aa(),ca=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},la=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ua=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},da=(e,t,n,r)=>{let i=ra(t,r),a=ra(n,r);k()._OrtAddSessionConfigEntry(e,i,a)!==0&&A(`Can't set a session config entry: ${t} - ${n}.`)},fa=(e,t,n,r)=>{let i=ra(t,r),a=ra(n,r);e.push([i,a])},pa=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,da(e,`session.disable_quant_qdq`,`1`,n),da(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&da(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&fa(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&fa(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];fa(a,`forceCpuNodeNames`,e.join(`\n`),n)}r.validationMode&&fa(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&fa(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);fa(a,e,t,n)}}}let o=k().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;fa(a,`deviceId`,e.toString(),n),fa(a,`webgpuInstance`,t.toString(),n),fa(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=ra(r,n),s=a.length,c=0,l=0;if(s>0){c=k()._malloc(s*k().PTR_SIZE),n.push(c),l=k()._malloc(s*k().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)k().setValue(c+e*k().PTR_SIZE,a[e][0],`*`),k().setValue(l+e*k().PTR_SIZE,a[e][1],`*`)}await k()._OrtAppendExecutionProvider(e,o,c,l,s)!==0&&A(`Can't append execution provider: ${r}.`)}},ma=async e=>{let t=k(),n=0,r=[],i=e||{};ua(i);try{let e=ca(i.graphOptimizationLevel??`all`),a=la(i.executionMode??`sequential`),o=typeof i.logId==`string`?ra(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?ra(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&A(`Can't create session options.`),i.executionProviders&&await pa(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);da(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=ra(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&A(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&ia(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{da(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&A(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ga,_a,va,ya,ba,xa,Sa,Ca,wa=O(()=>{\"use strict\";ga=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},_a=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},va=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ya=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},ba=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},xa=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Sa=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Ca=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ta,Ea=O(()=>{\"use strict\";Di(),Ta=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<0x40000000)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Da,Oa=O(()=>{\"use strict\";wa(),Da=(e,t)=>new(ya(t))(e)}),ka,Aa,ja,Ma,Na,Pa,Fa,Ia=O(()=>{\"use strict\";wa(),ka=[`V`,`I`,`W`,`E`,`F`],Aa=(e,t)=>{console.log(`[${ka[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Na=(e,t)=>{ja=e,Ma=t},Pa=(e,t)=>{let n=ba(e);n>=ba(ja)&&Aa(n,typeof t==`function`?t():t)},Fa=(...e)=>{Ma&&Pa(...e)}}),La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja=O(()=>{\"use strict\";wa(),Ia(),La=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Ra=(e,t)=>{if(t===`int32`)return e;let n=La.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(ya(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>0x7fffffff))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},za=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Ba=1,Va=()=>Ba++,Ha=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),Ua=(e,t)=>{let n=La.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},Wa=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,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 Ua(this.dataType,this.tensorShape)}destroy(){Fa(`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),n=za(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Ga=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,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Ha.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Fa(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Ua(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=Ra(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Fa(`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?za(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}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},Ka=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Va();return this.tensorTrackersById.set(e,new Ga(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,n,r,i){Fa(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Fa(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.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,n,r){let i=this.getMLContext(e),a=Va(),o=new Wa({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Ga(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Fa(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Fa(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new Wa({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},qa=(...e)=>new Ka(...e)}),Ya={};Tr(Ya,{WebNNBackend:()=>Qa});var Xa,Za,Qa,$a=O(()=>{\"use strict\";wa(),na(),Oa(),Ja(),Ia(),Xa=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),Za=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},Qa=class{constructor(e){this.tensorManager=qa(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Na(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Fa(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Fa(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Fa(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>Za(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.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 n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Fa(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Xa.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Fa(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Xa.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!k().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Fa(`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 n=await this.tensorManager.download(e);return Da(n,t)}}registerMLTensor(e,t,n,r){let i=Xa.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Fa(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Xa.get(ga(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),eo,to,no,ro,io,ao,oo,so,co,lo,uo,fo,po,mo=O(()=>{\"use strict\";Ei(),sa(),ha(),wa(),na(),aa(),Ea(),eo=(e,t)=>{k()._OrtInit(e,t)!==0&&A(`Can't initialize onnxruntime.`)},to=async e=>{eo(e.wasm.numThreads,ba(e.logLevel))},no=async(e,t)=>{k().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: \"${t}\"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: \"${r}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&k().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new($a(),Dr(Ya)).WebNNBackend(e);k().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},ro=/* @__PURE__ */ new Map,io=e=>{let t=k(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&A(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},ao=(e,t)=>{let n=k(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&A(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},oo=e=>{let t=k(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},so=async(e,t)=>{let n,r,i=k();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=oo(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await ma(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Ta(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&A(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=io(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=ao(a,t);e===0&&A(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:_a(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=ao(a,n+e);r===0&&A(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:_a(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&A(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Ca(e))}),ro.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&A(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&A(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&A(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},co=e=>{let t=k(),n=ro.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&A(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&A(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&A(`Can't release session.`),ro.delete(e)},lo=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=k(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=va(ga(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location \"gpu-buffer\" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=va(ga(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);p=n(r,t,ga(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,ra(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ga(l);m=va(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ga(l),p,m,g,u.length,Ca(f));e===0&&A(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},uo=async(e,t,n,r,i,a)=>{let o=k(),s=o.PTR_SIZE,c=ro.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),ee=o.stackAlloc(h*s),w=o.stackAlloc(h*s),te=o.stackAlloc(g*s),ne=o.stackAlloc(g*s);try{[_,v]=oa(a),mi(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await lo(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await lo(i[t],b,x,e,d[r[t]],h+r[t],p);hi(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(ee+e*s,y[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(te+e*s,b[e],`*`),o.setValue(ne+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);mi(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&A(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&A(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&A(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}hi(`wasm bindInputsOutputs`),ro.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,te,_):await o._OrtRun(l,w,ee,h,ne,g,te,_),c!==0&&A(`failed to call OrtRun().`);let C=[],re=[];mi(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(te+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&A(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&A(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&A(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=_a(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation \"gpu-buffer\" is not supported without using WebGPU.`);let r=t(d),i=va(a,g);if(i===void 0||!xa(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(ya(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&A(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation \"ml-tensor\" is not supported without using WebNN.`);if(va(a,g)===void 0||!Sa(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation \"ml-tensor\" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(ya(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&A(`Can't clear bound outputs.`),ro.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))C[e][2]=t;return hi(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},fo=e=>{let t=k(),n=ro.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&A(`Can't get an profile file name.`),t._OrtFree(i)},po=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),ho,go,_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No=O(()=>{\"use strict\";Ei(),mo(),na(),qi(),ho=()=>!!Br.wasm.proxy&&typeof document<`u`,_o=!1,vo=!1,yo=!1,So=/* @__PURE__ */ new Map,Co=(e,t)=>{let n=So.get(e);n?n.push(t):So.set(e,[t])},wo=()=>{if(_o||!vo||yo||!go)throw Error(`worker not ready`)},To=e=>{switch(e.data.type){case`init-wasm`:_o=!1,e.data.err?(yo=!0,xo[1](e.data.err)):(vo=!0,xo[0]()),bo&&=(URL.revokeObjectURL(bo),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=So.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Eo=async()=>{if(!vo){if(_o)throw Error(`multiple calls to 'initWasm()' detected.`);if(yo)throw Error(`previous call to 'initWasm()' failed.`);if(_o=!0,ho())return new Promise((e,t)=>{go?.terminate(),Wi().then(([n,r])=>{try{go=r,go.onerror=e=>t(e),go.onmessage=To,xo=[e,t];let i={type:`init-wasm`,in:Br};if(!i.in.wasm.wasmPaths&&n){let e=Li();e&&(i.in.wasm.wasmPaths=e)}go.postMessage(i),bo=n}catch(e){t(e)}},t)});try{await ta(Br.wasm),await to(Br),vo=!0}catch(e){throw yo=!0,e}finally{_o=!1}}},Do=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:Br}};go.postMessage(r)});await no(Br,e)},Oo=async e=>ho()?(wo(),new Promise((t,n)=>{Co(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};go.postMessage(r,[e.buffer])})):oo(e),ko=async(e,t)=>{if(ho()){if(t?.preferredOutputLocation)throw Error(`session option \"preferredOutputLocation\" is not supported for proxy.`);return wo(),new Promise((n,r)=>{Co(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),go.postMessage(i,a)})}return so(e,t)},Ao=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`release`,[t,n]);let r={type:`release`,in:e};go.postMessage(r)});co(e)},jo=async(e,t,n,r,i,a)=>{if(ho()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return wo(),new Promise((i,o)=>{Co(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};go.postMessage(c,po(s))})}return uo(e,t,n,r,i,a)},Mo=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};go.postMessage(r)});fo(e)}}),Po,Fo,Io,Lo=O(()=>{\"use strict\";Ei(),No(),wa(),Di(),Ea(),Po=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Fo=e=>{switch(e[3]){case`cpu`:return new ci(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!xa(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return ci.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Sa(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return ci.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Io=class{async fetchModelAndCopyToWasmMemory(e){return Oo(await Ta(e))}async loadModel(e,t){fi();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ko(n,t),pi()}async dispose(){return Ao(this.sessionId)}async run(e,t,n){fi();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Po(e,()=>`input \"${this.inputNames[i[t]]}\"`)),c=a.map((e,t)=>e?Po(e,()=>`output \"${this.outputNames[o[t]]}\"`):null),l=await jo(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Fo(l[e]);return pi(),u}startProfiling(){}endProfiling(){Mo(this.sessionId)}}}),Ro={};Tr(Ro,{OnnxruntimeWebAssemblyBackend:()=>Bo,initializeFlags:()=>zo,wasmBackend:()=>Vo});var zo,Bo,Vo,Ho=O(()=>{\"use strict\";Ei(),No(),Lo(),zo=()=>{(typeof Br.wasm.initTimeout!=`number`||Br.wasm.initTimeout<0)&&(Br.wasm.initTimeout=0);let e=Br.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.`),Br.wasm.simd=!1),typeof Br.wasm.proxy!=`boolean`&&(Br.wasm.proxy=!1),typeof Br.wasm.trace!=`boolean`&&(Br.wasm.trace=!1),typeof Br.wasm.numThreads!=`number`||!Number.isInteger(Br.wasm.numThreads)||Br.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)Br.wasm.numThreads=1;else{let e=typeof navigator>`u`?wr(`node:os`).cpus().length:navigator.hardwareConcurrency;Br.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Bo=class{async init(e){zo(),await Eo(),await Do(e)}async createInferenceSessionHandler(e,t){let n=new Io;return await n.loadModel(e,t),n}},Vo=new Bo});Ei(),Ei(),Ei();var Uo=`1.31.0-dev.20260914-8d85527a0`,Wo=Ti;{let e=(Ho(),Dr(Ro)).wasmBackend;Ar(`webgpu`,e,5),Ar(`webnn`,e,5),Ar(`cpu`,e,10),Ar(`wasm`,e,10)}Object.defineProperty(Br.versions,\"web\",{value:Uo,enumerable:!0});let Go=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.31.0-dev.20260911-2a43ec07e`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Go=e}},get logLevel(){return Go}},\"logLevel\",{enumerable:!0});let Ko=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},qo=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r},Jo=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new os(`float32`,u,[1,4,n,r]):new os(`float32`,u,[1,3,n,r])},Yo=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,Jo(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(Jo(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return Jo(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},Xo=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new os({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Zo=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new os({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Qo=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new os({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},$o=(e,t,n)=>new os({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),es=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),ts=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ns=!1,rs=()=>{if(!ns){ns=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(es.set(`int64`,BigInt64Array),ts.set(BigInt64Array,`int64`)),t&&(es.set(`uint64`,BigUint64Array),ts.set(BigUint64Array,`uint64`)),r?(es.set(`float16`,n),ts.set(n,`float16`)):es.set(`float16`,Uint16Array)}},is=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},as=(e,t)=>{switch(e.location){case`cpu`:return new os(e.type,e.data,t);case`cpu-pinned`:return new os({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new os({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new os({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new os({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var os=class{constructor(e,t,n){rs();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=es.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=es.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=ts.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=is(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Yo(e,t)}static fromTexture(e,t){return Xo(e,t)}static fromGpuBuffer(e,t){return Zo(e,t)}static fromMLTensor(e,t){return Qo(e,t)}static fromPinnedBuffer(e,t,n){return $o(e,t,n)}toDataURL(e){return Ko(this,e)}toImageData(e){return qo(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return as(this,e)}};let ss=os;var cs={url:self.location.href},ls=Object.defineProperty,us=(e,t)=>{for(var n in t)ls(e,n,{get:t[n],enumerable:!0})},ds={},fs={},ps={},ms=`4.3.2`,hs=typeof self<`u`,gs=!Bs(ds),_s=!Bs(fs),vs=hs&&`caches`in self,ys=globalThis.Deno!==void 0;globalThis.Bun;var bs=ys&&vs&&!gs,xs=typeof process<`u`,Ss=xs&&process?.release?.name===`node`&&!bs,Cs=typeof window<`u`&&window.document!==void 0,ws=hs&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),Ts=Cs||ws||bs,Es=Ss||typeof navigator<`u`&&`gpu`in navigator,Ds=typeof navigator<`u`&&`ml`in navigator,Os=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,ks=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,As=typeof ServiceWorkerGlobalScope<`u`&&hs&&self instanceof ServiceWorkerGlobalScope,js=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\\/(\\d+)/);return t?parseInt(t[1],10)<26:!1})(),j=Object.freeze({IS_BROWSER_ENV:Cs,IS_WEBWORKER_ENV:ws,IS_WEB_ENV:Ts,IS_SERVICE_WORKER_ENV:As,IS_DENO_WEB_RUNTIME:bs,IS_WEB_CACHE_AVAILABLE:vs,IS_WEBGPU_AVAILABLE:Es,IS_WEBNN_AVAILABLE:Ds,IS_SAFARI_BELOW_26:js,IS_PROCESS_AVAILABLE:xs,IS_NODE_ENV:Ss,IS_FS_AVAILABLE:gs,IS_PATH_AVAILABLE:_s,IS_CRYPTO_AVAILABLE:Os,IS_CHROME_AVAILABLE:ks}),Ms=gs&&_s,Ns=`./`;if(Ms){let e=self.location.href;e?Ns=fs.dirname(fs.dirname(ps.fileURLToPath(e))):typeof __dirname<`u`&&(Ns=fs.dirname(__dirname))}var Ps=Ms?fs.join(Ns,`/.cache/`):null,Fs=`/models/`,Is=Ms?fs.join(Ns,Fs):Fs,Ls=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Rs=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),zs=Rs.WARNING,M={version:ms,backends:{onnx:{}},get logLevel(){return zs},set logLevel(e){zs=e,M.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Cs||ws||bs),localModelPath:Is,useFS:gs,useBrowserCache:vs,useFSCache:gs,cacheDir:Ps,useCustomCache:!1,customCache:null,useWasmCache:vs||gs,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Ls};function Bs(e){return Object.keys(e).length===0}var Vs=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function Hs(e,t){e&&e(t)}var Us=class extends Vs{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=/* @__PURE__ */ new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function Ws(e){return Number.isInteger(e)||typeof e==`bigint`}function Gs(e){return e==null||e===-1}function Ks(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function qs(...e){return Array.prototype.concat.apply([],e)}function Js(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function Ys(e,t){return Math.abs((e+t)%(2*t)-t)}function Xs(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function Zs(e,t){let n=0;for(let r of e)r===t&&++n;return n}var N={error(...e){M.logLevel<=Rs.ERROR&&console.error(...e)},warn(...e){M.logLevel<=Rs.WARNING&&console.warn(...e)},info(...e){M.logLevel<=Rs.INFO&&console.log(...e)},debug(...e){M.logLevel<=Rs.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Qs=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=/* @__PURE__ */ Object.create(null);for(let n of e){let e=t;for(let t=0;t<n.length;++t){let r=n[t];e=e[r]??=/* @__PURE__ */ Object.create(null)}e.end=n}return t}split(e){let t=[],n=e.length,r=0,i=0;for(;i<n;){let a=this.trie,o=null,s=i;for(;s<n&&(a=a[e[s]]);)a.end&&(o=a.end),++s;o?(i>r&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r<n&&t.push(e.slice(r)),t}},$s=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}},ec=(e,t)=>{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=/* @__PURE__ */ new Map,i=e.replace(/(\\\\[pP])\\{([^}=]+)\\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},tc=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`),nc=(e,t=!0)=>{if(e.Regex!==void 0)return ec(Bc(Oc(e.Regex)),`gu`);if(e.String!==void 0){let n=Vc(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},rc=`\\\\p{Alphabetic}\\\\p{M}\\\\p{Nd}\\\\p{Pc}`,ic=`${rc}\\\\u00B2\\\\u00B3\\\\u00B9\\\\u00BC-\\\\u00BE`,ac=`[${ic}]`,oc=`[^${ic}]`,sc=`(?:(?<!${ac})(?=${ac})|(?<=${ac})(?!${ac}))`,cc=`(?:(?<!${ac})(?!${ac})|(?<=${ac})(?=${ac}))`,lc=`(?:(?<![\\\\s\\\\S])|(?<=\\\\n))`,uc=`(?:(?=\\\\n)|(?![\\\\s\\\\S]))`,dc=`0-9A-Fa-f`,fc=/* @__PURE__ */ new Map([[`A`,`(?<![\\\\s\\\\S])`],[`z`,`(?![\\\\s\\\\S])`],[`Z`,`(?=\\\\n?(?![\\\\s\\\\S]))`],[`h`,`[${dc}]`],[`H`,`[^${dc}]`],[`w`,ac],[`W`,oc],[`d`,`\\\\p{Nd}`],[`D`,`\\\\P{Nd}`],[`s`,`\\\\p{White_Space}`],[`S`,`\\\\P{White_Space}`],[`b`,sc],[`B`,cc],[`a`,`\\\\x07`],[`e`,`\\\\x1B`]]),pc=/* @__PURE__ */ new Map([[`h`,dc],[`w`,rc],[`d`,`\\\\p{Nd}`],[`D`,`\\\\P{Nd}`],[`s`,`\\\\p{White_Space}`],[`S`,`\\\\P{White_Space}`],[`a`,`\\\\x07`],[`e`,`\\\\x1B`]]),mc=/* @__PURE__ */ new Map([[`W`,`[^${rc}]`],[`H`,`[^${dc}]`]]),hc=/* @__PURE__ */ new Map([[`\n`,`\\\\n`],[`\\r`,`\\\\r`],[` `,`\\\\t`],[`\\f`,`\\\\f`],[`\\v`,`\\\\v`]]),gc=/* @__PURE__ */ new Map([[`alpha`,`\\\\p{Alphabetic}`],[`alnum`,`\\\\p{Alphabetic}\\\\p{Nd}`],[`digit`,`\\\\p{Nd}`],[`lower`,`\\\\p{Lowercase}`],[`upper`,`\\\\p{Uppercase}`],[`space`,`\\\\p{White_Space}`],[`blank`,`\\\\t\\\\p{Zs}`],[`punct`,`\\\\p{P}\\\\p{S}`],[`cntrl`,`\\\\p{Cc}`],[`word`,rc],[`xdigit`,dc]]),_c=`^$\\\\.*+?()[]{}|/`,vc=/^\\(\\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,yc=/^\\\\([pPxu])\\{([^}]*)\\}/,bc=/^\\{(\\d+(?:,\\d*)?|,\\d+)\\}/,xc=/^\\[:(\\^?)(\\p{Alphabetic}+):\\]/u,Sc=/^\\[:\\^:\\]/,Cc=/^\\[(?:\\.[^\\]]*\\.\\]|=[^\\]]*=\\])/,wc=/^(?:\\\\x[0-9A-Fa-f]{2}|\\\\u[0-9A-Fa-f]{4}|\\\\c[A-Za-z])/,Tc=e=>e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`,Ec=(e,t)=>String.fromCodePoint(e.codePointAt(t)),Dc=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let n=String.fromCharCode(t);return Tc(n)?`[${n.toLowerCase()}${n.toUpperCase()}]`:null},Oc=e=>e.replace(/\\[\\^\\(\\\\s\\|\\[([^\\]]+)\\]\\)\\]/g,`[^()|\\\\s$1]`),kc=`[\\\\s\\\\S]`,Ac=256,jc=()=>({fragment:``,alternatives:[],tail:null,contains_complex_set:!1}),Mc=e=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},Nc=(e,t,n,r=!0)=>{e.tail===`range`&&Mc(n),e.alternatives.push(t),e.tail=`set`,e.contains_complex_set=e.contains_complex_set||r},Pc=(e,t,n=!1,r=-1)=>{n&&e.tail===`range`&&Mc(r),e.tail===`range`?(e.fragment+=t,e.tail=`complete_range`):(e.fragment+=t,e.tail=n?`set`:`scalar`,e.contains_complex_set=e.contains_complex_set||n)},Fc=(e,t,n)=>{let r=yc.exec(e.slice(t));if(r){let[e,i,a]=r;return i===`P`&&a===`Word`?Nc(n,`[^${rc}]`,t):Pc(n,i===`x`?`\\\\u{${a}}`:i===`p`&&a===`Word`?rc:e,i===`p`||i===`P`,t),t+e.length}let i=wc.exec(e.slice(t));if(i)return Pc(n,i[0]),t+i[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=Ec(e,t+1),o=t+1+a.length,s=hc.get(a);if(s!==void 0)return Pc(n,s),o;let c=mc.get(a);if(c!==void 0)return Nc(n,c,t),o;let l=pc.get(a),u,d=!1;return l===void 0?u=/[A-Za-z0-9]/.test(a)||_c.includes(a)||a===`-`?`\\\\${a}`:a:(u=l,d=a!==`a`&&a!==`e`),Pc(n,u,d,t),o},Ic=e=>e.length===1?e[0]:`(?:(?=(?:${e.join(`|`)}))${kc})`,Lc=e=>Ic(e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives]),Rc=e=>{let t=ec(`^(?:${e})$`,`u`),n=``;for(let e=0;e<26;++e){let r=String.fromCharCode(65+e),i=String.fromCharCode(97+e),a=t.test(r);a!==t.test(i)&&(n+=a?i:r)}return n},zc=(e,t,n,r=!0,i=1)=>{if(i>Ac)throw SyntaxError(`Maximum character-class nesting depth of ${Ac} exceeded at index ${t}`);let a=t+1,o=e[a]===`^`;o&&++a;let s=a,c=[jc()],l=c[0],u=!1;for(;a<e.length;){let d=Ec(e,a);if(d===`\\\\`)a=Fc(e,a,l);else{if(d===`]`){if(a===s){Pc(l,`\\\\]`),++a;continue}if(l.tail===null)throw c.length>1?SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):SyntaxError(`Empty character class at index ${t}`);let e=c.some(e=>e.contains_complex_set);if(o&&c.length>1&&u)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let i=Lc(c[0]),d=i;if(c.length>1){let e=``;for(let t=1;t<c.length;++t)e+=`(?=${Lc(c[t])})`;d=`(?:${e}${i})`}let f=c.length===1&&l.alternatives.length===0,p=l.fragment;if(n&&r){let e=Rc(d);e.length>0&&(f?(p+=e,d=`[${p}]`):d=Ic([d,`[${e}]`]))}return{atom:o?f?`[^${p}]`:`(?:(?!${d})${kc})`:d,end:a+1,negated:o,contains_complex_set:e,contains_nested_negated_complex_set:u}}if(e.startsWith(`&&`,a)){if(l.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);l=jc(),c.push(l),a+=2}else if(d===`[`){let t=e.slice(a);if(Sc.test(t))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let r=xc.exec(t);if(r){let[,e,t]=r,i=gc.get(t);if(i===void 0)throw SyntaxError(`Unsupported POSIX character class \"${t}\" at index ${a}`);if(n&&e&&(t===`lower`||t===`upper`))throw SyntaxError(`Unsupported negated POSIX ${t} class inside an inline case-insensitive group`);e?Nc(l,`[^${i}]`,a):Pc(l,i,!0,a),a+=r[0].length;continue}if(Cc.test(t))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let o=zc(e,a,n,!1,i+1);Nc(l,o.atom,a,o.contains_complex_set),u||=o.contains_nested_negated_complex_set||o.negated&&o.contains_complex_set,a=o.end}else if(d===`-`){let t=e[a+1]===`]`||e.startsWith(`&&`,a+1);l.tail===`set`&&!t&&Mc(a),l.tail===null||l.tail===`range`||l.tail===`complete_range`||t?Pc(l,`\\\\-`):(l.fragment+=`-`,l.tail=`range`),++a}else Pc(l,d===`^`&&l.fragment.length===0?`\\\\^`:d),a+=d.length}}throw SyntaxError(`${c.length>1?`Unterminated character-class intersection`:`Unterminated character class`} at index ${t}`)},Bc=e=>{let t=``,n=-1,r=!1,i=!1,a=[],o=e=>{n=t.length,t+=e,r=!1};for(let s=0;s<e.length;){let c=Ec(e,s);if(c===`\\\\`){let n=yc.exec(e.slice(s));if(n){let[e,t,r]=n,a=e;if(t===`x`){let e=`\\\\u{${r}}`;a=i?Dc(r)??e:e}else r===`Word`&&(a=t===`p`?ac:oc);o(a),s+=e.length;continue}let r=wc.exec(e.slice(s));if(r){let e=r[0];o(i&&e[1]!==`c`?Dc(e.slice(2))??e:e),s+=e.length;continue}if(s+1>=e.length){t+=c;break}let a=Ec(e,s+1);if(s+=1+a.length,a===`G`)continue;let l=hc.get(a);if(l!==void 0){o(l);continue}let u=fc.get(a),d;d=u===void 0?/[A-Za-z0-9]/.test(a)||_c.includes(a)?`\\\\${a}`:a:u,o(d)}else switch(c){case`[`:{let t=zc(e,s,i);o(t.atom),s=t.end;continue}case`]`:o(`\\\\]`),++s;continue;case`.`:o(`[^\\\\n]`),++s;continue;case`^`:o(lc),++s;continue;case`$`:o(uc),++s;continue;case`(`:{let n=e.startsWith(`(?i:`,s),o=n?`(?i:`:vc.exec(e.slice(s))?.[0]??`(`,c=n||o===`(?>`?`(?:`:o;a.push([t.length,i]),n&&(i=!0),t+=c,r=!1,s+=o.length;continue}case`)`:t+=c,[n,i]=a.pop()??[-1,!1],r=!1,++s;continue;case`|`:t+=c,n=-1,r=!1,++s;continue;case`{`:{let i=bc.exec(e.slice(s));if(!i||n<0){o(`\\\\{`),++s;continue}let a=i[1].startsWith(`,`)?`0${i[1]}`:i[1];s+=i[0].length;let c=e[s];c===`+`||c===`*`?(t=`${t.slice(0,n)}(?:${t.slice(n)}{${a}})${c}`,++s):t+=`{${a}}`,r=!0;continue}case`}`:o(`\\\\}`),++s;continue;case`+`:if(r){++s;continue}t+=c,r=!0,++s;continue;case`*`:case`?`:t+=c,r=!0,++s;continue;default:o(i&&Tc(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),s+=c.length;continue}}return t},Vc=e=>e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`),Hc=(e,t,n)=>{let r=[],i=0;for(;i<e.length;)if(r.push(e[i]),(t.get(e[i])??n)!==n)++i;else for(;++i<e.length&&(t.get(e[i])??n)===n;)t.get(r.at(-1))!==n&&(r[r.length-1]+=e[i]);return r},Uc=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,Wc=e=>Number.isInteger(e)||typeof e==`bigint`,Gc=e=>{let t=0;for(let n of e)++t;return t},Kc=e=>Xc(e.toLowerCase()),qc=(...e)=>Array.prototype.concat.apply([],e),Jc=e=>new Map(Object.entries(e)),Yc=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r<i.index&&n.push(e.slice(r,i.index)),t.length>0&&n.push(t),r=i.index+t.length}return r<e.length&&n.push(e.slice(r)),n},Xc=e=>e.replace(/\\p{M}/gu,``),Zc=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a \"${r}\" property`;return null},Qc=e=>e.match(/\\S+/g)||[],$c=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},el=class extends $c{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},tl=class extends el{tokenize_chinese_chars(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];Uc(r.charCodeAt(0))?(t.push(` `),t.push(r),t.push(` `)):t.push(r)}return t.join(``)}strip_accents(e){return e.normalize(`NFD`).replace(/\\p{Mn}/gu,``)}is_control(e){switch(e){case` `:case`\n`:case`\\r`:return!1;default:return/^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let n of e){let e=n.charCodeAt(0);e===0||e===65533||this.is_control(n)||(/^\\s$/.test(n)?t.push(` `):t.push(n))}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=class extends el{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=e.includes(`~`)?e.split(`~`).map(e=>e.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},rl=class extends el{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>hl(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},il=class extends el{constructor(e){super(e),this.pattern=nc(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??``)}},al=class extends el{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},ol=class extends al{constructor(){super(...arguments),this.form=`NFC`}},sl=class extends al{constructor(){super(...arguments),this.form=`NFD`}},cl=class extends al{constructor(){super(...arguments),this.form=`NFKC`}},ll=class extends al{constructor(){super(...arguments),this.form=`NFKD`}},ul=class extends el{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}},dl=class extends el{normalize(e){return Xc(e)}},fl=class extends el{normalize(e){return e.toLowerCase()}},pl=class extends el{normalize(e){return e=this.config.prepend+e,e}};function ml(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new tl(e);case`Precompiled`:return new nl(e);case`Sequence`:return new rl(e);case`Replace`:return new il(e);case`NFC`:return new ol(e);case`NFD`:return new sl(e);case`NFKC`:return new cl(e);case`NFKD`:return new ll(e);case`Strip`:return new ul(e);case`StripAccents`:return new dl(e);case`Lowercase`:return new fl(e);case`Prepend`:return new pl(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var hl=ml,gl=class extends $c{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},_l=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),vl=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(_l),yl=`\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E`,bl=class extends gl{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu,this.byte_encoder=_l,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},xl=class extends gl{pre_tokenize_text(e,t){return e.match(/\\w+|[^\\w\\s]+/g)||[]}},Sl=class extends gl{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},Cl=class extends gl{constructor(e){super(),this.config=e,this.pattern=nc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):Yc(e,this.pattern)}},wl=class extends gl{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${yl}]+|[${yl}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Tl=class extends gl{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)||[]}},El=class extends gl{constructor(){super(),this.pattern=RegExp(`[^\\\\s${yl}]+|[${yl}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Dl=class extends gl{constructor(e){super(),this.config=e,this.pattern=nc(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},Ol=class extends gl{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>Ml(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},kl=class extends gl{pre_tokenize_text(e){return Qc(e)}},Al=class extends gl{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;n<e.length;n+=this._length)t.push(e.slice(n,n+this._length));return t}};function jl(e){if(e===null)return null;switch(e.type){case`BertPreTokenizer`:return new El;case`Sequence`:return new Ol(e);case`Whitespace`:return new xl;case`WhitespaceSplit`:return new kl;case`Metaspace`:return new Sl(e);case`ByteLevel`:return new bl(e);case`Split`:return new Cl(e);case`Punctuation`:return new wl(e);case`Digits`:return new Tl(e);case`Replace`:return new Dl(e);case`FixedLength`:return new Al(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}var Ml=jl,Nl=class extends $c{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=/* @__PURE__ */ 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=Hc(t,this.tokens_to_ids,this.unk_token_id)),t}},Pl=class extends Nl{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Jc(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){let t=[];for(let n of e){let e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i<e.length;){let t=e.length,n=null;for(;i<t;){let r=e.slice(i,t).join(``);if(i>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},Fl=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,/* @__PURE__ */ new Map)}},Il=class{constructor(){this.root=Fl.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=Fl.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e,t=0){let n=this.root;if(n===void 0)return;let r=``;for(let i=t;i<e.length;++i){let t=e[i];if(r+=t,n=n.children.get(t),n===void 0)return;n.is_leaf&&(yield r)}}},Ll=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},Rl=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Ll(this.bos_token_id??0,0,0,0,0),i=new Ll(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=new Ll(r,this.nodes.length,e,t,n);this.begin_nodes[e].push(i),this.end_nodes[e+t].push(i),this.nodes.push(i)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function zl(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}var Bl=class extends Nl{constructor(e,t){super(e);let n=e.vocab.length;this.vocab=Array(n),this.scores=Array(n);for(let t=0;t<n;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),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=zl(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Il,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;n<t.length;){let r=!1,i=this.trie.common_prefix_search(t,n);for(let t of i){let i=this.tokens_to_ids.get(t),a=this.scores[i],o=Gc(t);e.insert(n,o,a,i),!r&&o===1&&(r=!0)}r||e.insert(n,1,this.unk_score,this.unk_token_id),n+=1}}tokenize(e){let t=new Rl(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let n of e){let e=this.tokenize(n);t.push(...e)}return t}},Vl=class{constructor(e=(e,t)=>e>t,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 e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._sift_up_from(e))}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 n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_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}},Hl=class{constructor(e){this.capacity=e,this.cache=/* @__PURE__ */ 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()}},Ul=class extends Nl{constructor(e){super(e),this.tokens_to_ids=Jc(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),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 Hl(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 n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new Vl((e,t)=>e.score<t.score),t={token:n[0],bias:0,prev:null,next:null},i=t;for(let t=1;t<n.length;++t){let r={bias:t/n.length,token:n[t],prev:i,next:null};i.next=r,this.add_node(e,i),i=r}for(;!e.is_empty();){let n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;if(n.deleted=!0,n.next.deleted=!0,n.prev){let e={...n.prev};n.prev.deleted=!0,n.prev=e,e.prev?e.prev.next=e:t=e}let r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};r.prev?(r.prev.next=r,this.add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this.add_node(e,r))}for(let e=t;e!==null;e=e.next)r.push(e.token)}else r=n;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,r),r}add_node(e,t){let n=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));n!==void 0&&(t.score=n+t.bias,e.push(t))}encode(e){let t=[];for(let n of e){if(this.ignore_merges&&this.tokens_to_ids.has(n)){t.push(n);continue}let e=this.bpe(n);for(let n of e)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let e=Array.from(this.text_encoder.encode(n)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Wl=class extends Nl{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=Jc(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function Gl(e,t){switch(e.type){case`WordPiece`:return new Pl(e);case`Unigram`:return new Bl(e,t.eos_token);case`BPE`:return new Ul(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Bl(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new Ul(e):new Pl(e):new Wl(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var Kl=Gl,ql=class extends $c{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Jl=class extends ql{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=qc(i,e),a=qc(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=qc(i,t),a=qc(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},Yl=class extends ql{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Xl=class extends ql{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=qc([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=qc(e,i,t,a),r=qc(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Zl=class extends ql{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=qc([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=qc(e,i,t,a),r=qc(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Ql=class extends ql{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>eu(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function $l(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new Jl(e);case`ByteLevel`:return new Yl(e);case`BertProcessing`:return new Xl(e);case`RobertaProcessing`:return new Zl(e);case`Sequence`:return new Ql(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var eu=$l,tu=class extends $c{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}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},nu=class extends tu{constructor(e){super(e),this.byte_decoder=vl,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(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},ru=class extends tu{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=tc(e)),e})}},iu=class extends tu{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement,` `);n==0&&r.startsWith(` `)&&(r=r.substring(1)),t.push(r)}return t}},au=class extends tu{constructor(e){super(e),this.suffix=e.suffix??``}decode_chain(e){return e.map((t,n)=>t.replaceAll(this.suffix,n===e.length-1?``:` `))}},ou=class extends tu{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 n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let n=t.filter(e=>e!==this.pad_token).join(``);return this.cleanup&&(n=tc(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},su=class extends tu{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>pu(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},cu=class extends tu{constructor(e){super(e),this.pattern=nc(this.config.pattern)}decode_chain(e){let t=this.config.content??``,n=this.pattern;return n===null?e:e.map(e=>e.replaceAll(n,t))}},lu=class extends tu{decode_chain(e){return[e.join(``)]}},uu=class extends tu{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n<this.start&&e[n]===this.content;++n)t=n+1;let n=e.length;for(let t=0;t<this.stop;++t){let r=e.length-t-1;if(e[r]===this.content)n=r;else break}return e.slice(t,n)})}},du=class extends tu{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],n=[];for(let r of e){let e=null;if(r.length===6&&r.startsWith(`<0x`)&&r.endsWith(`>`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function fu(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new nu(e);case`WordPiece`:return new ru(e);case`Metaspace`:return new iu(e);case`BPEDecoder`:return new au(e);case`CTC`:return new ou(e);case`Sequence`:return new su(e);case`Replace`:return new cu(e);case`Fuse`:return new lu(e);case`Strip`:return new uu(e);case`ByteFallback`:return new du(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var pu=fu,mu=class{constructor(e,t){let n=Zc(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=Zc(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=hl(this.tokenizer.normalizer),this.pre_tokenizer=Ml(this.tokenizer.pre_tokenizer),this.model=Kl(this.tokenizer.model,this.config),this.post_processor=eu(this.tokenizer.post_processor),this.decoder=pu(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=/* @__PURE__ */ new Map;for(let e of this.tokenizer.added_tokens){let t=new $s(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),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 Qs(i),this.splitter_normalized=new Qs(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:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Wc(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=tc(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((e,t)=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=Kc(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t<n.length-1&&(n[t+1]=n[t+1].trimStart()))}),n.flatMap(e=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:qc(r??[],i??[])}}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=/* @__PURE__ */ new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=/* @__PURE__ */ new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(e||!this.added_tokens_map.has(r))&&t.set(r,n)}return t}},hu=Object.defineProperty,gu=(e,t,n)=>t in e?hu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_u=(e,t,n)=>(gu(e,typeof t==`symbol`?t:t+``,n),n),P=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),vu=class{constructor(e,t){this.value=e,this.type=t}};function yu(e){return/\\w/.test(e)}function bu(e){return/[0-9]/.test(e)}function xu(e){return/\\s/.test(e)}var Su=[[`{%`,P.OpenStatement],[`%}`,P.CloseStatement],[`{{`,P.OpenExpression],[`}}`,P.CloseExpression],[`(`,P.OpenParen],[`)`,P.CloseParen],[`{`,P.OpenCurlyBracket],[`}`,P.CloseCurlyBracket],[`[`,P.OpenSquareBracket],[`]`,P.CloseSquareBracket],[`,`,P.Comma],[`.`,P.Dot],[`:`,P.Colon],[`|`,P.Pipe],[`<=`,P.ComparisonBinaryOperator],[`>=`,P.ComparisonBinaryOperator],[`==`,P.ComparisonBinaryOperator],[`!=`,P.ComparisonBinaryOperator],[`<`,P.ComparisonBinaryOperator],[`>`,P.ComparisonBinaryOperator],[`+`,P.AdditiveBinaryOperator],[`-`,P.AdditiveBinaryOperator],[`~`,P.AdditiveBinaryOperator],[`**`,P.ExponentiationBinaryOperator],[`*`,P.MultiplicativeBinaryOperator],[`//`,P.MultiplicativeBinaryOperator],[`/`,P.MultiplicativeBinaryOperator],[`%`,P.MultiplicativeBinaryOperator],[`=`,P.Equals]],Cu=/* @__PURE__ */ new Map([[`n`,`\n`],[`t`,` `],[`r`,`\\r`],[`b`,`\\b`],[`f`,`\\f`],[`v`,`\\v`],[`'`,`'`],[`\"`,`\"`],[`\\\\`,`\\\\`]]);function wu(e,t={}){return e.endsWith(`\n`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \\t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\\n/g,`$1`)),e.replace(/(\\s*){%(-?)\\s*(?:end)?generation\\s*(-?)%}(\\s*)/gs,(e,t,n,r,i)=>(n?``:t)+(r?``:i))}function Tu(e,t={}){let n=[],r=wu(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);)if(r[i]===`\\\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=Cu.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n}else if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`);return t},s=()=>{let e=n.at(-1);e&&e.type===P.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i<r.length&&xu(r[i]);)++i};e:for(;i<r.length;){let e=n.at(-1)?.type;if(e===void 0||e===P.CloseStatement||e===P.CloseExpression||e===P.Comment){let e=``;for(;i<r.length&&(r[i]!==`{`||r[i+1]!==`%`&&r[i+1]!==`{`&&r[i+1]!==`#`);)e+=r[i++];if(e.length>0){n.push(new vu(e,P.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new vu(t,P.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new vu(`{%`,P.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new vu(`{{`,P.OpenExpression)),a=0,i+=3;continue}if(o(xu),r.slice(i,i+3)===`-%}`){n.push(new vu(`%}`,P.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new vu(`}}`,P.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===P.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case P.Identifier:case P.NumericLiteral:case P.StringLiteral:case P.CloseParen:case P.CloseSquareBracket:break;default:{++i;let e=o(bu);if(e.length>0&&r[i]===`.`&&bu(r[i+1])){++i;let t=o(bu);e=`${e}.${t}`}n.push(new vu(`${t}${e}`,e.length>0?P.NumericLiteral:P.UnaryOperator));continue}}}for(let[e,t]of Su)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new vu(e,t)),t===P.OpenExpression?a=0:t===P.OpenCurlyBracket?++a:t===P.CloseCurlyBracket&&--a,i+=e.length;continue e}if(t===`'`||t===`\"`){++i;let e=o(e=>e!==t);n.push(new vu(e,P.StringLiteral)),++i}else if(bu(t)){let e=o(bu);if(n.at(-1)?.type!==P.Dot&&r[i]===`.`&&bu(r[i+1])){++i;let t=o(bu);e=`${e}.${t}`}n.push(new vu(e,P.NumericLiteral))}else if(yu(t)){let e=o(yu);n.push(new vu(e,P.Identifier))}else throw SyntaxError(`Unexpected character: ${t}`)}return n}var Eu=class{type=`Statement`},Du=class extends Eu{constructor(e){super(),this.body=e}type=`Program`},Ou=class extends Eu{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},ku=class extends Eu{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},Au=class extends Eu{type=`Break`},ju=class extends Eu{type=`Continue`},Mu=class extends Eu{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},Nu=class extends Eu{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},Pu=class extends Eu{constructor(e){super(),this.value=e}type=`Comment`},Fu=class extends Eu{type=`Expression`},Iu=class extends Fu{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},Lu=class extends Fu{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},Ru=class extends Fu{constructor(e){super(),this.value=e}type=`Identifier`},zu=class extends Fu{constructor(e){super(),this.value=e}type=`Literal`},Bu=class extends zu{type=`IntegerLiteral`},Vu=class extends zu{type=`FloatLiteral`},Hu=class extends zu{type=`StringLiteral`},Uu=class extends zu{type=`ArrayLiteral`},Wu=class extends zu{type=`TupleLiteral`},Gu=class extends zu{type=`ObjectLiteral`},Ku=class extends Fu{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},qu=class extends Fu{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},Ju=class extends Eu{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Yu=class extends Fu{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},Xu=class extends Fu{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},Zu=class extends Fu{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},Qu=class extends Fu{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},$u=class extends Fu{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},ed=class extends Fu{constructor(e){super(),this.argument=e}type=`SpreadExpression`},td=class extends Fu{constructor(e){super(),this.argument=e}type=`KeywordSpreadExpression`},nd=class extends Eu{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},rd=class extends Fu{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function id(e){let t=new Du([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case P.Comment:return new Pu(e[n++].value);case P.Text:return l();case P.OpenStatement:return u();case P.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===P.OpenStatement&&e[n+1]?.type===P.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new Hu(r(P.Text,`Expected text token`).value)}function u(){if(r(P.OpenStatement,`Expected opening statement token`),e[n].type!==P.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(P.OpenStatement,`Expected {% token`),i(`endif`),r(P.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(P.OpenStatement,`Expected {% token`),i(`endmacro`),r(P.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(P.OpenStatement,`Expected {% token`),i(`endfor`),r(P.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(P.OpenParen)&&(e=te(`parameters`));let t=ue();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=te(`call`);r(P.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(P.OpenStatement,`Expected '{%'`),i(`endcall`),r(P.CloseStatement,`Expected closing statement token`),c=new nd(new Lu(t,l),e,u);break}case`break`:++n,r(P.CloseStatement,`Expected closing statement token`),c=new Au;break;case`continue`:++n,r(P.CloseStatement,`Expected closing statement token`),c=new ju;break;case`filter`:{++n;let e=ue();e instanceof Ru&&o(P.OpenParen)&&(e=w(e)),r(P.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(P.OpenStatement,`Expected '{%'`),i(`endfilter`),r(P.CloseStatement,`Expected '%}'`),c=new Ju(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(P.OpenExpression,`Expected opening expression token`);let e=_();return r(P.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(P.Equals))++n,t=h();else{for(r(P.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(P.OpenStatement,`Expected {% token`),i(`endset`)}return r(P.CloseStatement,`Expected closing statement token`),new Mu(e,t,c)}function p(){let e=_();r(P.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(P.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new Ou(e,t,i)}function m(){let e=ue();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=te(`parameters`);r(P.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new Nu(e,t,n)}function h(e=!1){let t=e?ue:_,r=[t()],i=o(P.Comma);for(;i&&(++n,r.push(t()),o(P.Comma)););return i?new Wu(r):r[0]}function g(){let e=h(!0);if(!(e instanceof Ru||e instanceof Wu))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError(\"Expected `in` keyword following loop variable\");++n;let t=_();r(P.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(P.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new ku(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new rd(t,e,v())):new Yu(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new Ku(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new Ku(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new Zu(r,x())}return t??S()}function S(){let t=C();for(;;){let r;if(c(`not`,`in`))r=new vu(`not in`,P.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(P.ComparisonBinaryOperator))r=e[n++];else break;let i=C();t=new Ku(r,t,i)}return t}function C(){let t=ae();for(;o(P.AdditiveBinaryOperator);){let r=e[n];++n;let i=ae();t=new Ku(r,t,i)}return t}function ee(){let e=ie(ue());return o(P.OpenParen)?w(e):e}function w(e){let t=new Lu(e,te(`call`));return t=ie(t),o(P.OpenParen)&&(t=w(t)),t}function te(e){r(P.OpenParen,`Expected opening parenthesis for arguments list`);let t=ne(e);return r(P.CloseParen,`Expected closing parenthesis for arguments list`),t}function ne(t){let r=[],i=/* @__PURE__ */ new Set,a=!1,s=!1;for(;!o(P.CloseParen);){let c=o(P.ExponentiationBinaryOperator),l=o(P.MultiplicativeBinaryOperator)&&e[n].value===`*`;if(t===`parameters`&&(c||l))throw SyntaxError(`Argument unpacking is not allowed in parameter declarations`);if(c){if(++n,r.push(new td(_())),o(P.Comma)&&++n,!o(P.CloseParen))throw SyntaxError(\"Expected closing parenthesis: `**` must be applied to the final argument\");break}let u;if(l){if(s)throw SyntaxError(\"Only one `*` argument unpacking is allowed\");s=!0,++n,u=new ed(_())}else{if(u=_(),o(P.Equals)){if(++n,!(u instanceof Ru))throw SyntaxError(t===`parameters`?`Expected identifier for parameter declaration`:`Expected identifier for keyword argument`);let e=_();u=new $u(u,e)}if(t===`parameters`){if(!(u instanceof Ru||u instanceof $u))throw SyntaxError(`Expected identifier for parameter declaration`);let e=u instanceof Ru?u.value:u.key.value;if(i.has(e))throw SyntaxError(`Duplicate parameter name: ${e}`);i.add(e)}if(u instanceof $u)a=!0;else if(a)throw SyntaxError(t===`call`?`Positional arguments must come before keyword arguments`:`Non-default argument follows default argument`);else if(s)throw SyntaxError(\"Positional arguments must not follow `*` argument unpacking\")}r.push(u),o(P.Comma)&&++n}return r}function re(){let e=[],t=!1;for(;!o(P.CloseSquareBracket);)o(P.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(P.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new Qu(...e)}return e[0]}function ie(t){for(;o(P.Dot)||o(P.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===P.OpenSquareBracket;if(o)a=re(),r(P.CloseSquareBracket,`Expected closing square bracket`);else if(a=ue(),a.type!==`Identifier`&&a.type!==`IntegerLiteral`)throw SyntaxError(`Expected identifier or integer following dot operator`);t=new Iu(t,a,o)}return t}function ae(){let t=oe();for(;o(P.MultiplicativeBinaryOperator);){let r=e[n++],i=oe();t=new Ku(r,t,i)}return t}function oe(){let t=se();for(;o(P.ExponentiationBinaryOperator);){let r=e[n++],i=se();t=new Ku(r,t,i)}return t}function se(){let e=ce();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=ue();if(!(r instanceof Ru))throw SyntaxError(`Expected identifier for the test`);e=new Xu(e,t,r)}return e}function ce(){let e=le();for(;o(P.Pipe);){++n;let t=ue();if(!(t instanceof Ru))throw SyntaxError(`Expected identifier for the filter`);o(P.OpenParen)&&(t=w(t)),e=new qu(e,t)}return e}function le(){let t=e[n];return t&&(t.type===P.UnaryOperator||t.type===P.AdditiveBinaryOperator)&&(t.value===`-`||t.value===`+`)?new Zu(e[n++],le()):ee()}function ue(){let t=e[n++];switch(t.type){case P.NumericLiteral:{let e=t.value;return e.includes(`.`)?new Vu(Number(e)):new Bu(Number(e))}case P.StringLiteral:{let r=t.value;for(;o(P.StringLiteral);)r+=e[n++].value;return new Hu(r)}case P.Identifier:return new Ru(t.value);case P.OpenParen:{let e=h();return r(P.CloseParen,\"Expected closing parenthesis, got ${tokens[current].type} instead.\"),e}case P.OpenSquareBracket:{let e=[];for(;!o(P.CloseSquareBracket);)e.push(_()),o(P.Comma)&&++n;return++n,new Uu(e)}case P.OpenCurlyBracket:{let e=/* @__PURE__ */ new Map;for(;!o(P.CloseCurlyBracket);){let t=_();r(P.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(P.Comma)&&++n}return++n,new Gu(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n<e.length;)t.body.push(a());return t}function ad(e,t,n=1){if(t===void 0&&(t=e,e=0),n===0)throw Error(`range() step must not be zero`);let r=[];if(n>0)for(let i=e;i<t;i+=n)r.push(i);else for(let i=e;i>t;i+=n)r.push(i);return r}function od(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*o<i*n;o+=r)a.push(e[o]);return a}function sd(e){return e.replace(/\\b\\w/g,e=>e.toUpperCase())}function cd(e){return ld(/* @__PURE__ */ new Date,e)}function ld(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function ud(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}function dd(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(ud(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var fd=class extends Error{},pd=class extends Error{},md=/* @__PURE__ */ new Map,hd=class{type=`RuntimeValue`;value;get builtins(){return md}constructor(e=void 0){this.value=e}__bool__(){return new R(!!this.value)}toString(){return String(this.value)}},F=class extends hd{type=`IntegerValue`},I=class extends hd{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},L=class extends hd{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new B(()=>new L(this.value.toUpperCase()))],[`lower`,new B(()=>new L(this.value.toLowerCase()))],[`strip`,new B(()=>new L(this.value.trim()))],[`title`,new B(()=>new L(sd(this.value)))],[`capitalize`,new B(()=>new L(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new F(this.value.length)],[`rstrip`,new B(()=>new L(this.value.trimEnd()))],[`lstrip`,new B(()=>new L(this.value.trimStart()))],[`startswith`,new B(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof L)return new R(this.value.startsWith(t.value));if(t instanceof z){for(let e of t.value){if(!(e instanceof L))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new R(!0)}return new R(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new B(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof L)return new R(this.value.endsWith(t.value));if(t instanceof z){for(let e of t.value){if(!(e instanceof L))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new R(!0)}return new R(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new B(e=>{let t=e[0]??new Cd;if(!(t instanceof L||t instanceof Cd))throw Error(`sep argument must be a string or null`);let n=e[1]??new F(-1);if(!(n instanceof F))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof Cd){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new z(r.map(e=>new L(e)))})],[`replace`,new B(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof L&&n instanceof L))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new Cd:e[2]:new Cd,!(r instanceof F||r instanceof Cd))throw Error(`replace() count argument must be a number or null`);return new L(dd(this.value,t.value,n.value,r.value))})]])}},R=class extends hd{type=`BooleanValue`},gd=/[\\x7f-\\uffff]/g;function _d(e){return e.replace(gd,e=>`\\\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function vd(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=_d(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`\n`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>vd(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=_d(s));let c=`${s}${l}${vd(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var yd=class extends hd{type=`ObjectValue`;_builtins;__bool__(){return new R(this.value.size>0)}get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`get`,new B(([e,t])=>{if(!(e instanceof L))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Cd})],[`items`,new B(()=>this.items())],[`keys`,new B(()=>this.keys())],[`values`,new B(()=>this.values())],[`dictsort`,new B(e=>{let t=/* @__PURE__ */ new Map,n=e.filter(e=>e instanceof bd?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new R(!1);if(!(r instanceof R))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new L(`key`);if(!(i instanceof L))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new R(!1);if(!(a instanceof R))throw Error(`reverse must be a boolean`);return new z(Array.from(this.value.entries()).map(([e,t])=>new z([new L(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=Md(e.value[n],t.value[n],r.value);return a.value?-o:o}))})]])}items(){return new z(Array.from(this.value.entries()).map(([e,t])=>new z([new L(e),t])))}keys(){return new z(Array.from(this.value.keys()).map(e=>new L(e)))}values(){return new z(Array.from(this.value.values()))}toString(){return vd(this,{},0,!1)}},bd=class extends yd{type=`KeywordArgumentsValue`},xd=class extends hd{type=`NamespaceValue`;toString(){return vd(this,{},0,!1)}},z=class extends hd{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`length`,new F(this.value.length)]])}__bool__(){return new R(this.value.length>0)}toString(){return vd(this,{},0,!1)}},Sd=class extends z{type=`TupleValue`},B=class extends hd{type=`FunctionValue`},Cd=class extends hd{type=`NullValue`},V=class extends hd{type=`UndefinedValue`};function wd(e){let t;if(e instanceof z?t=e.value:e instanceof L&&(t=Array.from(e.value,e=>new L(e))),!t||t.length!==2)throw Error(`namespace expected an object or an iterable of [key, value] pairs`);let[n,r]=t;if(!(n instanceof L))throw Error(`namespace keys must be strings`);return[n,r]}var Td=class{constructor(e){this.parent=e}variables=/* @__PURE__ */ new Map([[`namespace`,new B(e=>{let t=e.slice(),n;if(t.at(-1)instanceof bd&&(n=t.pop()),t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let r=/* @__PURE__ */ new Map;if(t.length===1){let e=t[0];if(e instanceof yd)for(let[t,n]of e.value)r.set(t,n);else if(e instanceof z)for(let t of e.value){let[e,n]=wd(t);r.set(e.value,n)}else throw Error(`'${e.type}' object is not iterable`)}if(n)for(let[e,t]of n.value)r.set(e,t);return new xd(r)})]]);tests=Td.TESTS;set(e,t){return this.declareVariable(e,Ld(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new V}catch{return new V}}},Ed=Td;_u(Ed,`TESTS`,/* @__PURE__ */ new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof B],[`odd`,e=>{if(!(e instanceof F))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof F))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof F||e instanceof I],[`integer`,e=>e instanceof F],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof yd],[`sequence`,e=>e instanceof z||e instanceof yd||e instanceof L],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function Dd(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,ad),e.set(`strftime_now`,cd),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function Od(e){return e instanceof yd||e instanceof xd}function kd(e){return e instanceof F||e instanceof I||e instanceof R}function Ad(e){return e instanceof R?Number(e.value):e.value}function jd(e,t){let n=t.split(`.`),r=e;for(let e of n)if(Od(r))r=r.value.get(e)??new V;else if(r instanceof z){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&t<r.value.length)r=r.value[t];else return new V}else return new V;return r}function Md(e,t,n=!1){if(e instanceof Cd&&t instanceof Cd)return 0;if(e instanceof Cd||t instanceof Cd)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof V&&t instanceof V)return 0;if(e instanceof V||t instanceof V)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(kd(e)&&kd(t)){let n=Ad(e),r=Ad(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type===`StringValue`){let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}throw Error(`Cannot compare type: ${e.type}`)}function Nd(e){if(e.type===`Identifier`)return{name:e.value};let t=e;return{name:t.key.value,defaultValue:t.value}}function Pd(e){return e===`kwargs`||e===`varargs`}function Fd(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=e=>{Pd(e)&&n.add(e)},a=e=>{if(e.type===`Identifier`)i(e.value);else if(e.type===`TupleLiteral`)for(let t of e.value)a(t)},o=e=>{i(Nd(e).name)},s=e=>{for(let t of e){let e=Nd(t);e.defaultValue&&l(e.defaultValue)}},c=e=>{e.type===`CallExpression`&&l(e.args)},l=e=>{if(Array.isArray(e))for(let t of e)l(t);else if(e instanceof Map)for(let[t,n]of e)l(t),l(n);else if(e instanceof Eu)switch(e.type){case`For`:{let t=e;if(a(t.loopvar),t.iterable.type===`SelectExpression`){let e=t.iterable;l(e.lhs),l(t.body),l(t.defaultBlock),l(e.test);return}l(t.iterable),l(t.body),l(t.defaultBlock);return}case`Set`:{let t=e;a(t.assignee),l(t.value),l(t.body);return}case`Macro`:{let t=e;for(let e of t.args)o(e);s(t.args),l(t.body);return}case`CallStatement`:{let t=e;l(t.call);for(let e of t.callerArgs??[])o(e);s(t.callerArgs??[]),l(t.body);return}case`FilterStatement`:{let t=e;l(t.body),c(t.filter);return}case`Identifier`:{let t=e.value;Pd(t)&&!n.has(t)&&r.add(t);return}case`MemberExpression`:{let t=e;l(t.object),t.computed&&l(t.property);return}case`FilterExpression`:{let t=e;l(t.operand),c(t.filter);return}case`TestExpression`:l(e.operand);return;case`SelectExpression`:{let t=e;l(t.test),l(t.lhs);return}case`KeywordArgumentExpression`:l(e.value);return;default:for(let t of Object.values(e))l(t)}};for(let t of e)o(t);return l(t),r}var Id=class{global;constructor(e){this.global=e??new Ed}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new R(n.value==r.value);case`!=`:return new R(n.value!=r.value)}if(n instanceof V||r instanceof V){if(r instanceof V&&[`in`,`not in`].includes(e.operator.value))return new R(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}if(n instanceof Cd||r instanceof Cd)throw Error(`Cannot perform operation on null values`);if(e.operator.value===`~`)return new L(n.value.toString()+r.value.toString());if(e.operator.value===`**`&&kd(n)&&kd(r)){let e=Ad(n),t=Ad(r);if(e===0&&t<0)throw Error(`0.0 cannot be raised to a negative power`);let i=e**t;if(!Number.isFinite(i))throw Error(`Exponentiation result is not a finite real number`);return n instanceof I||r instanceof I||t<0?new I(i):new F(i)}if((n instanceof F||n instanceof I)&&(r instanceof F||r instanceof I)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof I||r instanceof I?new I(a):new F(a)}case`/`:return new I(t/i);case`//`:{let e=Math.floor(t/i);return n instanceof I||r instanceof I?new I(e):new F(e)}case`%`:{let e=t%i;return n instanceof I||r instanceof I?new I(e):new F(e)}case`<`:return new R(t<i);case`>`:return new R(t>i);case`>=`:return new R(t>=i);case`<=`:return new R(t<=i)}}else if(n instanceof z&&r instanceof z)switch(e.operator.value){case`+`:return new z(n.value.concat(r.value))}else if(r instanceof z){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new R(t);case`not in`:return new R(!t)}}if(n instanceof L||r instanceof L)switch(e.operator.value){case`+`:return new L(n.value.toString()+r.value.toString())}if(n instanceof L&&r instanceof L)switch(e.operator.value){case`in`:return new R(r.value.includes(n.value));case`not in`:return new R(!r.value.includes(n.value))}if(n instanceof L&&r instanceof yd)switch(e.operator.value){case`in`:return new R(r.value.has(n.value));case`not in`:return new R(!r.value.has(n.value))}throw SyntaxError(`Unknown operator \"${e.operator.value}\" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=/* @__PURE__ */ new Map,i=(e,t)=>{if(r.has(e))throw Error(`Got multiple values for keyword argument '${e}'`);r.set(e,t)};for(let r of e)if(r.type===`SpreadExpression`){let e=r,i=this.evaluate(e.argument,t);if(!(i instanceof z))throw Error(`Cannot unpack non-iterable type: ${i.type}`);for(let e of i.value)n.push(e)}else r.type!==`KeywordArgumentExpression`&&r.type!==`KeywordSpreadExpression`&&n.push(this.evaluate(r,t));for(let n of e)if(n.type===`KeywordArgumentExpression`){let e=n;i(e.key.value,this.evaluate(e.value,t))}else if(n.type===`KeywordSpreadExpression`){let e=n,r=this.evaluate(e.argument,t);if(!(r instanceof yd))throw Error(`Argument after ** must be a mapping, not ${r.type}`);for(let[e,t]of r.value)i(e,t)}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new L(vd(e,{}));if(e instanceof z)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new F(e.value.length);case`reverse`:return new z(e.value.slice().reverse());case`sort`:return new z(e.value.slice().sort((e,t)=>Md(e,t,!1)));case`join`:return new L(e.value.map(e=>e.value).join(``));case`string`:return new L(vd(e,{},0,!1));case`unique`:{let t=/* @__PURE__ */ new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new z(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof L)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof B)return t.value([],n);if(t instanceof F)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new L(e.value.trim());case`indent`:return new L(e.value.split(`\n`).map((e,t)=>t===0||e.length===0?e:` `+e).join(`\n`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new F(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new I(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof F||e instanceof I)switch(r.value){case`abs`:return e instanceof F?new F(Math.abs(e.value)):new I(Math.abs(e.value));case`int`:return new F(Math.floor(e.value));case`float`:return new I(e.value);case`string`:return new L(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof yd)switch(r.value){case`items`:return new z(Array.from(e.value.entries()).map(([e,t])=>new z([new L(e),t])));case`length`:return new F(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof B?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof R)switch(r.value){case`bool`:return new R(e.value);case`int`:return new F(+!!e.value);case`float`:return new I(+!!e.value);case`string`:return new L(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter \"${r.value}\" to type: ${e.type}`)}if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new Cd;if(!(i instanceof F||i instanceof Cd))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new R(!1);if(!(a instanceof R))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new R(!1);if(!(o instanceof R))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new Cd,c=null;if(s instanceof z||s instanceof Sd){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof L)||!(t instanceof L))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof Cd))throw Error(`If set, separators must be a tuple of two strings`);return new L(vd(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}if(i===`join`){let t;if(e instanceof L)t=Array.from(e.value);else if(e instanceof z)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new L(``);if(!(s instanceof L))throw Error(`separator must be a string`);return new L(t.join(s.value))}if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new F(0):new I(0));if(e instanceof L){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new F(t):new I(t)}if(e instanceof F||e instanceof I)return e;if(e instanceof R)return i===`int`?new F(+!!e.value):new I(+!!e.value);throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`)}if(i===\"default\"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new L(``),o=t[1]??i.get(`boolean`)??new R(!1);if(!(o instanceof R))throw Error(\"`default` filter flag must be a boolean\");return e instanceof V||o.value&&!e.__bool__().value?a:e}if(e instanceof z){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new R(!1);if(!(a instanceof R))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new R(!1);if(!(o instanceof R))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new Cd;if(!(s instanceof L||s instanceof F||s instanceof Cd))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof Cd?e:jd(e,s instanceof F?String(s.value):s.value);return new z(e.value.slice().sort((e,t)=>{let n=Md(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!Od(e)))throw Error(`\\`${i}\\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \\`${i}\\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new z(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof L))throw Error(`attribute must be a string`);let r=t.get(`default`);return new z(e.value.map(e=>{if(!Od(e))throw Error(`items in map must be an object`);let t=jd(e,n.value);return t instanceof V?r??new V:t}))}throw Error(\"`map` expressions without `attribute` set are not currently supported.\")}}throw Error(`Unknown ArrayValue filter: ${i}`)}if(e instanceof L){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new F(4);if(!(a instanceof F))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new R(!1),s=t.at(2)??i.get(`blank`)??new R(!1),c=e.value.split(`\n`),l=` `.repeat(a.value);return new L(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(`\n`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof B))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new bd(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}if(e instanceof yd){let t=e.builtins.get(i);if(t&&t instanceof B){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new bd(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new R(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new V}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new R(!n.value);case`+`:case`-`:{let t=e.operator.value===`-`?-1:1;if(n instanceof F||n instanceof I||n instanceof R){let e=t*(n instanceof R?+!!n.value:n.value);return n instanceof I?new I(e):new F(e)}throw SyntaxError(`Unknown operator \"${e.operator.value}\" for ${n.type}`)}default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new L(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new bd(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof z||e instanceof L))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof F||r instanceof V))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof F||i instanceof V))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof F||a instanceof V))throw Error(`Slice step must be numeric or undefined`);return e instanceof z?new z(od(e.value,r.value,i.value,a.value)):new L(od(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=e.property.type===`IntegerLiteral`?new F(e.property.value):new L(e.property.value);let i;if(Od(n)){if(!(r instanceof L))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??(n instanceof yd?n.builtins.get(r.value):void 0)}else if(n instanceof z||n instanceof L){if(r instanceof F)i=n.value.at(r.value),n instanceof L&&(i=new L(n.value.at(r.value)));else if(r instanceof L)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`)}else{if(!(r instanceof L))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof hd?i:new V}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof z))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;e<r.value.length;++e){let n=r.value[e];if(n.type!==`Identifier`)throw Error(`Cannot unpack to non-identifier in set: ${n.type}`);t.setVariable(n.value,i[e])}}else if(e.assignee.type===`MemberExpression`){let r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof xd))throw Error(`cannot assign attribute on non-namespace object`);if(r.property.type!==`Identifier`)throw Error(`Cannot assign to member with non-identifier property`);i.value.set(r.property.value,n)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Cd}evaluateIf(e,t){let n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let n=new Ed(t),r,i;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=this.evaluate(t.lhs,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof z||i instanceof yd))throw Error(`Expected iterable or object type in for loop: got ${i.type}`);i instanceof yd&&(i=i.keys());let a=[],o=[];for(let t=0;t<i.value.length;++t){let s=new Ed(n),c=i.value[t],l;if(e.loopvar.type===`Identifier`)l=t=>t.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r<t.value.length;++r){if(t.value[r].type!==`Identifier`)throw Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,n.value[r])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);r&&(l(s),!this.evaluate(r,s).__bool__().value)||(a.push(c),o.push(l))}let s=``,c=!0;for(let t=0;t<a.length;++t){let r=/* @__PURE__ */ new Map([[`index`,new F(t+1)],[`index0`,new F(t)],[`revindex`,new F(a.length-t)],[`revindex0`,new F(a.length-t-1)],[`first`,new R(t===0)],[`last`,new R(t===a.length-1)],[`length`,new F(a.length)],[`previtem`,t>0?a[t-1]:new V],[`nextitem`,t<a.length-1?a[t+1]:new V]]);n.setVariable(`loop`,new yd(r)),o[t](n);try{let t=this.evaluateBlock(e.body,n);s+=t.value}catch(e){if(e instanceof pd)continue;if(e instanceof fd)break;throw e}c=!1}if(c){let t=this.evaluateBlock(e.defaultBlock,n);s+=t.value}return new L(s)}bindMacroArguments(e,t,n,r,i){let a=r.slice(),o=/* @__PURE__ */ new Map;a.at(-1)instanceof bd&&(o=new Map(a.pop().value));let s=[];for(let e=0;e<t.length;++e){let{name:n,defaultValue:r}=Nd(t[e]),c=a[e];c===void 0&&o.has(n)&&(c=o.get(n),o.delete(n)),c===void 0&&r!==void 0&&s.push([n,r]),i.setVariable(n,c??new V)}if(n.has(`kwargs`))i.setVariable(`kwargs`,new yd(o));else if(o.size>0)throw Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(n.has(`varargs`))i.setVariable(`varargs`,new z(a.slice(t.length)));else if(a.length>t.length)throw Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(let[e,t]of s)i.setVariable(e,this.evaluate(t,i))}evaluateMacro(e,t){let n=Fd(e.args,e.body);return t.setVariable(e.name.value,new B((t,r)=>{let i=new Ed(r);return this.bindMacroArguments(`'${e.name.value}'`,e.args,n,t,i),this.evaluateBlock(e.body,i)})),new Cd}evaluateCallStatement(e,t){let n=e.callerArgs??[],r=Fd(n,e.body),i=new B(i=>{let a=new Ed(t);return this.bindMacroArguments(`None`,n,r,i,a),this.evaluateBlock(e.body,a)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new bd(o));let s=this.evaluate(e.call.callee,t);if(s.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${s.type}`);let c=new Ed(t);return c.setVariable(`caller`,i),s.value(a,c)}evaluateFilterStatement(e,t){let n=this.evaluateBlock(e.body,t);return this.applyFilter(n,e.filter,t)}evaluate(e,t){if(!e)return new V;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 fd;case`Continue`:throw new pd;case`IntegerLiteral`:return new F(e.value);case`FloatLiteral`:return new I(e.value);case`StringLiteral`:return new L(e.value);case`ArrayLiteral`:return new z(e.value.map(e=>this.evaluate(e,t)));case`TupleLiteral`:return new Sd(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=/* @__PURE__ */ new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof L))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new yd(n)}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 Cd;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function Ld(e){switch(typeof e){case`number`:return Number.isInteger(e)?new F(e):new I(e);case`string`:return new L(e);case`boolean`:return new R(e);case`undefined`:return new V;case`object`:return e===null?new Cd:Array.isArray(e)?new z(e.map(Ld)):new yd(new Map(Object.entries(e).map(([e,t])=>[e,Ld(t)])));case`function`:return new B((t,n)=>Ld(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var Rd=`\n`,zd=`{%- `,Bd=` -%}`,Vd=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function Hd(e){switch(e.operator.type){case`ExponentiationBinaryOperator`:return Vd.EXPONENTIATION;case`MultiplicativeBinaryOperator`:return Vd.MULTIPLICATIVE;case`AdditiveBinaryOperator`:return Vd.ADDITIVE;case`ComparisonBinaryOperator`:return Vd.COMPARISON;case`Identifier`:return e.operator.value===`and`?Vd.LOGICAL_AND:e.operator.value===`in`||e.operator.value===`not in`?Vd.COMPARISON:Vd.LOGICAL_OR}return Vd.LOGICAL_OR}function Ud(e){switch(e.type){case`SelectExpression`:case`Ternary`:return Vd.CONDITIONAL;case`BinaryExpression`:return Hd(e);case`UnaryExpression`:return e.operator.value===`not`?Vd.LOGICAL_NOT:Vd.UNARY_SIGN;case`TestExpression`:return Vd.TEST;case`FilterExpression`:return Vd.FILTER;default:return Vd.ATOM}}function Wd(e,t){let n=nf(e);return Ud(e)<t?`(${n})`:n}function Gd(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return qd(e.body,0,n).replace(/\\n$/,``)}function Kd(...e){return zd+e.join(` `)+Bd}function qd(e,t,n){return e.map(e=>Yd(e,t,n)).join(Rd)}function Jd(e){return e.map(e=>nf(e)).join(`, `)}function Yd(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return qd(e.body,t,n);case`If`:return Xd(e,t,n);case`For`:return Zd(e,t,n);case`Set`:return Qd(e,t,n);case`Macro`:return $d(e,t,n);case`Break`:return r+Kd(`break`);case`Continue`:return r+Kd(`continue`);case`CallStatement`:return ef(e,t,n);case`FilterStatement`:return tf(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+nf(e)+` -}}`}}function Xd(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+Kd(`if`,nf(i[0].test))+Rd+qd(i[0].body,t+1,n);for(let e=1;e<i.length;++e)o+=Rd+r+Kd(`elif`,nf(i[e].test))+Rd+qd(i[e].body,t+1,n);return a&&a.alternate.length>0&&(o+=Rd+r+Kd(`else`)+Rd+qd(a.alternate,t+1,n)),o+=Rd+r+Kd(`endif`),o}function Zd(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${nf(t.lhs)} if ${nf(t.test)}`}else i=nf(e.iterable);let a=r+Kd(`for`,nf(e.loopvar),`in`,i)+Rd+qd(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=Rd+r+Kd(`else`)+Rd+qd(e.defaultBlock,t+1,n)),a+=Rd+r+Kd(`endfor`),a}function Qd(e,t,n){let r=n.repeat(t),i=nf(e.assignee),a=e.value?nf(e.value):``,o=r+Kd(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+Rd+qd(e.body,t+1,n)+Rd+r+Kd(`endset`)}function $d(e,t,n){let r=n.repeat(t),i=Jd(e.args);return r+Kd(`macro`,`${e.name.value}(${i})`)+Rd+qd(e.body,t+1,n)+Rd+r+Kd(`endmacro`)}function ef(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${Jd(e.callerArgs)})`:``,a=nf(e.call),o=r+Kd(`call${i}`,a)+Rd;return o+=qd(e.body,t+1,n)+Rd,o+=r+Kd(`endcall`),o}function tf(e,t,n){let r=n.repeat(t),i=r+Kd(`filter`,e.filter.type===`Identifier`?e.filter.value:nf(e.filter))+Rd;return i+=qd(e.body,t+1,n)+Rd,i+=r+Kd(`endfilter`),i}function nf(e){switch(e.type){case`SpreadExpression`:return`*${nf(e.argument)}`;case`KeywordSpreadExpression`:return`**${nf(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:{let t=e.value;return Object.is(t,-0)?`-0.0`:t%1==0?t.toFixed(1):t.toString()}case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let t=e,n=Hd(t),r=Wd(t.left,n),i=Wd(t.right,n+1);return`${r} ${t.operator.value} ${i}`}case`UnaryExpression`:{let t=e,n=t.argument.type===`UnaryExpression`?Ud(t):Vd.ATOM;return t.operator.value+(t.operator.value===`not`?` `:``)+Wd(t.argument,n)}case`CallExpression`:{let t=e,n=Jd(t.args);return`${nf(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=Wd(t.object,Vd.ATOM),r=nf(t.property);return!t.computed&&t.property.type!==`Identifier`&&t.property.type!==`IntegerLiteral`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=Wd(t.operand,Vd.FILTER);return t.filter.type===`CallExpression`?`${n} | ${nf(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${Wd(t.lhs,Vd.LOGICAL_OR)} if ${Wd(t.test,Vd.LOGICAL_OR)}`}case`TestExpression`:{let t=e;return`${Wd(t.operand,Vd.TEST)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=Jd(e.value),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${nf(e)}: ${nf(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?nf(t.start):``}:${t.stop?nf(t.stop):``}${t.step?`:${nf(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${nf(t.value)}`}case`Ternary`:{let t=e;return`${Wd(t.trueExpr,Vd.LOGICAL_OR)} if ${Wd(t.condition,Vd.LOGICAL_OR)} else ${Wd(t.falseExpr,Vd.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var rf=class{parsed;constructor(e){let t=Tu(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=id(t)}render(e){let t=new Ed;if(Dd(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new Id(t).run(this.parsed).value}format(e){return Gd(this.parsed,e?.indent||` `)}},af={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`},of=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=ds.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=ds.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=ds.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,af[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await ds.promises.readFile(this.filePath)).buffer}async blob(){let e=await ds.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await ds.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},sf=class{constructor(e){this._mt=/* @__PURE__ */ 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(j.IS_CRYPTO_AVAILABLE){let t=/* @__PURE__ */ new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}Number.isSafeInteger(e)&&(e=Math.abs(e));let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t|0);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(0x6c078965,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,0x5d588b65))-i>>>0;t[0]=0x80000000,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&0x80000000|e[(t+1)%624]&0x7fffffff;e[t]=(e[(t+397)%624]^n>>>1^(n&1?0x9908b0df:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&0x9d2c5680,t^=t<<15&0xefc60000,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/0x20000000000000}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[cf(this._random_fn,t)]}};function cf(e,t){let n=0;for(let e=0;e<t.length;++e)n+=t[e];let r=e()*n;for(let e=0;e<t.length;++e)if(r-=t[e],r<0)return e;return t.length-1}var lf=new sf,uf=Object.freeze({Random:sf,seed:lf.seed.bind(lf),random:lf.random.bind(lf),gauss:lf.gauss.bind(lf),shuffle:lf.shuffle.bind(lf),choices:lf.choices.bind(lf)}),df=e=>cf(uf.random,e),ff=new sf,pf=class{constructor(e){this.path=e}async match(e){let t=new of(fs.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=fs.join(this.path,e),i=r+`.tmp.${j.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${ff._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await ds.promises.mkdir(fs.dirname(r),{recursive:!0});let s=ds.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{t?n(t):e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await ds.promises.rename(i,r)}catch(e){try{await ds.promises.unlink(i)}catch{}throw e}}async delete(e){let t=fs.join(this.path,e);try{return await ds.promises.unlink(t),!0}catch{return!1}}},mf={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`},hf=100,gf=/^(\\b[\\w\\-.]+\\b\\/)?\\b[\\w\\-.]{1,96}\\b$/;function _f(...e){return e=e.map((t,n)=>(n&&(t=t.replace(/* @__PURE__ */ RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(/* @__PURE__ */ RegExp(`/$`),``)),t)),e.join(`/`)}function vf(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function yf(e){return!(!gf.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function bf(e,t={},...n){return JSON.stringify([e,t.revision??`main`,t.cache_dir??null,t.local_files_only??!1,...n])}var xf=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name=`ModelFileNotFoundError`,this.status=t}},Sf=/* @__PURE__ */ new Set([401,403,404]);function Cf(e,t,n){if(!n)return null;let r=`${mf[e]??`Error (${e}) occurred while trying to load file`}: \"${t}\".`;throw Sf.has(e)?new xf(r,{status:e}):Error(r)}async function wf(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&N.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function Tf(e){return vf(e,[`blob:`])}function Ef(e,{allowUnresolved:t=!1}={}){let n;if(typeof location<`u`&&location.href)n=location.href;else if(cs!==void 0&&self.location.href)n=self.location.href;else return e;try{return new URL(e,n).href}catch(n){if(!t)throw n;return e}}var Df=`SHA-256`,Of=`experimental_transformers-hash-cache`,kf=e=>({algorithm:Df,value:e}),Af=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Of),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let e=await(await navigator.crossOriginStorage.requestFileHandle(kf(t))).getFile();return new Response(e,{headers:{\"Content-Length\":String(e.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(kf(t),{create:!0,origins:`*`})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(Df,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function jf(e=null){let t=null;if(M.useCustomCache){if(!M.customCache)throw Error(\"`env.useCustomCache=true`, but `env.customCache` is not defined.\");if(!M.customCache.match||!M.customCache.put)throw Error(\"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\");t=M.customCache}if(!t&&M.experimental_useCrossOriginStorage&&Af.isAvailable()&&(t=new Af),!t&&M.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(M.cacheKey)}catch(e){N.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&M.useFSCache){if(!j.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new pf(e??M.cacheDir)}return t}async function Mf(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Nf=new class{#e;#t;constructor(e){this.#e=e,this.#t=/* @__PURE__ */ new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function Pf(e,t){let n=Nf.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Nf.delete(e),Promise.reject(t)));return Nf.put(e,r),r}async function Ff(e){if(!vf(e,[`http:`,`https:`]))return null;let t=zf(e);return t.set(`Range`,`bytes=0-0`),M.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function If(e,t,n={}){return Pf(bf(e,n,t),()=>Lf(e,t,n))}async function Lf(e,t,n){let r=await jf(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=Bf(e,t,n,r),c=await Vf(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(M.allowLocalModels&&!vf(i,[`http:`,`https:`]))try{let e=await Rf(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(M.allowRemoteModels&&!n.local_files_only&&s){let e=await Ff(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \\d+-\\d+\\/(\\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}e&&e.status!==404&&e.status!==416&&Cf(e.status,a,!0)}return{exists:!1,fromCache:!1}}async function Rf(e){return M.useFS&&!vf(e,[`http:`,`https:`,`blob:`])?new of(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):M.fetch(e,{headers:zf(e)})}function zf(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!process.env?.TESTING_REMOTELY,r=M.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),vf(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function Bf(e,t,n={},r=null){let i=n.revision??`main`,a=_f(e,t),o=yf(e),s=o?_f(M.localModelPath,a):a,c=_f(M.remoteHost,M.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof pf?i===`main`?a:_f(e,i,t):c,validModelId:o}}async function Vf(e,t,n){if(e)return await Mf(e,t,n)}async function Hf(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0&&!(typeof Cache<`u`&&n instanceof Cache&&!vf(Ef(r,{allowUnresolved:!0}),[`http:`,`https:`]))){if(!a){let a=o.progress_callback?n=>Hs(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{N.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Uf(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=Bf(e,t,r,a),d,f=!1,p;p=await Vf(a,s,l);let m=p!==void 0;if(m)d=l;else{if(M.allowLocalModels){if(!vf(o,[`http:`,`https:`]))try{p=await Rf(s),d=s}catch(e){N.warn(`Unable to load from local path \"${s}\": \"${e}\"`)}else if(r.local_files_only)throw Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${o}.`);else if(!M.allowRemoteModels)throw Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!M.allowRemoteModels){if(n)throw new xf(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${s}\".`);return null}if(!u)throw new xf(`Local file missing at \"${s}\" and download aborted due to invalid model ID \"${e}\".`);if(p=await Rf(c),p.status!==200)return Cf(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}Hs(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(j.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),Hs(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await If(e,t,r);n.size&&(i=n.size)}catch{}n=await wf(p,n=>{Hs(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await Hf(e,t,a,d,p,h,r),j.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;Hs(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(Hs(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!j.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof of)return p.filePath;let g=await a?.match(d);if(g instanceof of)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var Wf=/* @__PURE__ */ new Map;async function Gf(e,t,n=!0,r={},i=!1){if(!M.allowLocalModels){if(r.local_files_only)throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\");if(!M.allowRemoteModels)throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")}let a=bf(e,r,t,n,i),{progress_callback:o}=r,s=o instanceof Us?o.loads:Wf,c=s.get(a);return c||(Hs(o,{status:`initiate`,name:e,file:t}),c=jf(r.cache_dir).then(a=>Uf(e,t,n,r,i,a)),s===Wf&&(c=c.finally(()=>Wf.delete(a))),s.set(a,c)),await c}async function Kf(e,t,n=!0,r={}){let i=await Gf(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function qf(e,t,n=!0,r={}){let i=await Kf(e,t,n,r);return i===null?{}:JSON.parse(i)}function Jf(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o<i;++o)for(let i=0;i<a;++i){let s=o*a+i,p=(i+.5)/c-.5,m=(o+.5)/l-.5,h=Math.floor(p),g=Math.floor(m),_=Math.min(h+1,r-1),v=Math.min(g+1,n-1);h=Math.max(h,0),g=Math.max(g,0);let y=p-h,b=m-g,x=(1-y)*(1-b),S=y*(1-b),C=(1-y)*b,ee=y*b,w=g*r,te=v*r,ne=w+h,re=w+_,ie=te+h,ae=te+_;for(let n=0;n<t;++n){let t=n*d;u[n*f+s]=x*e[t+ne]+S*e[t+re]+C*e[t+ie]+ee*e[t+ae]}}return u}function Yf(e,t,n){let r=Array(n.length),i=Array(n.length);for(let e=n.length-1,a=1;e>=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,i=n;e>=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function Xf(e){let t=$f(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function Zf(e){let t=$f(e)[0],n=0;for(let r=0;r<e.length;++r)n+=Math.exp(e[r]-t);let r=Math.log(n);return e.map(e=>e-t-r)}function Qf(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}function $f(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],n=r);return[t,n]}function ep(e){return e>0&&!(e&e-1)}var tp=class{constructor(e){if(this.size=e|0,this.size<=1||!ep(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;e<this.table.length;e+=2){let t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){let n=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let n=t||Array(e.length>>>1);for(let t=0;t<e.length;t+=2)n[t>>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t<n.length;t+=2)n[t]=e[t>>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleTransform2(t,e,o,n,i)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleTransform4(t,e,o,r,i,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o<r;o+=a){let r=o+t-1;for(let a=o,s=0;a<r;a+=2,s+=i){let r=a,i=r+t,o=i+t,c=o+t,u=e[r],d=e[r+1],f=e[i],p=e[i+1],m=e[o],h=e[o+1],g=e[c],_=e[c+1],v=l[s],y=n*l[s+1],b=f*v-p*y,x=f*y+p*v,S=l[2*s],C=n*l[2*s+1],ee=m*S-h*C,w=m*C+h*S,te=l[3*s],ne=n*l[3*s+1],re=g*te-_*ne,ie=g*ne+_*te,ae=u+ee,oe=d+w,se=u-ee,ce=d-w,le=b+re,ue=x+ie,T=n*(b-re),de=n*(x-ie);e[r]=ae+le,e[r+1]=oe+ue,e[i]=se+de,e[i+1]=ce-T,e[o]=ae-le,e[o+1]=oe-ue,e[c]=se-de,e[c+1]=ce+T}}}}_singleTransform2(e,t,n,r,i){let a=e[r],o=e[r+1],s=e[r+i],c=e[r+i+1];t[n]=a+s,t[n+1]=o+c,t[n+2]=a-s,t[n+3]=o-c}_singleTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+1],u=e[r+i],d=e[r+i+1],f=e[r+o],p=e[r+o+1],m=e[r+s],h=e[r+s+1],g=c+f,_=l+p,v=c-f,y=l-p,b=u+m,x=d+h,S=a*(u-m),C=a*(d-h);t[n]=g+b,t[n+1]=_+x,t[n+2]=v+C,t[n+3]=y-S,t[n+4]=g-b,t[n+5]=_-x,t[n+6]=v-C,t[n+7]=y+S}_realTransform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleRealTransform2(t,e,o,n>>>1,i>>>1)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleRealTransform4(t,e,o,r>>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o<r;o+=a)for(let r=0,a=0;r<=c;r+=2,a+=i){let i=o+r,u=i+s,d=u+s,f=d+s,p=e[i],m=e[i+1],h=e[u],g=e[u+1],_=e[d],v=e[d+1],y=e[f],b=e[f+1],x=p,S=m,C=l[a],ee=n*l[a+1],w=h*C-g*ee,te=h*ee+g*C,ne=l[2*a],re=n*l[2*a+1],ie=_*ne-v*re,ae=_*re+v*ne,oe=l[3*a],se=n*l[3*a+1],ce=y*oe-b*se,le=y*se+b*oe,ue=x+ie,T=S+ae,de=x-ie,fe=S-ae,pe=w+ce,me=te+le,he=n*(w-ce),ge=n*(te-le);if(e[i]=ue+pe,e[i+1]=T+me,e[u]=de+ge,e[u+1]=fe-he,r===0){e[d]=ue-pe,e[d+1]=T-me;continue}if(r===c)continue;let _e=o+s-r,ve=o+t-r;e[_e]=de-n*ge,e[_e+1]=-fe-n*he,e[ve]=ue-n*pe,e[ve+1]=-T+n*me}}let u=r>>>1;for(let t=2;t<u;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,n,r,i){let a=e[r],o=e[r+i];t[n]=a+o,t[n+1]=0,t[n+2]=a-o,t[n+3]=0}_singleRealTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+i],u=e[r+o],d=e[r+s],f=c+u,p=c-u,m=l+d,h=a*(l-d);t[n]=f+m,t[n+1]=0,t[n+2]=p,t[n+3]=-h,t[n+4]=f-m,t[n+5]=0,t[n+6]=p,t[n+7]=h}},np=class{constructor(e){let t=2*(e-1),n=2*(2*e-1),r=2**Math.ceil(Math.log2(n));this.bufferSize=r,this._a=t;let i=new Float64Array(n),a=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);let o=-2*Math.PI/e,s=Math.cos(o),c=Math.sin(o);for(let t=0;t<n>>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new tp(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e<c.length;e+=2){let n=e+1,i=t[e>>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e<c.length;e+=2){let n=e+1;r[e]=t[e]*c[e]-t[n]*c[n],r[n]=t[e]*c[n]+t[n]*c[e]}this._f.transform(a,r);for(let e=0;e<s.length;e+=2){let t=e+1;i[e]=a[e]*s[e]-a[t]*s[t],i[t]=a[e]*s[t]+a[t]*s[e]}this._f.inverseTransform(o,i);for(let t=0;t<o.length;t+=2){let n=o[t+l],r=o[t+l+1],i=c[t],a=c[t+1];e[t]=n*i-r*a,e[t+1]=n*a+r*i}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},rp=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=ep(e),this.isPowerOfTwo?(this.fft=new tp(e),this.outputBufferSize=2*e):(this.fft=new np(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function ip(e,t){if(t%2==0||t<=0)throw Error(`Window size must be a positive odd number`);let n=new e.constructor(e.length),r=new e.constructor(t),i=Math.floor(t/2);for(let t=0;t<e.length;++t){let a=0;for(let n=-i;n<=i;++n){let i=t+n;i<0?i=Math.abs(i):i>=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function ap(e,t){let n=10**t;return Math.round(e*n)/n}function op(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function sp(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t<r[1];++t)for(let n=1;n<r[0];++n){let r=i[n-1][t-1],o=i[n-1][t],s=i[n][t-1],c,l;r<o&&r<s?(c=r,l=0):o<r&&o<s?(c=o,l=1):(c=s,l=2),i[n][t]=e[n-1][t-1]+c,a[n][t]=l}for(let e=0;e<r[1];++e)a[0][e]=2;for(let e=0;e<r[0];++e)a[e][0]=1;let o=t,s=n,c=[],l=[];for(;o>0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var cp=/* @__PURE__ */ (function(){let e=null;return function(t){if(!e){e=/* @__PURE__ */ new Float32Array(65536);let t=/* @__PURE__ */ new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;++t){let i=0,a=(t&32768)<<16,o=(t&31744)>>10,s=t&1023;if(o===31)i=a|0x7f800000|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;e<n;++e)i[e]=r[t[e]];return i}})(),lp={};async function up(e){let t=e.split(`/`).pop(),n;try{if(n=await jf(),n){let t=await n.match(e);if(t)return t}}catch(e){N.warn(`Failed to load ${t} from cache:`,e)}let r=await M.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){N.warn(`Failed to cache ${t}:`,e)}return r}async function dp(e){let t=await up(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return N.warn(`Failed to read WASM binary:`,e),null}}async function fp(e){if(j.IS_SERVICE_WORKER_ENV||j.IS_CHROME_AVAILABLE)return e;let t=await up(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return N.warn(`Failed to read WASM factory:`,e),null}}var pp=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},\"webnn-npu\":{name:`webnn`,deviceType:`npu`},\"webnn-gpu\":{name:`webnn`,deviceType:`gpu`},\"webnn-cpu\":{name:`webnn`,deviceType:`cpu`}});function mp(e){return e<=Rs.DEBUG?0:e<=Rs.INFO?2:e<=Rs.WARNING||e<=Rs.ERROR?3:4}var hp={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},gp=[],_p,vp,yp=/* @__PURE__ */ Symbol.for(`onnxruntime`);if(yp in globalThis)vp=globalThis[yp];else if(j.IS_NODE_ENV){switch(vp=lp,process.platform){case`win32`:gp.push(`dml`);break;case`linux`:process.arch===`x64`&&gp.push(`cuda`);break;case`darwin`:gp.push(`coreml`)}gp.push(`webgpu`),gp.push(`cpu`),_p=[`cpu`]}else vp=yr,j.IS_WEBNN_AVAILABLE&&gp.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),j.IS_WEBGPU_AVAILABLE&&gp.push(`webgpu`),gp.push(`wasm`),_p=[`wasm`];function bp(){return[...gp]}var xp=vp.InferenceSession;function Sp(e=null){if(!e)return _p;switch(e){case`auto`:return gp;case`gpu`:return gp.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(gp.includes(e))return[pp[e]??e];throw Error(`Unsupported device: \"${e}\". Should be one of: ${gp.join(`, `)}.`)}var Cp=Promise.resolve(),wp=null;async function Tp(){if(wp)return wp;if(!(M.useWasmCache&&typeof Ap?.wasm?.wasmPaths==`object`&&Ap?.wasm?.wasmPaths?.wasm&&Ap?.wasm?.wasmPaths?.mjs)){if(j.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return wp=Promise.resolve(),wp}return wp=(async()=>{let e=Ap.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!Tf(e.wasm)?(async()=>{try{let n=await dp(Ef(e.wasm));n&&(Ap.wasm.wasmBinary=n,t=!0)}catch(e){N.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!Tf(e.mjs)?(async()=>{try{let t=await fp(Ef(e.mjs));t&&(Ap.wasm.wasmPaths.mjs=t)}catch(e){N.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Ap.wasm.wasmPaths.mjs=e.mjs)})(),wp}async function Ep(e,t,n){await Tp();let r=mp(M.logLevel??Rs.WARNING),i=()=>xp.create(e,{logSeverityLevel:r,...t}),a=await(j.IS_WEB_ENV?Cp=Cp.then(i):i());return a.config=n,a}var Dp=Promise.resolve();async function Op(e,t){let n=()=>e.run(t);return j.IS_WEB_ENV?Dp=Dp.then(n):n()}function kp(e){return e instanceof vp.Tensor}var Ap=vp?.env;function jp(){return Ap?.wasm?.proxy}if(Ap){let e=function(e){Ap.logLevel=hp[mp(e)]};if(Ap.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Ap.versions?.web&&!Ap.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ap.versions.web}/dist/`,t=`.asyncify`;j.IS_SAFARI_BELOW_26&&!j.IS_WEBGPU_AVAILABLE&&(t=``),Ap.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${t}.mjs`,wasm:`${e}ort-wasm-simd-threaded${t}.wasm`}}Ap.wasm.proxy=!1}Ap.webgpu&&(Ap.webgpu.powerPreference=`high-performance`),e(M.logLevel??Rs.WARNING),M.backends.onnx={...Ap,setLogLevel:e,getSupportedDevices:bp}}var Mp=async(e,t,n)=>{let r=await Ep(new Uint8Array(e),t);return(async e=>{let t=jp(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await Op(r,i);return Array.isArray(n)?n.map(e=>new H(a[e])):new H(a[n])})},Np=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=Mp([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||=Mp([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||=Mp([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||=Mp([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||=Mp([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||=Mp([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=Mp([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||=Mp([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}},Pp=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`}),Fp=j.IS_NODE_ENV?`cpu`:`wasm`;function Ip(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for \"${t}\". Using the default device (${Fp}).`),Fp):Fp}var Lp=/* @__PURE__ */ (function(){let e;return async function(){if(e===void 0){if(!j.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),Rp=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),zp=Rp.fp32,Bp=Object.freeze({[Pp.wasm]:Rp.q8}),Vp=Object.freeze({[Rp.fp32]:``,[Rp.fp16]:`_fp16`,[Rp.int8]:`_int8`,[Rp.uint8]:`_uint8`,[Rp.q8]:`_quantized`,[Rp.q4]:`_q4`,[Rp.q2]:`_q2`,[Rp.q1]:`_q1`,[Rp.q4f16]:`_q4f16`,[Rp.q2f16]:`_q2f16`,[Rp.q1f16]:`_q1f16`,[Rp.bnb4]:`_bnb4`});function Hp(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===Rp.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==Rp.auto&&Rp.hasOwnProperty(e))return e}s=Bp[n]??zp}else s=a&&Rp.hasOwnProperty(a)?a:Bp[n]??zp;return o&&i&&i(`dtype not specified for \"${t}\". Using the default dtype (${s}) for this device (${n}).`),s}var Up=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}),H=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=kp(e[0])?e[0]:new ss(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r<e;++r)yield this._subarray(r,n,t)}else yield*this.data}_getitem(t){let[n,...r]=this.dims;if(t=tm(t,n),r.length>0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}_subarray(t,n,r){let i=t*n,a=(t+1)*n,o=`subarray`in this.data?this.data.subarray(i,a):this.data.slice(i,a);return new e(this.type,o,r)}item(){let e=this.data;if(e.length!==1)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return Wp(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]=e(t[n],n,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]-=e;return this}remainder(e){return this.clone().remainder_(e)}remainder_(e){let t=this.data,n=t instanceof BigInt64Array||t instanceof BigUint64Array?BigInt(e):Number(e);if((n===0||n===0n)&&(this.type.includes(`int`)||this.type===`bool`))throw RangeError(`Division by zero`);if(n<0&&(this.type.startsWith(`uint`)||this.type===`bool`))throw RangeError(`Negative divisors are not supported for unsigned or boolean tensors`);for(let e=0;e<t.length;++e){let r=t[e]%n;t[e]=r<0&&n>0||r>0&&n<0?r+n:r}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let n=[],r=[];for(let e=0;e<this.dims.length;++e){let i=t[e];if(i==null)r.push([0,this.dims[e]]),n.push(this.dims[e]);else if(typeof i==`number`)i=tm(i,this.dims[e],e),r.push([i,i+1]);else if(Array.isArray(i)&&i.length===2){let[t,a]=i;if(t=t===null?0:tm(t,this.dims[e],e,!1),a=a===null?this.dims[e]:tm(a,this.dims[e],e,!1),t>a)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e<i.length;++e)if(r[e][0]!==0||r[e][1]!==this.dims[e]){l=!1;break}if(l){let e=r[0][0]*c[0],t=r[0][1]*c[0];if(ArrayBuffer.isView(o))s.set(o.subarray(e,t));else if(Array.isArray(o)){let n=o.slice(e,t);for(let e=0;e<n.length;++e)s[e]=n[e]}else throw Error(`Unsupported data type for slicing`)}else for(let e=0;e<a;++e){let t=0;for(let n=i.length-1,a=e;n>=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return Gp(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=rm(o,this,n,r);if(t!==1)for(let e=0;e<l.length;++e)l[e]=l[e]**(1/t);return new e(c,l,u)}normalize_(e=2,t=1){t=tm(t,this.dims.length);let n=this.norm(e,t,!0),r=this.data,i=n.data;for(let e=0;e<r.length;++e){let n=0;for(let r=this.dims.length-1,i=e,a=1;r>=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return om(this.dims)}squeeze(t=null){return new e(this.type,this.data,$p(this.dims,t))}squeeze_(e=null){return this.dims=$p(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,em(this.dims,t))}unsqueeze_(e){return this.dims=em(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;e<t.length;++e)if(t[e]===-1){if(n!==-1)throw Error(`Only one dimension can be inferred`);n=e}let r=this.data;if(n!==-1){let e=t.reduce((e,t,r)=>r===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]>t);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]<t);return new e(`bool`,n,this.dims)}clamp_(e,t){let n=this.data;for(let r=0;r<n.length;++r)n[r]=Math.min(Math.max(n[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return am(this,e,t)}min(t=null,n=!1){if(t===null){let t=Qf(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=rm((e,t)=>Math.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=$f(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=rm((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error(\"`dim !== null` not yet implemented.\");let r=Qf(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error(\"`dim !== null` not yet implemented.\");let r=$f(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(e=>e===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=om(r),l=om(i);for(let e=0;e<a;++e){let t=e,n=0;for(let e=0;e<i.length;++e){let i=Math.floor(t/l[e]);t%=l[e];let a=i%r[e];n+=a*c[e]}s[e]=o[n]}return new e(this.type,s,i)}tile(...e){if(e.length<this.dims.length){let t=this.dims.length-e.length;e=Array(t).fill(1).concat(e)}return this.repeat(...e)}to(t){if(this.type===t)return this;if(!Up.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let n,r=[`int64`,`uint64`].includes(this.type),i=[`int64`,`uint64`].includes(t);if(r&&!i)n=Number;else if(!r&&i)n=[`float16`,`float32`,`float64`].includes(this.type)?e=>BigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,cp(this.data),this.dims);return new e(t,Up[t].from(this.data,n),this.dims)}};function Wp(e,t){let n=e.length;if(n!==(t.length===0?1:t.reduce((e,t)=>e*t)))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.length<t[e]?i.push(r):n.push([r]),n},[[]]);return r[0]}function Gp(e,t){let[n,r]=Yf(e.data,e.dims,t);return new H(e.type,n,r)}function Kp(e,[t,n],r=`bilinear`,i=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),s=e.dims.at(-1),c=Jf(e.data,[a,o,s],[t,n],r,i);return new H(e.type,c,[a,t,n])}async function qp(e,{size:t=null,mode:n=`bilinear`}={}){if(e.dims.length!==4)throw Error(\"`interpolate_4d` currently only supports 4D input.\");if(!t)throw Error(\"`interpolate_4d` requires a `size` argument.\");let r;if(t.length===2)r=[...e.dims.slice(0,2),...t];else if(t.length===3)r=[e.dims[0],...t];else if(t.length===4)r=t;else throw Error(\"`size` must be of length 2, 3, or 4.\");let i;if(n===`nearest`)i=await Np.nearest_interpolate_4d;else if(n===`bilinear`)i=await Np.bilinear_interpolate_4d;else if(n===`bicubic`)i=await Np.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${n}`);let a=new H(`int64`,new BigInt64Array(r.map(BigInt)),[r.length]);return await i({x:e,s:a})}async function Jp(e,t){return await(await Np.matmul)({a:e,b:t})}async function Yp(e,t){let n=await Np.top_k;return t=t==null?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await n({x:e,k:new H(`int64`,[BigInt(t)],[1])})}var Xp=e=>new H(`int64`,e,[e.length]);async function Zp(e,t,n,r,i){return await(await Np.slice)({x:e,s:Xp(t),e:Xp(n),a:Xp(r),t:Xp(i??Array(r.length).fill(1))})}function Qp(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;e<o;++e){let t=e*c*s;for(let i=0;i<c;++i){let o=0,u=0,d=e*s,f=t+i;for(let e=0;e<s;++e){let t=Number(r[d+e]);u+=t,o+=n[f+e*c]*t}let p=o/u;a[l++]=p}}return new H(e.type,a,i)}function $p(e,t){return e=e.slice(),t===null?e=e.filter(e=>e!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function em(e,t){return t=tm(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function tm(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function U(e,t=0){t=tm(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a<e.length;++a){let{data:o,dims:s}=e[a];for(let e=0;e<o.length;++e){let a=0;for(let i=s.length-1,o=e,c=1;i>=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new H(a,i,n)}function nm(e,t=0){return U(e.map(e=>e.unsqueeze(t)),t)}function rm(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=tm(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t<a.length;++t){let r=0;for(let e=o.length-1,i=t,a=1;e>=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function im(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new H(e.type,[t],[]);return[new H(e.type,[r],[]),a]}t=tm(t,a.length);let o=am(e,t,r),s=o.data,[c,l,u]=rm((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;e<l.length;++e)l[e]=Math.sqrt(l[e]/(a[t]-n));return[new H(c,l,u),o]}function am(e,t=null,n=!1){let r=e.dims,i=e.data;if(t===null){let t=i.reduce((e,t)=>e+t,0);return new H(e.type,[t/i.length],[])}t=tm(t,r.length);let[a,o,s]=rm((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e<o.length;++e)o[e]/=r[t];return new H(a,o,s)}function om(e){let t=Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}function sm(e,t,n,r){return new H(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function cm(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return sm(e,t,n,r)}function lm(e,t){return cm(e.dims,t)}function um(e){return sm(e,1n,`int64`,BigInt64Array)}function dm(e){return um(e.dims)}function fm(e){return sm(e,0n,`int64`,BigInt64Array)}function pm(e){return fm(e.dims)}function mm(e){let t=e.reduce((e,t)=>e*t,1);return new H(`float32`,Float32Array.from({length:t},()=>uf.gauss()),e)}function hm(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e<a.length;++e){let t=+(a[e]>0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new H(r,o,[e.dims[0],e.dims[1]/8])}async function gm(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await If(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function _m(e,t){let n=await gm(e);return await Promise.all(n.map(n=>qf(e,n,!0,t)))}function vm(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error(\"Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.\");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var ym=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function bm(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?qs(e[i],s):qs(s,e[i])}}function xm(e,t){for(let n of Object.keys(e))e[n].length=t}function Sm(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Cm(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var W=class extends Vs{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new mu(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Sm(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Sm(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Sm(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Sm(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Sm(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Sm(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=/* @__PURE__ */ Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with \"name\" and \"template\" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=/* @__PURE__ */ new Map;let n=Cm(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await _m(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))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(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(N.warn(\"`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`.\"),s=this.model_max_length):i===!1&&(N.warn(\"Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length.\"),o=!0)),i===!0&&(s=Math.min($f(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;e<u.length;++e)if(u[e].input_ids.length===s)continue;else u[e].input_ids.length>s?o&&xm(u[e],s):i&&bm(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.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 e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new H(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof H&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof H&&(e=vm(e)),!Array.isArray(e)||e.length===0||!Ws(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=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(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new rf(i),this._compiled_template_cache.set(i,m));let h=/* @__PURE__ */ Object.create(null);for(let e of ym){let t=Sm(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function wm(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error(\"Tokenizer must have `language_codes` attribute set and it should be an array of language ids.\");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error(\"Tokenizer must have `languageRegex` attribute set and it should be a regular expression.\");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error(\"Tokenizer must have `lang_to_token` attribute set and it should be a function.\");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code \"${a}\" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code \"${i}\" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);let t=e._tokenizer.post_processor?.config;if(t&&`single`in t){for(let n of t.single)if(`SpecialToken`in n&&e.languageRegex.test(n.SpecialToken.id)){n.SpecialToken.id=e.lang_to_token(i);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Tm={};us(Tm,{AlbertTokenizer:()=>Em,AutoTokenizer:()=>G,BartTokenizer:()=>Dm,BertTokenizer:()=>Om,BlenderbotSmallTokenizer:()=>km,BlenderbotTokenizer:()=>Am,BloomTokenizer:()=>jm,CLIPTokenizer:()=>Nm,CamembertTokenizer:()=>Mm,CodeGenTokenizer:()=>Fm,CodeLlamaTokenizer:()=>Pm,CohereAsrTokenizer:()=>Lm,CohereTokenizer:()=>Im,ConvBertTokenizer:()=>Rm,DebertaTokenizer:()=>Bm,DebertaV2Tokenizer:()=>zm,DistilBertTokenizer:()=>Vm,ElectraTokenizer:()=>Hm,EsmTokenizer:()=>Um,FalconTokenizer:()=>Wm,GPT2Tokenizer:()=>qm,GPTNeoXTokenizer:()=>Km,GemmaTokenizer:()=>Gm,HerbertTokenizer:()=>Jm,LlamaTokenizer:()=>Ym,M2M100Tokenizer:()=>Xm,MBart50Tokenizer:()=>$m,MBartTokenizer:()=>Qm,MPNetTokenizer:()=>nh,MarianTokenizer:()=>Zm,MgpstrTokenizer:()=>eh,MobileBertTokenizer:()=>th,NllbTokenizer:()=>rh,NougatTokenizer:()=>ih,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>ah,RoFormerTokenizer:()=>sh,RobertaTokenizer:()=>oh,SiglipTokenizer:()=>ch,SpeechT5Tokenizer:()=>lh,SqueezeBertTokenizer:()=>uh,T5Tokenizer:()=>dh,TokenizersBackend:()=>W,VitsTokenizer:()=>ph,Wav2Vec2CTCTokenizer:()=>mh,WhisperTokenizer:()=>xh,XLMRobertaTokenizer:()=>Sh,XLMTokenizer:()=>Ch});var Em=class extends W{return_token_type_ids=!0},Dm=class extends W{},Om=class extends W{return_token_type_ids=!0},km=class extends W{},Am=class extends W{},jm=class extends W{},Mm=class extends W{},Nm=class extends W{},Pm=class extends W{},Fm=class extends W{},Im=class extends W{},Lm=class extends W{},Rm=class extends W{return_token_type_ids=!0},zm=class extends W{return_token_type_ids=!0},Bm=class extends W{return_token_type_ids=!0},Vm=class extends W{},Hm=class extends W{return_token_type_ids=!0},Um=class extends W{},Wm=class extends W{},Gm=class extends W{},Km=class extends W{},qm=class extends W{},Jm=class extends W{return_token_type_ids=!0},Ym=class extends W{padding_side=`left`},Xm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},Zm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^(>>\\w+<<)\\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),N.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,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||N.warn(`Unsupported language code \"${e}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),qs([e],super._encode_text(t))}}},Qm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},$m=class extends Qm{},eh=class extends W{},th=class extends W{return_token_type_ids=!0},nh=class extends W{},rh=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},ih=class extends W{},ah=class extends W{},oh=class extends W{},sh=class extends W{return_token_type_ids=!0},ch=class extends W{},lh=class extends W{},uh=class extends W{return_token_type_ids=!0},dh=class extends W{},fh=class extends tu{decode_chain(e){let t=``;for(let n=1;n<e.length;n+=2)t+=e[n];return[t]}},ph=class extends W{constructor(e,t){super(e,t),this._tokenizer.decoder=new fh({type:`VitsDecoder`})}},mh=class extends W{},hh=[[`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`]],gh=new Map(hh),_h=new Map([...hh.map(([e,t])=>[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function vh(e){e=e.toLowerCase();let t=_h.get(e);if(t===void 0){let n=e.match(/^<\\|([a-z]{2})\\|>$/);if(n&&(e=n[1]),gh.has(e))t=e;else{let t=e.length===2?gh.keys():gh.values();throw Error(`Language \"${e}\" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var yh=/* @__PURE__ */ RegExp(`^[\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E]+$`,`gu`),bh=.1,xh=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r<g)break;v=n}}}let b=[],x=[];for(let n=0;n<e.length;++n){let g=Number(e[n]);if(_.has(g)){let e=this.decode([g]),n=gh.get(e.slice(2,-2));if(n!==void 0){if(a!==null&&n!==a&&!t){p.push(b);let e=this.findLongestCommonSequence(p)[0],t=this.decode(e);l.text=t,c.push(l),p=[],b=[],l=s()}a=l.language=n}}else if(g>=d&&g<=f){let e=ap((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g<y)h=!1;else if(l.timestamp[0]===null)l.timestamp[0]=e;else if(e!==l.timestamp[0]){l.timestamp[1]=e,p.push(b),o&&m.push(x);let[t,n]=this.findLongestCommonSequence(p,m),r=this.decode(t);if(l.text=r,o&&(l.words=this.collateWordTimestamps(t,n,a),l.words.length>0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=ap(i[n]+u,2),t;if(n+1<i.length){t=ap(i[n+1]+u,2);let a=this.decode([g]);yh.test(a)&&(t=ap(Math.min(e+r,t),2))}else t=null;x.push([e,t])}}if(`stride`in n){let[e,t,r]=n.stride;u+=e-r}b.length>0?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=/* @__PURE__ */ Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e<c.length;++e){let r=c[e];t||delete r.timestamp,n||delete r.language}if(o){let e=[];for(let t of c)for(let n of t.words)e.push(n);v={chunks:e}}else v={chunks:c}}return[y,v]}findLongestCommonSequence(e,t=null){let n=e[0],r=n.length,i=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,s=a?t[0]:null;for(let c=1;c<e.length;++c){let l=e[c],u=0,d=[r,r,0,0],f=l.length;for(let e=1;e<r+f;++e){let i=Math.max(0,r-e),o=Math.min(r,r+f-e),p=n.slice(i,o),m=Math.max(0,e-r),h=Math.min(f,e),g=l.slice(m,h);if(p.length!==g.length)throw Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");let _;_=a?p.filter((e,n)=>e===g[n]&&s[i+n][0]-bh<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e<r.length;++e){let n=a[e];o.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,n=`\"'“¡¿([{-`,r=`\"'.。,,!!??::”)]}、`){t??=`english`;let i,a,o;return[`chinese`,`japanese`,`thai`,`lao`,`myanmar`].includes(t)?[i,a,o]=this.splitTokensOnUnicode(e):[i,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(i,a,o,n,r)}decode(e,t){let n;return t?.decode_with_timestamps?(e instanceof H&&(e=vm(e)),n=this.decodeWithTimestamps(e,t)):n=super.decode(e,t),n}decodeWithTimestamps(e,t){let n=t?.time_precision??.02,r=this.all_special_ids.at(-1)+1,i=[[]];for(let t of e)if(t=Number(t),t>=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c<e.length;++c){let l=e[c];a.push(l),o.push(c);let u=this.decode(a,{decode_with_timestamps:!0});u.includes(`�`)&&t[s+u.indexOf(`�`)]!==`�`||(n.push(u),r.push(a),i.push(o),a=[],o=[],s+=u.length)}return[n,r,i]}splitTokensOnSpaces(e){let[t,n,r]=this.splitTokensOnUnicode(e),i=[],a=[],o=[];for(let e=0;e<t.length;++e){let s=t[e],c=n[e],l=r[e],u=c[0]>=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=yh.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=qs(o[c],o[l]),s[l]=qs(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;l<a.length;)!a[c].endsWith(` `)&&i.includes(a[l])?(a[c]+=a[l],o[c]=qs(o[c],o[l]),s[c]=qs(s[c],s[l]),a[l]=``,o[l]=[],s[l]=[]):c=l,++l;return[a.filter(e=>e),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Sh=class extends W{},Ch=class extends W{return_token_type_ids=!0;constructor(e,t){super(e,t),N.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},G=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await _m(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Tm[c];return l||=(N.warn(`Unknown tokenizer class \"${c}\", attempting to construct from base class.`),W),new l(o,s)}},wh=`https://github.com/huggingface/transformers.js/issues/new/choose`,Th=`preprocessor_config.json`,Eh=`preprocessor_config.json`,Dh=`processor_config.json`,Oh=`chat_template.jinja`,K=class extends Vs{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?qf(e,Dh,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?Kf(e,Oh,!0,t):null]);return new this(n,r,i)}},kh={};us(kh,{ChatterboxProcessor:()=>Cg,CohereAsrProcessor:()=>Tg,EmbeddingGemma2Processor:()=>Bg,EmbeddingGemma2VideoProcessor:()=>Lg,Florence2Processor:()=>y1,Gemma3Processor:()=>b1,Gemma3nProcessor:()=>x1,Gemma4Processor:()=>Ig,Glm46VProcessor:()=>C1,GraniteSpeechProcessor:()=>w1,GroundingDinoProcessor:()=>E1,Idefics3Processor:()=>A1,JinaCLIPProcessor:()=>M1,Lfm2VlProcessor:()=>N1,Lfm3VlProcessor:()=>P1,LlavaProcessor:()=>F1,MgpstrProcessor:()=>L1,MoonshineProcessor:()=>R1,OwlViTProcessor:()=>z1,PaliGemmaProcessor:()=>H1,Phi3VProcessor:()=>G1,PixtralProcessor:()=>K1,Processor:()=>K,PyAnnoteProcessor:()=>q1,Qwen2VLProcessor:()=>S1,Qwen2_5_VLProcessor:()=>J1,Qwen3VLProcessor:()=>Y1,Sam2Processor:()=>Z1,Sam2VideoProcessor:()=>Q1,SamProcessor:()=>X1,SmolVLMProcessor:()=>A1,SpeechT5Processor:()=>$1,UltravoxProcessor:()=>e0,VLChatProcessor:()=>j1,VoxtralProcessor:()=>a0,VoxtralRealtimeProcessor:()=>d0,Wav2Vec2Processor:()=>f0,Wav2Vec2ProcessorWithLM:()=>p0,WhisperProcessor:()=>m0});var Ah=class extends Vs{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await qf(e,Th,!0,t);return new this(n)}};function jh(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \\`load_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`)}var Mh={};us(Mh,{ASTFeatureExtractor:()=>ng,ChatterboxFeatureExtractor:()=>ig,ClapFeatureExtractor:()=>ag,CohereAsrFeatureExtractor:()=>cg,DacFeatureExtractor:()=>lg,EncodecFeatureExtractor:()=>rg,FeatureExtractor:()=>Ah,Gemma3nAudioFeatureExtractor:()=>ug,Gemma4AudioFeatureExtractor:()=>dg,GraniteSpeechFeatureExtractor:()=>fg,MoonshineFeatureExtractor:()=>pg,ParakeetFeatureExtractor:()=>sg,PyAnnoteFeatureExtractor:()=>mg,SeamlessM4TFeatureExtractor:()=>hg,SnacFeatureExtractor:()=>gg,SpeechT5FeatureExtractor:()=>_g,VoxtralRealtimeFeatureExtractor:()=>bg,Wav2Vec2FeatureExtractor:()=>vg,WeSpeakerFeatureExtractor:()=>yg,WhisperFeatureExtractor:()=>xg});var Nh={fromWeb:()=>{}};async function Ph(e,t){if(j.IS_BROWSER_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(j.IS_FS_AVAILABLE){let n=t.stream();Nh.fromWeb(n),ds.createWriteStream(e),await void 0}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function Fh(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 n=await(await Rf(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&N.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r<i.length;++r)a[r]=e*(t[r]+n[r])/2}else a=i.getChannelData(0);return a}async function Ih(e,t){return await Fh(e,t)}function Lh(e,t){if(e<1)return/* @__PURE__ */ new Float64Array;if(e===1)return new Float64Array([1]);let n=1-t,r=2*Math.PI/(e-1),i=new Float64Array(e);for(let a=0;a<e;++a)i[a]=t-n*Math.cos(a*r);return i}function Rh(e){return Lh(e,.5)}function zh(e){return Lh(e,.54)}var Bh={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function Vh(e,t=`htk`){let n=Bh[t];if(!n)throw Error(`mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var Hh={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function Uh(e,t=`htk`){let n=Hh[t];if(!n)throw Error(`mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function Wh(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;n<e.length;++n){let i=r[n];for(let r=0;r<t.length;++r)i[r]=t[r]-e[n]}let i=t.length-2,a=Array.from({length:i},()=>Array(e.length));for(let t=0;t<e.length;++t){let e=r[t];for(let r=0;r<i;++r){let i=-e[r]/n[r],o=e[r+2]/n[r+1];a[r][t]=Math.max(0,Math.min(i,o))}}return a}function Gh(e,t,n){let r=(t-e)/(n-1);return Float64Array.from({length:n},(t,n)=>e+r*n)}function Kh(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or \"slaney\"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=Gh(Vh(n,o),Vh(r,o),t+2),l=Uh(c,o),u;if(s){let t=i/((e-1)*2);u=Vh(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=Gh(0,Math.floor(i/2),e);let d=Wh(u,l);if(a!==null&&a===`slaney`)for(let n=0;n<t;++n){let t=d[n],r=2/(l[n+2]-l[n]);for(let n=0;n<e;++n)t[n]*=r}return d}function qh(e,t,n){let r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n<e.length;++n)r[t+n]=e[n];for(let n=1;n<=t;++n)r[t-n]=e[Ys(n,i)];for(let a=1;a<=n;++a)r[i+t+a]=e[Ys(i-a,i)];return r}function Jh(e,t,n,r,i){if(n<=0)throw Error(`reference must be greater than zero`);if(r<=0)throw Error(`min_value must be greater than zero`);n=Math.max(r,n);let a=Math.log10(n);for(let n=0;n<e.length;++n)e[n]=t*Math.log10(Math.max(r,e[n])-a);if(i!==null){if(i<=0)throw Error(`db_range must be greater than zero`);let t=$f(e)[0]-i;for(let n=0;n<e.length;++n)e[n]=Math.max(e[n],t)}return e}function Yh(e,t=1,n=1e-5,r=null){return Jh(e,20,t,n,r)}function Xh(e,t=1,n=1e-10,r=null){return Jh(e,10,t,n,r)}async function Zh(e,t,n,r,{fft_length:i=null,power:a=1,center:o=!0,pad_mode:s=`reflect`,onesided:c=!0,preemphasis:l=null,preemphasis_htk_flavor:u=!0,mel_filters:d=null,mel_floor:f=1e-10,log_mel:p=null,max_log_mel:m=null,reference:h=1,min_value:g=1e-10,db_range:_=null,remove_dc_offset:v=null,min_num_frames:y=null,max_num_frames:b=null,do_pad:x=!0,transpose:S=!1,mel_offset:C=0,mel_floor_mode:ee=`clamp`}={}){let w=t.length;if(i===null&&(i=n),n>i)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(w!==n)throw Error(`Length of the window (${w}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error(\"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.\");if(!u)throw Error(\"`preemphasis_htk_flavor=false` is not currently supported.\");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=qh(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode=\"${s}\" not implemented yet.`)}}let te=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&te<y&&(te=y);let ne=c?Math.floor(i/2)+1:i,re=te,ie=te;b!==null&&(b>te?x&&(ie=b):ie=re=b);let ae=new rp(i),oe=new Float64Array(i),se=new Float64Array(ae.outputBufferSize),ce=new Float32Array(ne*ie);for(let i=0;i<re;++i){let a=i*r,o=Math.min(e.length-a,n);o!==n&&oe.fill(0,0,n);for(let t=0;t<o;++t)oe[t]=e[a+t];if(v){let e=0;for(let t=0;t<o;++t)e+=oe[t];let t=e/o;for(let e=0;e<o;++e)oe[e]-=t}if(l!==null){for(let e=o-1;e>=1;--e)oe[e]-=l*oe[e-1];oe[0]*=1-l}for(let e=0;e<t.length;++e)oe[e]*=t[e];ae.realTransform(se,oe);for(let e=0;e<ne;++e){let t=e<<1;ce[e*ie+i]=se[t]**2+se[t+1]**2}}if(a!==null&&a!==2){let e=a/2;for(let t=0;t<ce.length;++t)ce[t]**=e}let le=d.length,ue=await Jp(new H(`float32`,d.flat(),[le,ne]),new H(`float32`,ce,[ne,ie]));S&&(ue=ue.transpose(1,0));let T=ue.data;if(ee===`add`)for(let e=0;e<T.length;++e)T[e]=C+T[e]+f;else for(let e=0;e<T.length;++e)T[e]=C+Math.max(f,T[e]);if(a!==null&&p!==null){let e=Math.min(T.length,re*le);switch(p){case`log`:for(let t=0;t<e;++t)T[t]=Math.log(T[t]);break;case`log10`:for(let t=0;t<e;++t)T[t]=Math.log10(T[t]);break;case`log10_max_norm`:{for(let t=0;t<e;++t)T[t]=Math.log10(T[t]);let t=(m??$f(T)[0])-8;for(let n=0;n<e;++n)T[n]=(Math.max(T[n],t)+4)/4;break}case`dB`:if(a===1)Yh(T,h,g,_);else if(a===2)Xh(T,h,g,_);else throw Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return ue}function Qh(e,t,{periodic:n=!0,frame_length:r=null,center:i=!0}={}){let a=n?e+1:e,o;switch(t){case`boxcar`:o=new Float64Array(a).fill(1);break;case`hann`:case`hann_window`:o=Rh(a);break;case`hamming`:o=zh(a);break;case`povey`:o=Rh(a).map(e=>e**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function $h(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=/* @__PURE__ */ new ArrayBuffer(44),i=new DataView(r);return eg(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),eg(i,8,`WAVE`),eg(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),eg(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice())],{type:`audio/wav`})}function eg(e,t,n){for(let r=0;r<n.length;++r)e.setUint8(t+r,n.charCodeAt(r))}var tg=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return/* @__PURE__ */ new Float32Array;if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((e,t)=>e+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),$h(e,this.sampling_rate)}async save(e){return Ph(e,this.toBlob())}},ng=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){jh(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t<n.length;++t)n[t]=(n[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}},rg=class extends Ah{async _call(e){jh(e,`EncodecFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let n=[1,t,e.length/t];return{input_values:new H(`float32`,e,n)}}},ig=class extends Ah{async _call(e){jh(e,`ChatterboxFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new H(`float32`,e,t)}}},ag=class extends Ah{constructor(e){super(e),this.mel_filters=Kh(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=Kh(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=Qh(this.config.fft_window_size,`hann`)}async _get_input_mel(e,t,n,r){let i,a=e.length-t;if(a>0){if(n===`rand_trunc`){let n=Math.floor(uf.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy \"${n}\" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r<t;r+=e.length)n.set(e.subarray(0,Math.min(e.length,t-r)),r);else if(r===`repeatpad`)for(let t=e.length;t<-a;t+=e.length)n.set(e,t);e=n}if(n===`fusion`)throw Error(`Truncation strategy \"${n}\" not implemented`);i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return i.unsqueeze_(0)}async _extract_fbank_features(e,t,n=null){return Zh(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:`dB`,max_num_frames:n,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return jh(e,`ClapFeatureExtractor`),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},og=1e-5,sg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(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=Qh(this.config.win_length,`hann`,{periodic:!1});this.window=new Float64Array(this.config.n_fft);let n=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,n)}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 Zh(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){jh(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<n;++e){let t=e*a;for(let e=0;e<a;++e){let n=r[t+e];o[e]+=n,s[e]+=n*n}}let c=n>1?n-1:1;for(let e=0;e<a;++e){let t=o[e]/n,i=(s[e]-n*t*t)/c,l=1/(Math.sqrt(i)+og);for(let i=0;i<n;++i){let n=i*a+e;r[n]=(r[n]-t)*l}}let l=new BigInt64Array(i);return l.fill(1n,0,n),{input_features:t.unsqueeze_(0),attention_mask:new H(`int64`,l,[1,i])}}},cg=class extends sg{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let n=new sf(e.length);for(let r=0;r<e.length;++r)e[r]+=t*n.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,n=this.config.overlap_chunk_second??5,r=this.config.min_energy_window_samples??1600,i=this.config.sampling_rate,a=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(n*i));if(e.length<=a)return[e];let s=[],c=0,l=e.length;for(;c<l;){if(c+a>=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;a<r;++a){let r=e[t+n+a];i+=r*r}i=Math.sqrt(i/r),i<a&&(a=i,o=t+n)}return o}async _call(e){jh(e,`CohereAsrFeatureExtractor`);let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},lg=class extends rg{},ug=class extends Ah{constructor(e){super(e);let{fft_length:t,feature_size:n,min_frequency:r,max_frequency:i,sampling_rate:a,frame_length:o}=this.config,s=Kh(Math.floor(1+t/2),n,r,i,a,null,`htk`,!1);this.mel_filters=s,this.window=Qh(o,`hann`)}async _extract_fbank_features(e,t){return Zh(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:n=!0,padding:r=!0,pad_to_multiple_of:i=128}={}){if(jh(e,`Gemma3nAudioFeatureExtractor`),n&&e.length>t&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=cm([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},dg=class extends ug{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return Zh(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){jh(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e<a;++e)f[e]=+!!d[e*c+u-1];let p=i.data;for(let e=0;e<a;++e)f[e]||p.fill(0,e*o,(e+1)*o);return r.input_features_mask=new H(`bool`,f,[1,a]),r}},fg=class extends Ah{constructor(e){super(e);let{n_fft:t,win_length:n,n_mels:r,sample_rate:i}=e.melspec_kwargs;this.mel_filters=Kh(Math.floor(1+t/2),r,0,i/2,i,null,`htk`);let a=Qh(n,`hann`);this.window=new Float64Array(t);let o=Math.floor((t-n)/2);this.window.set(a,o)}async _call(e){jh(e,`GraniteSpeechFeatureExtractor`);let{n_fft:t,hop_length:n,n_mels:r}=this.config.melspec_kwargs,i=Math.floor(e.length/n)+1,a=i-i%2;return{input_features:(await Zh(e,this.window,t,n,{power:2,mel_filters:this.mel_filters,log_mel:`log10_max_norm`,transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},pg=class extends Ah{async _call(e){jh(e,`MoonshineFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new H(`float32`,e,t)}}},mg=class extends Ah{async _call(e){jh(e,`PyAnnoteFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new H(`float32`,e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let n=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(let t of e.tolist()){let e=[],i=-1;for(let n=0;n<t.length;++n){let[r,a]=$f(Xf(t[n])),[o,s]=[n,n+1];a===i?(e.at(-1).end=s,e.at(-1).score+=r):(i=a,e.push({id:a,start:o,end:s,score:r}))}r.push(e.map(({id:e,start:t,end:r,score:i})=>({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},hg=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){jh(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r<t;++r){let i=0;for(let a=0;a<e;++a)i+=n[a*t+r];let a=i/e,o=0;for(let i=0;i<e;++i)o+=(n[i*t+r]-a)**2;o/=e-1;let s=Math.sqrt(o+1e-7);for(let i=0;i<e;++i){let e=i*t+r;n[e]=(n[e]-a)/s}}}let o;if(t){let[e,t]=a.dims,r=a.data,s=e%n;if(s>0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new H(a.type,n,[c,t]),i&&(o=new H(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;n<s;n+=l,++r)t[r]=e[n]}else t.fill(1n);d.attention_mask=new H(`int64`,t,[1,e])}return d}},gg=class extends lg{},_g=class extends Ah{},vg=class extends Ah{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){jh(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 n=[1,t.length];return{input_values:new H(`float32`,t,n),attention_mask:new H(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},yg=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){jh(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t<r;++t){let r=t*i*a,o=t*a;for(let t=0;t<i;++t){let i=r+t*a;for(let t=0;t<a;++t)n[i+t]-=e[o+t]}}}return{input_features:t}}},bg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Qh(this.config.n_fft,`hann`)}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:n,hop_length:r,mel_filters:i,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/r:(e.length-n)/r);return await Zh(e,this.window,n,r,{power:2,mel_filters:i,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 jh(e,`VoxtralRealtimeFeatureExtractor`),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},xg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Qh(this.config.n_fft,`hann`)}async _extract_fbank_features(e){return await Zh(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}={}){jh(e,`WhisperFeatureExtractor`);let n,r=t??this.config.n_samples;return e.length>r?(e.length>this.config.n_samples&&N.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`.\"),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},Sg=class{static async from_pretrained(e,t={}){let n=await qf(e,Th,!0,t),r=n.feature_extractor_type,i=Mh[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${wh}.`);return new i(n)}},Cg=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},wg=/* @__PURE__ */ new Set([`ja`,`zh`]),Tg=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=wg.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},Eg={},Dg,Og,kg;if(j.IS_WEB_ENV)Dg=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},kg=self.createImageBitmap,Og=self.ImageData;else if(Eg)kg=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new Mg(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var Ag={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},jg=/* @__PURE__ */ new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),Mg=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)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 Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!j.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await Rf(e);if(t.status!==200)throw Error(`Unable to read image from \"${e}\" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(j.IS_WEB_ENV){let t=await kg(e),n=Dg(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=Eg(await e.arrayBuffer());return await kg(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.permute(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){let r=this.data[t],i=this.data[t+1],a=this.data[t+2];e[n++]=Math.round(.2989*r+.587*i+.114*a)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t];break;case 4:for(let t=0,n=0;t<this.data.length;t+=4)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=255;break;case 3:for(let t=0,n=0;t<this.data.length;t+=3)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2],e[n++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${e.channels}`);let t=this.data,n=e.data,r=this.width*this.height;if(this.channels===3){let e=new Uint8ClampedArray(r*4);for(let i=0,a=0,o=0;i<r;++i)e[o++]=t[a++],e[o++]=t[a++],e[o++]=t[a++],e[o++]=n[i];return this._update(e,this.width,this.height,4)}if(this.channels===4){for(let e=0;e<r;++e)t[4*e+3]=n[e];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,n,{resample:r=2}={}){if(this.width===t&&this.height===n)return this;let i=Ag[r]??r,a=Gs(t),o=Gs(n);if(a&&o)return this;if(a?t=n/this.height*this.width:o&&(n=t/this.width*this.height),j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),a=Dg(t,n).getContext(`2d`);return a.drawImage(i,0,0,t,n),new e(a.getImageData(0,0,t,n).data,t,n,4).convert(r)}{let e=this.toSharp();switch(i){case`box`:case`hamming`:(i===`box`||i===`hamming`)&&(N.warn(`Resampling method ${i} is not yet supported. Using bilinear instead.`),i=`bilinear`);case`nearest`:case`bilinear`:case`bicubic`:e=e.affine([t/this.width,0,0,n/this.height],{interpolator:i});break;case`lanczos`:e=e.resize({width:t,height:n,fit:`fill`,kernel:`lanczos3`});break;default:throw Error(`Resampling method ${i} is not supported.`)}return await kg(e)}}async pad([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.max(r,0),i=Math.max(i,0),t===0&&n===0&&r===0&&i===0)return this;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=this.width+t+n,c=this.height+r+i,l=Dg(s,c).getContext(`2d`);return l.drawImage(o,0,0,this.width,this.height,t,r,this.width,this.height),new e(l.getImageData(0,0,s,c).data,s,c,4).convert(a)}{let e=this.toSharp().extend({left:t,right:n,top:r,bottom:i});return await kg(e)}}async crop([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.min(r,this.width-1),i=Math.min(i,this.height-1),t===0&&n===0&&r===this.width-1&&i===this.height-1)return this;let a=r-t+1,o=i-n+1;if(j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),s=Dg(a,o).getContext(`2d`);return s.drawImage(i,t,n,a,o,0,0,a,o),new e(s.getImageData(0,0,a,o).data,a,o,4).convert(r)}{let e=this.toSharp().extract({left:t,top:n,width:a,height:o});return await kg(e)}}async center_crop(t,n){if(this.width===t&&this.height===n)return this;let r=(this.width-t)/2,i=(this.height-n)/2;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=Dg(t,n).getContext(`2d`),c=0,l=0,u=0,d=0;return r>=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await kg(e)}}async toBlob(e=`image/png`,t=1){if(!j.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new H(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!j.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=Dg(e.width,e.height),n=new Og(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;e<o;++e){let n=i*e;for(let r=0;r<i;++r)s[r][e]=t[n+r]}return s.map(t=>new e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(j.IS_WEB_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=jg.get(t)??`image/png`;return Ph(e,await this.toBlob(n))}if(j.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(j.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return Eg(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Mg.read.bind(Mg);function Ng(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \\`pooling_kernel_size * patch_size\\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function Pg(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;t<s;++t)for(let a=0;a<c;++a)for(let o=0;o<i;++o){let s=(t*i+o)*n*r+a*i*r;for(let t=0;t<i;++t){let n=s+t*r;for(let t=0;t<r;++t)d[f++]=e[n+t]}}let p=new BigInt64Array(a*2).fill(-1n),m=0;for(let e=0;e<s;++e)for(let t=0;t<c;++t)p[m++]=BigInt(t),p[m++]=BigInt(e);return{patches:new H(`float32`,d,[a,u]),positions:new H(`int64`,p,[a,2]),num_soft_tokens:Math.floor(l/o**2)}}var Fg=class extends Vs{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:n}=this,r=this.max_soft_tokens*n**2,i=[],a=[],o=[];for(let s of e){if(this.do_convert_rgb&&(s=s.rgb()),this.do_resize){let[e,i]=Ng(s.height,s.width,t,r,n);(e!==s.height||i!==s.width)&&(s=await s.resize(i,e,{resample:this.resample}))}let e=Float32Array.from(s.data);if(this.do_rescale)for(let t=0;t<e.length;++t)e[t]*=this.rescale_factor;let{patches:c,positions:l,num_soft_tokens:u}=Pg(e,s.height,s.width,s.channels,t,r,n);i.push(c),a.push(l),o.push(u)}return{pixel_values:nm(i,0),image_position_ids:nm(a,0),num_soft_tokens_per_image:o}}},Ig=class extends K{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([qf(e,Dh,!0,t),G.from_pretrained(e,t),Kf(e,Oh,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new Fg(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new dg(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>`\n\n${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token}\n\n`))}let a;if(n){let t=Array.isArray(n)?n:[n];a=await this.feature_extractor(t[0],r);let i=this.feature_extractor.config.sampling_rate??16e3,o=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>`\n\n${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token}\n\n`))}return{...this.tokenizer(e,r),...i,...a}}},Lg=class extends Vs{constructor(e){super(),this.config=e,this.frame_processor=new Fg(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??`uniform`}sample_frames(e){let t=e.length,{max_frames:n}=this;if(t<=n)return e;if(this.overflow_strategy===`truncate`)return e.slice(0,n);let r=n>1?(t-1)/(n-1):0;return Array.from({length:n},(i,a)=>e[a>0&&a===n-1?t-1:Math.floor(a*r)])}async _call(e){Array.isArray(e)||(e=[e]);let t=e.map(e=>this.sample_frames(e.frames.map(e=>e.image))),{pixel_values:n,image_position_ids:r,num_soft_tokens_per_image:i}=await this.frame_processor(t.flat()),a=0;return{pixel_values_videos:n,video_position_ids:r,num_frames_per_video:t.map(e=>e.length),num_soft_tokens_per_video:t.map(e=>i[(a+=e.length)-1])}}};function Rg(e,t){return Array.isArray(e)?e.every(e=>Array.isArray(e))?e:t?[e]:e.map(e=>[e]):[[e]]}function zg(e,t,n){let r=0;if(e=e.map(e=>e.replaceAll(t,()=>n[r++]??``)),r!==n.length)throw Error(`Found ${r} ${t} tokens in the text, but ${n.length} inputs were passed.`);return e}var Bg=class extends Ig{constructor(e,t,n){super(e,t,n),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new Lg(e.video_processor)}async _call(e,t=null,n=null,r=null,i={}){let a=[[this.image_token,t&&Rg(t,!0)],[this.video_token,r&&Rg(r,!1)],[this.audio_token,n&&Rg(n,!1)]];if(e==null){let t=a.filter(([,e])=>e),n=t[0]?.[1].length;if(t.some(([,e])=>e.length!==n))throw Error(`Received a different number of samples per modality.`);e=Array.from({length:n},(e,n)=>t.flatMap(([e,t])=>Array(t[n].length).fill(e)).join(` `))}else typeof e==`string`&&(e=[e]);let[o,s,c]=a.map(([,e])=>e?.flat()),l=o&&await this.image_processor(o),u=s&&await this.video_processor(s),d=c&&await this._process_audio(c),{image_token:f,video_token:p,audio_token:m,boi_token:h,eoi_token:g,boa_token:_,eoa_token:v}=this,y={[f]:l?.num_soft_tokens_per_image.map(e=>h+f.repeat(e)+g),[p]:u?.num_soft_tokens_per_video.map((e,t)=>(h+p.repeat(e)+g).repeat(u.num_frames_per_video[t])),[m]:d?.num_soft_tokens_per_audio.map(e=>_+m.repeat(e)+v)};for(let[t,n]of Object.entries(y))e=zg(e,t,n??[]);return{...this.tokenizer(e,{padding:!0,...i}),...l,...u,...d}}async _process_audio(e){let t=[];for(let n of e)t.push(await this.feature_extractor(n));let n=Math.max(...t.map(e=>e.input_features.dims[1])),r=t[0].input_features.dims[2],i=new Float32Array(e.length*n*r),a=new Uint8Array(e.length*n);return t.forEach((e,t)=>{i.set(e.input_features.data,t*n*r),a.set(e.input_features_mask.data,t*n)}),{input_features:new H(`float32`,i,[e.length,n,r]),input_features_mask:new H(`bool`,a,[e.length,n]),num_soft_tokens_per_audio:t.map(({input_features_mask:{data:e}})=>{let t=0;for(let n=0;n<e.length;n+=4)t+=Number(e[n]);return t})}}};function Vg(e,t,n=0,r=null){let i=e/t,a=op(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),a<n&&(a=Math.ceil(i)*t),a}function Hg([e,t],n){return[Math.max(Math.floor(e/n),1)*n,Math.max(Math.floor(t/n),1)*n]}function Ug([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function Wg(e,t=.5,n=null,r=!1){let i=e.logits,a=e.pred_boxes,[o,s,c]=i.dims;if(n!==null&&n.length!==o)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let l=[];for(let e=0;e<o;++e){let o=n===null?null:n[e],u={boxes:[],classes:[],scores:[]},d=i[e],f=a[e];for(let e=0;e<s;++e){let n=d[e],i=[],a;if(r){a=n.sigmoid().data;for(let e=0;e<a.length;++e)a[e]>t&&i.push(e)}else{let e=$f(n.data)[1];if(e===c-1||(a=Xf(n.data),a[e]<t))continue;i.push(e)}for(let t of i){let n=f[e].data;n=Ug(n),o!==null&&(n=n.map((e,t)=>e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function Gg(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;e<r;++e){let r=t===null?null:t[e],a=n[e];r!==null&&(a=Kp(a,r,`bilinear`,!1));let[o,s]=r??a.dims.slice(-2),c=new H(`int32`,new Int32Array(o*s),[o,s]),l=a[0].data,u=c.data;for(let e=1;e<a.dims[0];++e){let t=a[e].data;for(let n=0;n<t.length;++n)t[n]>l[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;e<u.length;++e){let t=u[e];d[t]=t}let f=d.filter(e=>e!==void 0);i.push({segmentation:c,labels:f})}return i}function Kg(e,t,n,r){let i=[],a=[],o=[];for(let s=0;s<e.dims[0];++s){let c=e[s],l=t[s],u=$f(c.data)[1];if(u===r)continue;let d=Xf(c.data)[u];d>n&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function qg(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t<e.length;++t)e[t]===n&&(a.push(t),++o),c[t]>=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function Jg(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new H(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;t<e.length;++t)e[t]=Kp(e[t],o,`bilinear`,!1);let d=new Int32Array(e[0].data.length),f=new Float32Array(e[0].data.length);for(let n=0;n<e.length;++n){let r=t[n],i=e[n].data;for(let e=0;e<i.length;++e)i[e]*=r,i[e]>f[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a<n.length;++a){let o=n[a],[s,c]=qg(d,e,a,r,i);if(s){++p;for(let e of c)m[e]=p;u.push({id:p,label_id:o,score:t[a]})}}return[l,u]}function Yg(e,t,n=28,r=3136,i=0xf5000,a=1){if(e<n||t<n){let r=Math.max(n/e,n/t);e=Math.round(e*r),t=Math.round(t*r)}if(Math.max(e,t)/Math.min(e,t)>200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/n)*n,s=Math.round(t/n)*n;if(a*o*s>i){let r=Math.sqrt(a*e*t/i);o=Math.max(n,Math.floor(e/r/n)*n),s=Math.max(n,Math.floor(t/r/n)*n)}else if(a*o*s<r){let i=Math.sqrt(r/(a*e*t));o=Math.ceil(e*i/n)*n,s=Math.ceil(t*i/n)*n}return[s,o]}function Xg(e,t=.5,n=.5,r=.8,i=null,a=null){i===null&&(N.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\"),i=/* @__PURE__ */ new Set);let o=e.class_queries_logits??e.logits,s=(e.masks_queries_logits??e.pred_masks).sigmoid(),[c,l,u]=o.dims;if(--u,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 d=[];for(let e=0;e<c;++e){let c=a===null?null:a[e],l=o[e],f=s[e],[p,m,h]=Kg(l,f,t,u);if(h.length===0){let[e,t]=c??f.dims.slice(-2),n=new H(`int32`,new Int32Array(e*t).fill(-1),[e,t]);d.push({segmentation:n,segments_info:[]});continue}let[g,_]=Jg(p,m,h,n,r,i,c);d.push({segmentation:g,segments_info:_})}return d}function Zg(e,t=.5,n=null){throw Error(\"`post_process_instance_segmentation` is not yet implemented.\")}var q=class extends Vs{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,n=2){let r=e.height,i=e.width,a=t.height,o=t.width,s=Math.min(r,a),c=Math.min(i,o);return s===r&&c===i?e:(r>i?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=Qf(n.data)[0],i=$f(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;e<n.height;++e){let t=e*n.width;for(let d=0;d<n.width;++d)(u[t+d]-r)/i<a&&(o=Math.min(o,d),s=Math.min(s,e),c=Math.max(c,d),l=Math.max(l,e))}return e=await e.crop([o,s,c,l]),e}pad_image(e,t,n,{mode:r=`constant`,center:i=!1,constant_values:a=0}={}){let[o,s,c]=t,l,u;if(typeof n==`number`?(l=n,u=n):n===`square`?l=u=Math.max(o,s):(l=n.width,u=n.height),l!==s||u!==o){let n=new Float32Array(l*u*c);if(Array.isArray(a))for(let e=0;e<n.length;++e)n[e]=a[e%c];else a!==0&&n.fill(a);let[d,f]=i?[Math.floor((l-s)/2),Math.floor((u-o)/2)]:[0,0];for(let t=0;t<o;++t){let r=(t+f)*l,i=t*s;for(let t=0;t<s;++t){let a=(r+t+d)*c,o=(i+t)*c;for(let t=0;t<c;++t)n[a+t]=e[o+t]}}if(r===`symmetric`){if(i)throw Error(\"`center` padding is not supported when `mode` is set to `symmetric`.\");let t=o-1,r=s-1;for(let i=0;i<u;++i){let a=i*l,u=Ys(i,t)*s;for(let t=0;t<l;++t){if(i<o&&t<s)continue;let l=(a+t)*c,d=(u+Ys(t,r))*c;for(let t=0;t<c;++t)n[l+t]=e[d+t]}}}e=n,t=[u,l,c]}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[n,r]=e.size,i,a;if(this.do_thumbnail){let{height:e,width:n}=t;i=Math.min(e,n)}else Number.isInteger(t)?(i=t,a=this.config.max_size??i):t!==void 0&&(i=t.shortest_edge,a=t.longest_edge);if(i!==void 0||a!==void 0){let e=i===void 0?1:Math.max(i/n,i/r),t=n*e,o=r*e,s=a===void 0?1:Math.min(a/t,a/o),c=Math.floor(Number((t*s).toFixed(2))),l=Math.floor(Number((o*s).toFixed(2)));return this.size_divisibility!==void 0&&([c,l]=Hg([c,l],this.size_divisibility)),[c,l]}if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let e=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=i/r,a=e/n;Math.abs(1-a)<Math.abs(1-t)?t=a:a=t,i=Vg(t*r,this.config.ensure_multiple_of),e=Vg(a*n,this.config.ensure_multiple_of)}return[e,i]}if(this.size_divisibility!==void 0)return Hg([n,r],this.size_divisibility);throw Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(t)}`)}async resize(e){let[t,n]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,n,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:n=null,do_convert_rgb:r=null,do_convert_grayscale:i=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[o,s]=e.size;if(r??this.do_convert_rgb?e=e.rgb():i&&(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 t,n;Number.isInteger(this.crop_size)?(t=this.crop_size,n=this.crop_size):(t=this.crop_size.width,n=this.crop_size.height),e=await e.center_crop(t,n)}let c=[e.height,e.width],l=Float32Array.from(e.data),u=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(l),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=Array(e.channels).fill(t));let n=this.image_std;if(Array.isArray(this.image_std)||(n=Array(e.channels).fill(n)),t.length!==e.channels||n.length!==e.channels)throw Error(`When set to arrays, the length of \\`image_mean\\` (${t.length}) and \\`image_std\\` (${n.length}) must match the number of channels in the image (${e.channels}).`);for(let r=0;r<l.length;r+=e.channels)for(let i=0;i<e.channels;++i)l[r+i]=(l[r+i]-t[i])/n[i]}if(n??this.do_pad){if(this.pad_size){let t=this.pad_image(l,[e.height,e.width,e.channels],this.pad_size);[l,u]=t}else if(this.size_divisibility){let e=Math.ceil(u[1]/this.size_divisibility)*this.size_divisibility,t=Math.ceil(u[0]/this.size_divisibility)*this.size_divisibility;[l,u]=this.pad_image(l,u,{width:e,height:t})}}if(a??this.do_flip_channel_order){if(u[2]!==3)throw Error(`Flipping channel order is only supported for RGB images.`);for(let e=0;e<l.length;e+=3){let t=l[e];l[e]=l[e+2],l[e+2]=t}}let d=new H(`float32`,l,u).permute(2,0,1);return{original_size:[s,o],reshaped_input_size:c,pixel_values:d}}async _call(e,...t){Array.isArray(e)||(e=[e]);let n=await Promise.all(e.map(e=>this.preprocess(e)));return{pixel_values:nm(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t);return new this(n)}},Qg={};us(Qg,{BeitFeatureExtractor:()=>$g,BitImageProcessor:()=>e_,CHMv2ImageProcessor:()=>n_,CLIPFeatureExtractor:()=>i_,CLIPImageProcessor:()=>r_,ChineseCLIPFeatureExtractor:()=>t_,ConvNextFeatureExtractor:()=>o_,ConvNextImageProcessor:()=>a_,DINOv3ViTImageProcessor:()=>d_,DPTFeatureExtractor:()=>h_,DPTImageProcessor:()=>m_,DeiTFeatureExtractor:()=>c_,DeiTImageProcessor:()=>s_,DetrFeatureExtractor:()=>u_,DetrImageProcessor:()=>l_,DonutFeatureExtractor:()=>p_,DonutImageProcessor:()=>f_,EfficientNetImageProcessor:()=>g_,GLPNFeatureExtractor:()=>b_,Gemma3ImageProcessor:()=>__,Gemma4ImageProcessor:()=>Fg,Glm46VImageProcessor:()=>y_,GroundingDinoImageProcessor:()=>x_,Idefics3ImageProcessor:()=>S_,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>w_,Lfm2VlImageProcessor:()=>A_,Lfm3VlImageProcessor:()=>j_,LlavaOnevisionImageProcessor:()=>M_,Mask2FormerImageProcessor:()=>F_,MaskFormerFeatureExtractor:()=>P_,MaskFormerImageProcessor:()=>N_,MobileNetV1FeatureExtractor:()=>L_,MobileNetV1ImageProcessor:()=>I_,MobileNetV2FeatureExtractor:()=>z_,MobileNetV2ImageProcessor:()=>R_,MobileNetV3FeatureExtractor:()=>V_,MobileNetV3ImageProcessor:()=>B_,MobileNetV4FeatureExtractor:()=>U_,MobileNetV4ImageProcessor:()=>H_,MobileViTFeatureExtractor:()=>G_,MobileViTImageProcessor:()=>W_,NougatImageProcessor:()=>K_,OwlViTFeatureExtractor:()=>J_,OwlViTImageProcessor:()=>q_,Owlv2ImageProcessor:()=>Y_,Phi3VImageProcessor:()=>t1,PixtralImageProcessor:()=>n1,PvtImageProcessor:()=>r1,Qwen2VLImageProcessor:()=>v_,RTDetrImageProcessor:()=>i1,Sam2ImageProcessor:()=>a1,Sam3ImageProcessor:()=>a1,SamImageProcessor:()=>a1,SapiensFeatureExtractor:()=>s1,SapiensImageProcessor:()=>o1,SegformerFeatureExtractor:()=>l1,SegformerImageProcessor:()=>c1,SiglipImageProcessor:()=>u1,SmolVLMImageProcessor:()=>S_,Swin2SRImageProcessor:()=>d1,VLMImageProcessor:()=>C_,ViTFeatureExtractor:()=>p1,ViTImageProcessor:()=>f1,VitMatteImageProcessor:()=>m1,VitPoseImageProcessor:()=>h1,YolosFeatureExtractor:()=>_1,YolosImageProcessor:()=>g1});var $g=class extends q{},e_=class extends q{},t_=class extends q{},n_=class extends q{},r_=class extends q{},i_=class extends r_{},a_=class extends q{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},o_=class extends a_{},s_=class extends q{},c_=class extends s_{},l_=class extends q{async _call(e){let t=await super._call(e),n=cm([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Wg(...e)}post_process_panoptic_segmentation(...e){return Xg(...e)}post_process_instance_segmentation(...e){return Zg(...e)}},u_=class extends l_{},d_=class extends q{},f_=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},p_=class extends f_{},m_=class extends q{},h_=class extends m_{},g_=class extends q{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},__=class extends q{},v_=class extends q{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 n=this.patch_size*this.merge_size;return Yg(e.height,e.width,n,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:n,original_sizes:r,reshaped_input_sizes:i}=await super._call(e,...t),a=n,{temporal_patch_size:o,merge_size:s,patch_size:c}=this.config;a.dims[0]===1&&(a=U(Array.from({length:o},()=>a),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new H(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},y_=class extends v_{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return Yg(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},b_=class extends q{},x_=class extends q{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=um([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},S_=class extends q{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[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await qp(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,U(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>qp(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(U(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=cm([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=cm([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;r<l;++r){let a=i[r].dims[0];if(a<e){i[r]=U([i[r],cm([e-a,d,f,p],0)],0);let o=r*n+a*f*p,s=(r+1)*n;t.fill(!1,o,s)}}m=nm(i,0)}return{pixel_values:m,pixel_attention_mask:h,original_sizes:s,reshaped_input_sizes:c,...n?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){let n=t,r=t,i=[],[a,o]=e.dims.slice(-2),s=0,c=0;if(a>n||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;n<s;++n)for(let r=0;r<c;++r){let u,d,f,p;n===s-1?(d=a-t,p=a):(d=n*t,p=(n+1)*t),r===c-1?(u=o-l,f=o):(u=r*l,f=(r+1)*l);let m=await Zp(e,[d,u],[p,f],[2,3]);i.push(m)}let u=n,d=r;(a!==u||o!==d)&&(e=await qp(e,{size:[u,d]}))}return i.push(e),{frames:i,num_splits_h:s,num_splits_w:c}}},C_=class extends q{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(e=>e*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},w_=class extends q{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function T_(e,t){return Math.round(e/t)*t}function E_(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t<a?(a=t,o=n):t===a&&s>.5*i*i*n[0]*n[1]&&(o=n)}return o}function D_(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function O_(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;e<n;++e){let n=e*r*d,i=e*o*s*c;for(let e=0;e<o;++e)for(let o=0;o<s;++o){let f=i+(e*s+o)*c;for(let i=0;i<t;++i){let s=(e*t+i)*a+o*t;for(let e=0;e<t;++e){let t=s+e;for(let e=0;e<r;++e)u[f++]=l[n+e*d+t]}}}}return new H(`float32`,u,[n,o*s,c])}function k_(e,t){let[,n,r]=e.dims,i=new BigInt64Array(t);i.fill(1n,0,n);let a=e;if(n<t){let n=new Float32Array(t*r);n.set(e.data),a=new H(`float32`,n,[1,t,r])}return{padded:a,mask:new H(`int64`,i,[t])}}var A_=class extends q{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,n=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,n)}_is_image_too_large(e,t){let n=this.encoder_patch_size*this.downsample_factor;return Math.max(this.encoder_patch_size,T_(e,n))*Math.max(this.encoder_patch_size,T_(t,n))>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=D_(this.min_tiles,this.max_tiles),[r,i]=E_(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=Yg(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&(this.min_tiles!==1||this.max_tiles!==1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await qp(l,{size:[a,i]});m=[];for(let t=0;t<r;++t)for(let n=0;n<e;++n){let e=t*this.tile_size,r=n*this.tile_size;m.push(o.slice(null,null,[e,e+this.tile_size],[r,r+this.tile_size]))}this.use_thumbnail&&e*r!==1&&m.push(await qp(l,{size:[p,f]}))}else m=[await qp(l,{size:[p,f]})];for(let e of m){let[,,t,n]=e.dims,{padded:o,mask:s}=k_(O_(e,this.encoder_patch_size),this.max_num_patches);r.push(o),i.push(s),a.push([Math.floor(t/this.encoder_patch_size),Math.floor(n/this.encoder_patch_size)])}o.push(h),s.push(g),c.push([p,f])}}let l={pixel_values:U(r,0),pixel_attention_mask:nm(i,0),spatial_shapes:new H(`int64`,BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(l.image_rows=o,l.image_cols=s,l.image_sizes=c),l}},j_=class extends v_{async _call(e,...t){Array.isArray(e)||(e=[e]);let n=await Promise.all(e.map(e=>super._call(e,...t)));return{pixel_values:U(n.map(e=>e.pixel_values),0),image_grid_thw:U(n.map(e=>e.image_grid_thw),0),original_sizes:n.flatMap(e=>e.original_sizes),reshaped_input_sizes:n.flatMap(e=>e.reshaped_input_sizes)}}},M_=class extends q{},N_=class extends q{post_process_panoptic_segmentation(...e){return Xg(...e)}post_process_instance_segmentation(...e){return Zg(...e)}},P_=class extends N_{},F_=class extends N_{},I_=class extends q{},L_=class extends I_{},R_=class extends q{},z_=class extends R_{},B_=class extends q{},V_=class extends B_{},H_=class extends q{},U_=class extends H_{},W_=class extends q{},G_=class extends W_{},K_=class extends f_{},q_=class extends q{post_process_object_detection(...e){return Wg(...e)}},J_=class extends q_{},Y_=class extends q_{},X_=336,Z_=[2,3],{ceil:Q_,floor:$_,sqrt:e1}=Math,t1=class extends q{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:n}=this.config;return $_(($_(t/X_)*$_(e/X_)+1)*n+1+($_(t/X_)+1)*e1(n))}get_resize_output_image_size(e,t){let n=this._num_crops,[r,i]=e.size,a=r/i,o=1;for(;o*Math.ceil(o/a)<=n;)o+=1;--o;let s=Math.floor(o*336);return[s,Math.floor(s/a)]}pad_image(e,t,n,r={}){let[i,a]=t,o=X_*Q_(i/X_),s=X_*Q_(a/X_),c=[1,1,1].map((e,t)=>(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||e1(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await qp(e,{size:[X_,X_],mode:`bicubic`});if(t>0){let a=[],s=e1(t),c=$_(r/s),l=$_(n/s);for(let t=0;t<s;++t)for(let i=0;i<s;++i){let o,u,d,f;t===s-1?(u=n-l,f=n):(u=t*l,f=(t+1)*l),i===s-1?(o=r-c,d=r):(o=i*c,d=(i+1)*c);let p=await Zp(e,[u,o],[f,d],Z_);a.push(p)}let u=await qp(U(a,0),{size:[X_,X_],mode:`bicubic`});o.push(U([i,u],0))}else o.push(i)}let s=nm(o,0),c=a.map(e=>e.map(e=>X_*Q_(e/X_)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new H(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},n1=class extends q{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},r1=class extends q{},i1=class extends q{post_process_object_detection(...e){return Wg(...e)}},a1=class extends q{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=Ks(e);if(i.length===3)r||(i=[1,...i]),e=[e];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 r=0;r<e.length;++r){let[i,a]=t[r],[o,s]=n[r],c=[s/a,o/i];for(let t=0;t<e[r].length;++t)for(let n=0;n<e[r][t].length;++n)for(let i=0;i<e[r][t][n].length;++i)e[r][t][n][i]*=c[i%2]}return new H(`float32`,Float32Array.from(e.flat(1/0)),i)}add_input_labels(e,t){let n=Ks(e);if(n.length===2)n=[1,...n],e=[e];else if(n.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(n.some((e,n)=>e!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new H(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error(\"`input_points` must be provided if `input_labels` are provided.\");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;a<t.length;++a){let c=t[a],l=n[a],u=await qp(e[a],{mode:`bilinear`,size:s});if(u=u.slice(null,null,[0,l[0]],[0,l[1]]),u=await qp(u,{mode:`bilinear`,size:c}),i){let e=u.data,t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)e[n]>r&&(t[n]=1);u=new H(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},o1=class extends q{post_process_semantic_segmentation(...e){return Gg(...e)}},s1=class extends o1{},c1=class extends q{post_process_semantic_segmentation(...e){return Gg(...e)}},l1=class extends c1{},u1=class extends q{},d1=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},f1=class extends q{},p1=class extends f1{},m1=class extends q{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:nm(n.map((e,t)=>U([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},h1=class extends q{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e<i;++e){let i=r[e],a=t[e],l=[];for(let e=0;e<a.length;++e){let t=a[e],r=[],c=[],u=[],d=t.at(-2)/s,f=t.at(-1)/o;for(let e=0;e<i.length;++e){let[t,a]=[0,0],o=0,s=-1/0,l=i[e];for(let e=0;e<l.length;++e){let n=l[e];for(let r=0;r<n.length;++r){let i=n[r];o+=i,s=Math.max(s,i),t+=(r+.5)*i,a+=e*i}}if(n!=null&&s<n)continue;let p=[d*t/o,f*a/o];r.push(p),u.push(e),c.push(s)}l.push({bbox:t,scores:c,labels:u,keypoints:r})}c.push(l)}return c}},g1=class extends q{post_process_object_detection(...e){return Wg(...e)}},_1=class extends g1{},v1=class{static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t),r=n.image_processor_type??n.feature_extractor_type,i=Qg[r?.replace(/Fast$/,``)];return i||=(r!==void 0&&N.warn(`Image processor type '${r}' not found, assuming base ImageProcessor. Please report this at ${wh}.`),q),new i(n)}},y1=class extends K{static tokenizer_class=G;static image_processor_class=v1;constructor(e,t,n){super(e,t,n);let{tasks_answer_post_processing_type:r,task_prompts_without_inputs:i,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(r??{})),this.task_prompts_without_inputs=new Map(Object.entries(i??{})),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 n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(`<s>`,``).replaceAll(`</s>`,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task \"${t}\" (of type \"${r}\") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},b1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.image_seq_length=this.config.image_seq_length;let{boi_token:r,image_token:i,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=i,this.eoi_token=a;let o=i.repeat(this.image_seq_length);this.full_image_sequence=`\n\n${r}${o}${a}\n\n`}async _call(e,t=null,n={}){typeof e==`string`&&(e=[e]);let r;return t&&(r=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,n),...r}}},x1=class extends K{static image_processor_class=v1;static feature_extractor_class=Sg;static tokenizer_class=G;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a;let d=a.repeat(this.audio_seq_length);this.full_audio_sequence=`\n\n${i}${d}${o}\n\n`,this.image_token_id=s,this.boi_token=c,this.image_token=l;let f=l.repeat(this.image_seq_length);this.full_image_sequence=`\n\n${c}${f}${u}\n\n`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},S1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static image_token=`<|image_pad|>`;async _call(e,t=null,...n){Array.isArray(e)||(e=[e]);let r,i;if(t&&(r=await this.image_processor(t),i=r.image_grid_thw),i){let t=this.image_processor.config.merge_size**2,n=0,r=this.constructor.image_token,a=i.tolist();e=e.map(e=>{for(;e.includes(r);){let i=Number(a[n++].reduce((e,t)=>e*t,1n));e=e.replace(r,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,r)})}return{...this.tokenizer(e),...r}}},C1=class extends S1{static image_token=`<|image|>`},w1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new H(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function T1(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var E1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>Ug(e))),f=[];for(let e=0;e<s;++e){let a=i===null?null:i[e];a!==null&&(d[e]=d[e].map(e=>e.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i<c;++i){let a=o[i];if(a<=n)continue;let c=d[e][i],u=l[e][i];s.push(a),m.push(c);let f=T1(u.gt(r),t[e]);p.push(f)}f.push({scores:s,boxes:m,labels:this.batch_decode(p)})}return f}};function D1(e,t,n,r,i,a){let o=``;for(let a=0;a<t;++a){for(let t=0;t<n;++t)o+=r+`<row_${a+1}_col_${t+1}>`+i.repeat(e);o+=`\n`}return o+=`\n${r}${a}`+i.repeat(e)+`${r}`,o}function O1(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function k1(e,t,n,r,i,a){return e===0&&t===0?O1(n,r,i,a):D1(n,e,t,r,i,a)}var A1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static uses_processor_config=!0;fake_image_token=`<fake_token_around_image>`;image_token=`<image>`;global_img_token=`<global-img>`;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;t<e.length;++t){let n=e[t],r=i[t],l=a[t];s.push(Zs(n,this.image_token));let u=r.map((e,t)=>k1(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;e<u.length;++e)f+=u[e]+d[e+1];c.push(f)}return{...this.tokenizer(c),...r}}},j1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static uses_processor_config=!0;constructor(e,t,n){super(e,t,n),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:n=`default`}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(e=>e.images).flatMap(e=>e.images).map(e=>Mg.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of \"${this.image_tag}\" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e<o.length;++e){let t=Array(this.num_image_tokens).fill(c),n=a(o[e]);d=qs(d,[l],t,[u],n);let r=Array(this.num_image_tokens).fill(!0);f=qs(f,[!1],r,[!1],Array(n.length).fill(!1))}let p=[1,d.length],m={input_ids:new H(`int64`,d,p),attention_mask:new H(`int64`,Array(d.length).fill(1),p),images_seq_mask:new H(`bool`,f,p),images_emb_mask:new H(`bool`,Array(s*this.num_image_tokens).fill(!0),[1,s,this.num_image_tokens])};if(t&&t.length>0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},M1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},N1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??`<image>`,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e<h;++e)for(let n=0;n<g;++n)v+=`<|img_row_${e+1}_col_${n+1}|>`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},P1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t=null,n={}){let r=e?await this.image_processor(e,n):{};if(t!==null){Array.isArray(t)||(t=[t]);let e=this.tokenizer.config.image_token??`<|image|>`,n=r.image_grid_thw?.tolist()??[],i=t.reduce((t,n)=>t+n.split(e).length-1,0);if(i!==n.length)throw Error(`Found ${i} ${e} tokens in the text but received ${n.length} images.`);let a=this.image_processor.config.merge_size,o=0;t=t.map(t=>t.replaceAll(e,()=>{let t=Number(n[o++].reduce((e,t)=>e*t,1n));return e.repeat(t/a**2)}))}return{...r,...t===null?{}:this.tokenizer(t,n)}}},F1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e<t.length;++e)t[e]=t[e].replace(i,i.repeat(s))}let i=t?this.tokenizer(t,n):{};return{...r,...i}}},I1={char:[`char_decode`,1],bpe:[`bpe_decode`,2],wp:[`wp_decode`,102]},L1=class extends K{static tokenizer_class=G;static image_processor_class=v1;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(!I1.hasOwnProperty(t))throw Error(`Format ${t} is not supported.`);let[n,r]=I1[t],i=this[n].bind(this),[a,o]=e.dims,s=[],c=[],l=e.tolist();for(let e=0;e<a;++e){let t=l[e],n=[],i=[];for(let e=1;e<o;++e){let[a,o]=$f(Xf(t[e]));if(i.push(a),o==r)break;n.push(o)}let a=i.length>0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e<r.length;++e){let[t,n]=$f([i[e],o[e],c[e]]);l.push([r[e],a[e],s[e]][n]),u.push(t)}return{generated_text:l,scores:u,char_preds:r,bpe_preds:a,wp_preds:s}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),n=await G.from_pretrained(`Xenova/gpt2`),r=await G.from_pretrained(`Xenova/bert-base-uncased`);return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:n,wp_tokenizer:r},t}async _call(e,t=null){let n=await this.image_processor(e);return t&&(n.labels=this.tokenizer(t).input_ids),n}},R1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},z1=class extends K{static tokenizer_class=G;static image_processor_class=v1},B1=`<image>`;function V1(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e}\n`}var H1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(N.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(B1))?a=t.map(e=>{let t=e.replaceAll(B1,B1.repeat(i)),n=t.lastIndexOf(B1),a=n===-1?0:n+B1.length;return t.slice(0,a)+r+t.slice(a)+`\n`}):(N.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(t=>V1(t,r,i,B1,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},U1=`<|image|>`,W1=/<\\|image_\\d+\\|>/g,G1=class extends K{static image_processor_class=v1;static tokenizer_class=G;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(W1).join(U1.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(U1);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},K1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e<t.length;++e){let n=i.repeat(d),r=n+a,s=n+o,c=r.repeat(u-1)+s;t[e]=t[e].replace(i,c)}}let i=t?this.tokenizer(t,n):{};return{...r,...i}}},q1=class extends K{static feature_extractor_class=mg;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}},J1=class extends S1{},Y1=class extends J1{},X1=class extends K{static image_processor_class=v1;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)}},Z1=class extends X1{},Q1=class extends Z1{},$1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},e0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let i=t.length,{input_features:a}=await this.feature_extractor(t,{...n,max_length:i}),o=Math.round(i/this.config.encoder_ds_factor+1e-4),s=1+Math.ceil(o/this.config.stack_factor);r.audio_token_len=[s],r.audio_values=a;let c=this.config.audio_placeholder;if(!e.includes(c))throw Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(s))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},t0=`[AUDIO]`,n0=`[BEGIN_AUDIO]`,r0=375;function i0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.subarray(r,Math.min(r+t,e.length)));return n}var a0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!1;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){if(!e.includes(t0))throw Error(`The input text does not contain the audio token ${t0}.`);Array.isArray(t)||(t=[t]);let i=e.split(t0),a=i.length-1;if(a!==t.length)throw Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${a}).`);let o=this.feature_extractor.config.n_samples,s=t.map(e=>i0(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?U(u,0):u[0];let d=i[0];for(let e=0;e<c.length;++e){d+=n0;for(let t=0;t<c[e];++t)d+=t0.repeat(r0);d+=i[e+1]}e=d}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},o0=32,s0=6,c0=8,l0=10,u0=32,d0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(s0+1)*c0}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 c0*e+t}get num_right_pad_tokens(){return s0+1+l0}get audio_length_per_tok(){return c0}get raw_audio_length_per_tok(){return c0*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:n=!0}={}){if(jh(e,`VoxtralRealtimeProcessor`),!t&&!n)throw Error(\"In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.\");if(n){if(t){let t=o0*this.raw_audio_length_per_tok,n=new Float32Array(t+e.length);n.set(e,t);let r=await this.feature_extractor(n,{center:!0}),i=1+(o0+s0),a=new BigInt64Array(i).fill(BigInt(u0));return a[0]=1n,{input_ids:new H(`int64`,a,[1,i]),...r}}{let t=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+t);return n.set(e),await this.feature_extractor(n,{center:!0})}}return await this.feature_extractor(e,{center:!1})}},f0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},p0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},m0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},h0=class{static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t),{image_processor_type:r,feature_extractor_type:i,processor_class:a}=n;if(a&&kh[a])return kh[a].from_pretrained(e,t);if(!r&&!i)throw Error(\"No `image_processor_type` or `feature_extractor_type` found in the config.\");let o={};if(r){let e=Qg[r.replace(/Fast$/,``)];if(!e)throw Error(`Unknown image_processor_type: '${r}'.`);o.image_processor=new e(n)}if(i){let e=Qg[i];if(e)o.image_processor=new e(n);else{let e=Mh[i];if(!e)throw Error(`Unknown feature_extractor_type: '${i}'.`);o.feature_extractor=new e(n)}}return new K({},o,null)}};async function g0(e,t){return await qf(e,`config.json`,!0,t)}function _0(e){let t={},n={};switch(e.model_type){case`llava`:case`paligemma`:case`gemma3`:case`florence2`:case`llava_onevision`:case`idefics3`:case`granite_speech`:case`ultravox`:case`voxtral`:case`voxtral_realtime`:case`smolvlm`:case`gemma3n`:case`gemma4`:case`lfm2_vl`:case`lfm3_vl`:case`chatterbox`:case`lighton_ocr`:case`glm_ocr`:case`mistral3`:case`qwen2_5_vl`:case`qwen3_vl`:case`qwen3_vl_moe`:n=_0(e.text_config);break;case`moondream1`:n=_0(e.phi_config);break;case`musicgen`:n=_0(e.decoder);break;case`multi_modality`:n=_0(e.language_config);break;case`gpt2`:case`gptj`:case`jais`:case`codegen`:case`gpt_bigcode`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`n_embd`;break;case`gpt_neox`:case`stablelm`:case`opt`:case`falcon`:case`modernbert-decoder`:t.num_heads=`num_attention_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`;break;case`gpt_oss`:case`llama`:case`llama4_text`:case`nanochat`:case`apertus`:case`arcee`:case`afmoe`:case`lfm2`:case`lfm2_moe`:case`lfm3`:case`smollm3`:case`olmo`:case`olmo2`:case`olmo3`:case`mobilellm`:case`granite`:case`granitemoehybrid`:case`cohere`:case`cohere2`:case`mistral`:case`voxtral_realtime_text`:case`voxtral_realtime_encoder`:case`starcoder2`:case`qwen2`:case`qwen2_moe`:case`qwen2_vl`:case`qwen2_vl_text`:case`qwen2_5_vl_text`:case`qwen3_moe`:case`qwen3_vl_text`:case`qwen3_vl_moe_text`:case`phi`:case`phi3`:case`phi3_v`:case`llava_qwen2`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`,t.num_attention_heads=`num_attention_heads`,t.dim_kv=`head_dim`;break;case`qwen3`:case`solar_open`:case`glm_ocr_text`:case`gemma`:case`gemma2`:case`vaultgemma`:case`gemma3_text`:case`gemma3n_text`:case`gemma4_text`:case`glm`:case`helium`:case`ernie4_5`:case`hunyuan_v1_dense`:case`falcon_h1`:case`nemotron_h`:case`ministral`:case`ministral3`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=`head_dim`;break;case`openelm`:t.num_heads=`num_kv_heads`,t.num_layers=`num_transformer_layers`,t.dim_kv=`head_dim`;break;case`gpt_neo`:case`donut-swin`:t.num_heads=`num_heads`,t.num_layers=`num_layers`,t.hidden_size=`hidden_size`;break;case`bloom`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`hidden_size`;break;case`mpt`:t.num_heads=`n_heads`,t.num_layers=`n_layers`,t.hidden_size=`d_model`;break;case`exaone`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_layers`,t.dim_kv=`head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`youtu`:case`deepseek_v3`:case`deepseek_v4`:case`glm_moe_dsa`:case`mistral4`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=e.model_type===`deepseek_v4`?`head_dim`:`qk_head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`zaya`:case`hrm_text`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`,t.dim_kv=`head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`t5`:case`mt5`:case`longt5`:t.num_decoder_layers=`num_decoder_layers`,t.num_decoder_heads=`num_heads`,t.decoder_dim_kv=`d_kv`,t.num_encoder_layers=`num_layers`,t.num_encoder_heads=`num_heads`,t.encoder_dim_kv=`d_kv`;break;case`bart`:case`mbart`:case`marian`:case`whisper`:case`lite-whisper`:case`m2m_100`:case`blenderbot`:case`blenderbot-small`:case`florence2_language`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`d_model`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`d_model`;break;case`speecht5`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`hidden_size`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`hidden_size`;break;case`trocr`:t.num_encoder_layers=t.num_decoder_layers=`decoder_layers`,t.num_encoder_heads=t.num_decoder_heads=`decoder_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`d_model`;break;case`musicgen_decoder`:t.num_encoder_layers=t.num_decoder_layers=`num_hidden_layers`,t.num_encoder_heads=t.num_decoder_heads=`num_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`moonshine`:t.num_decoder_layers=`decoder_num_hidden_layers`,t.num_decoder_heads=`decoder_num_key_value_heads`,t.num_encoder_layers=`encoder_num_hidden_layers`,t.num_encoder_heads=`encoder_num_key_value_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`cohere_asr`:t.num_decoder_layers=`num_hidden_layers`,t.num_decoder_heads=`num_key_value_heads`,t.decoder_hidden_size=`hidden_size`,t.decoder_dim_kv=`head_dim`;let{num_hidden_layers:r,num_attention_heads:i,hidden_size:a}=e.encoder_config;n={num_encoder_layers:r,num_encoder_heads:i,encoder_hidden_size:a,encoder_dim_kv:e.head_dim};break;case`vision-encoder-decoder`:let o=_0(e.decoder),s=`num_decoder_layers`in o,c=Xs(e,[`model_type`,`is_encoder_decoder`]);return s?(c.num_decoder_layers=o.num_decoder_layers,c.num_decoder_heads=o.num_decoder_heads,c.decoder_hidden_size=o.decoder_hidden_size,c.num_encoder_layers=o.num_encoder_layers,c.num_encoder_heads=o.num_encoder_heads,c.encoder_hidden_size=o.encoder_hidden_size):(c.num_layers=o.num_layers,c.num_heads=o.num_heads,c.hidden_size=o.hidden_size),c}let r={...n,...Xs(e,[`model_type`,`multi_query`,`is_encoder_decoder`])};for(let n in t)r[n]=e[t[n]];return r}function v0(e,t){e instanceof b0||(e=new b0(e));let n=t?.prefix??`past_key_values`,r=n===`present`?`present`:`past`,i=/* @__PURE__ */ new Set;if([`lfm2`,`lfm2_moe`,`lfm3`].includes(e.model_type)){let{layer_types:t}=e;for(let e=0;e<t.length;++e)if(t[e]===`full_attention`||t[e]===`sliding_attention`)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);else if(t[e]===`conv`)i.add(`${r}_conv.${e}`);else throw Error(`Unsupported layer type: ${t[e]}`);return i}if([`granitemoehybrid`,`falcon_h1`,`nemotron_h`].includes(e.model_type)){let t=e,a=t.layer_types??t.layers_block_type,o=t.num_hidden_layers??a?.length;for(let e=0;e<o;++e)a&&a[e]!==`mamba`||(i.add(`${r}_conv.${e}`),i.add(`${r}_ssm.${e}`)),a&&a[e]!==`attention`||(i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`));return i}if([`qwen3_next`,`qwen3_5_text`,`qwen3_5_moe_text`,`olmo_hybrid`].includes(e.model_type)){let{layer_types:t}=e;for(let a=0;a<t.length;++a)if(t[a]===`full_attention`)i.add(`${n}.${a}.key`),i.add(`${n}.${a}.value`);else if(t[a]===`linear_attention`)e.model_type===`olmo_hybrid`?(i.add(`${r}_conv.${a}.key`),i.add(`${r}_conv.${a}.value`),i.add(`${r}_conv.${a}.query`)):i.add(`${r}_conv.${a}`),i.add(`${r}_recurrent.${a}`);else throw Error(`Unsupported layer type: ${t[a]}`);return i}if([`gemma4`,`gemma4_text`].includes(e.model_type)){let t=e.model_type===`gemma4`?e.text_config:e,r=t.num_hidden_layers-(t.num_kv_shared_layers??0);for(let e=0;e<r;++e)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);return i}if(e.model_type===`deepseek_v4`){let{layer_types:t,num_hidden_layers:a}=e;for(let e=0;e<a;++e){i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);let a=t[e];if(a===`compressed_sparse_attention`)i.add(`${r}_compressor.${e}.kv`),i.add(`${r}_compressor.${e}.gate`),i.add(`${r}_indexer.${e}.kv`),i.add(`${r}_indexer.${e}.gate`);else if(a===`heavily_compressed_attention`)i.add(`${r}_compressor.${e}.kv`),i.add(`${r}_compressor.${e}.gate`);else if(a&&a!==`sliding_attention`)throw Error(`Unsupported layer type: ${a}`)}return i}if(e.model_type===`zaya`){let{num_hidden_layers:t,cca_time1:r}=e,a=r??1;for(let e=0;e<t;e+=a)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`),i.add(`${n}.${e}.conv_state`),i.add(`${n}.${e}.shift_state`);return i}if([`lfm2_vl`,`lfm3_vl`,`qwen3_5`,`qwen3_5_moe`,`voxtral_realtime`].includes(e.model_type)){let n;return n=e.model_type===`voxtral_realtime`&&t?.session_name===`audio_encoder`?e.audio_config:e.text_config,v0(n,t)}return y0(e,{prefix:n})}function y0(e,{prefix:t=`past_key_values`}={}){let n=/* @__PURE__ */ new Set,r=e.normalized_config;if(r.is_encoder_decoder&&`num_encoder_heads`in r&&`num_decoder_heads`in r)for(let e=0;e<r.num_decoder_layers;++e)n.add(`${t}.${e}.encoder.key`),n.add(`${t}.${e}.encoder.value`),n.add(`${t}.${e}.decoder.key`),n.add(`${t}.${e}.decoder.value`);else if(r.multi_query)for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key_value`);else for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key`),n.add(`${t}.${e}.value`);return n}var b0=class e{model_type=null;is_encoder_decoder=!1;max_position_embeddings;\"transformers.js_config\";constructor(e){Object.assign(this,e),this.normalized_config=_0(this)}static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:o=`main`}={}){r&&!(r instanceof e)&&(r=new e(r));let s=r??await g0(t,{progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:o});return new this(s)}},x0=class{static async from_pretrained(...e){return b0.from_pretrained(...e)}};function S0(e,t,n){return e?typeof e==`object`&&e?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(n)?+e[n]:0:+e:0}function C0(e,t){let n=[];for(let r=0;r<t;++r)n.push(`${e}_data${r===0?``:`_`+r}`);return n}async function w0(e,t,n,r){let i=`${t}${r}.onnx`;return await Gf(e,`${n.subfolder??``}/${i}`,!0,n,j.IS_NODE_ENV)}async function T0(e,t,n,r,i,a={}){let o=`${t}${n}.onnx`,s=j.IS_NODE_ENV,c=[],l=S0(i,o,t);if(l>0){if(l>hf)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${hf}).`);let t=C0(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(Gf(e,t,!0,r,s).then(e=>e instanceof Uint8Array?{path:n,data:e}:n))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await Gf(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function E0(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=Ip(n.device??a.device,t,{warn:e=>N.info(e)}),s=Sp(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=Hp(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>N.info(e)});if(!Vp.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(Rp).join(`, `)}`);if(o===`webgpu`&&!j.IS_NODE_ENV&&l===Rp.fp16&&!await Lp())throw Error(`The device (${o}) does not support fp16.`);let u=Vp[l],d={...n.session_options};d.executionProviders??=s;let f=a.free_dimension_overrides;f?d.freeDimensionOverrides??=f:o.startsWith(`webnn`)&&!d.freeDimensionOverrides&&N.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config[\"transformers.js_config\"][\"device_config\"][\"${o}\"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=w0(e,t,n,u),m=await T0(e,t,u,n,n.use_external_data_format??a.use_external_data_format,d);if(m.length>0&&(!j.IS_NODE_ENV||m.some(e=>typeof e!=`string`))&&(d.externalData=m),r&&o===`webgpu`){let e=v0(n.config,{prefix:`present`,session_name:i});if(e.size>0&&!jp()){let t={};for(let n of e)t[n]=`gpu-buffer`;d.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:d,session_config:{dtype:l,device:o}}}async function D0(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await E0(e,t[i],n,a,i);return[i,await Ep(o,s,c)]})))}function O0(e){for(let t in e)kp(e[t])?e[t]=new H(e[t]):typeof e[t]==`object`&&O0(e[t]);return e}async function J(e,t){let n=k0(e,t);try{return O0(await Op(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return j.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw N.error(`An error occurred during model execution: \"${e}\".`),N.error(`Inputs given to model:`,t),e}}function k0(e,t){let n=/* @__PURE__ */ Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];e instanceof H?n[i]=jp()?e.clone():e:r.push(i)}if(r.length>0)throw Error(`An error occurred during model execution: \"Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));N.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: \"${n.join(`, `)}\".`)}return n}var A0=class{},j0=class extends A0{constructor({last_hidden_state:e,hidden_states:t=null,attentions:n=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=n}},Y=class extends A0{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},M0=class extends A0{constructor({logits:e}){super(),this.logits=e}},N0=class extends A0{constructor({logits:e}){super(),this.logits=e}},P0=class extends A0{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},F0=class extends A0{constructor({logits:e}){super(),this.logits=e}},I0=class extends A0{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}},L0=class extends A0{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=i}},R0=class extends A0{constructor({alphas:e}){super(),this.alphas=e}},z0=class extends Vs{_call(e,t){throw Error(\"`_call` should be implemented in a subclass\")}},B0=class extends Vs{_call(e,t){throw Error(\"`_call` should be implemented in a subclass\")}},V0=class extends Vs{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},H0=class extends z0{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===1){let e=t[n].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}},U0=class extends z0{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.max_length-1){let e=t[n].data;e.fill(-1/0);for(let t of this.eos_token_id)e[t]=0}return t}},W0=class extends z0{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let n=0;n<e.length;++n){let e=t[n].data;for(let t of this.suppress_tokens)e[t]=-1/0}return t}},G0=class extends z0{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.begin_index){let e=t[n].data;for(let t of this.begin_suppress_tokens)e[t]=-1/0}return t}},K0=class extends z0{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,this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;if(r[this.no_timestamps_token_id]=-1/0,e[n].length===this.begin_index){r.subarray(0,this.timestamp_begin).fill(-1/0);continue}let i=e[n].slice(this.begin_index),a=i.length>=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=Zf(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>$f(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},q0=class extends z0{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){let t=[];for(let n=0;n<this.no_repeat_ngram_size;++n)t.push(e[r+n]);n.push(t.map(Number))}let r=/* @__PURE__ */ new Map;for(let e of n){let t=e.slice(0,e.length-1),n=JSON.stringify(t),i=r.get(n)??[];i.push(e[e.length-1]),r.set(n,i)}return r}getGeneratedNgrams(e,t){let n=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(n.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=this.calcBannedNgramTokens(e[n]);for(let e of i)r[e]=-1/0}return t}},J0=class extends z0{constructor(e){super(),this.penalty=e}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;for(let t of new Set(e[n])){let e=Number(t);r[e]<0?r[e]*=this.penalty:r[e]/=this.penalty}}return t}},Y0=class extends z0{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length<this.min_length){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},X0=class extends z0{constructor(e,t,n){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(n)?n:[n]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length-this.prompt_length_to_skip<this.min_new_tokens){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},Z0=class extends z0{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=e[n];for(let e of this.bad_words_ids){if(i.length<e.length-1)continue;let t=!0;for(let n=1;n<=e.length-1;++n)if(e.at(-n-1)!=i.at(-n)){t=!1;break}t&&(r[e.at(-1)]=-1/0)}}return t}},Q0=class extends z0{constructor(e){if(super(),e<=1)throw Error(`Require guidance scale >1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;e<i.data.length;++e)i.data[e]+=(r.data[e]-i.data[e])*this.guidance_scale;return i}},$0=class extends B0{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 n=t.data;for(let e=0;e<n.length;++e)n[e]/=this.temperature;return t}},ev=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Xs(e,Object.getOwnPropertyNames(this)))}},tv=class extends Vs{_call(e,t){throw Error(`StoppingCriteria needs to be subclassed`)}},nv=class e extends Vs{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(t){t instanceof e?t=t.criteria:t instanceof tv&&(t=[t]),this.criteria.push(...t)}_call(e,t){let n=Array(e.length).fill(!1);for(let r of this.criteria){let i=r(e,t);for(let e=0;e<n.length;++e)n[e]||=i[e]}return n}[Symbol.iterator](){return this.criteria.values()}},rv=class extends tv{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(e=>e.length>=this.max_length)}},iv=class extends tv{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},av=class extends Vs{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 n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return df(e)}static getSampler(e){if(e.do_sample)return new sv(e);if(e.num_beams>1)return new cv(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 ov(e)}},ov=class extends av{async sample(e){let t=$f(e.data)[1];return[[BigInt(t),0]]}},sv=class extends av{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[n,r]=await Yp(e,t),i=Xf(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},cv=class extends av{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[n,r]=await Yp(e,t),i=Xf(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},lv=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key \"${t}\" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof H))throw TypeError(`Expected a Tensor for key \"${t}\", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},X={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16,MultimodalEncoder:17},uv={[X.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[X.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[X.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[X.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[X.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[X.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},[X.MultimodalEncoder]:{sessions:(e,t)=>({model:t.model_file_name??`model`,...e.vision_config&&{vision_encoder:`vision_encoder`},...e.audio_config&&{audio_encoder:`audio_encoder`}})},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function dv(e,t,n={}){let r=uv[e]??uv.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function fv(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=xv.get(e);if(t!==void 0)return t}if(e.model_type){let t=xv.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(hv))if(t.has(e.model_type)){let n=xv.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;N.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${wh}`)}return X.EncoderOnly}function pv(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?Pf(bf(e,{cache_dir:n,local_files_only:r,revision:i}),()=>x0.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):x0.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function mv(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await pv(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=fv(t),f=(e,t=null)=>{t??=e;let n=Ip(l,e),r=Vp[Hp(u,e,n)]??``,i=`${t}${r}.onnx`,o=`${c}/${i}`;a.push(o);let d=S0(s,i,e);for(let e of C0(i,d)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=dv(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var hv=null;function gv(e){hv=e}function _v(e){if(e instanceof H)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 H(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}return new H(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function vv(e){return new H(`bool`,[e],[1])}var yv={[X.DecoderOnly]:{can_generate:!0,forward:Mv,prepare_inputs:Rv},[X.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Mv,prepare_inputs:Rv},[X.Seq2Seq]:{can_generate:!0,forward:wv,prepare_inputs:zv},[X.Vision2Seq]:{can_generate:!0,forward:wv,prepare_inputs:zv},[X.Musicgen]:{can_generate:!0,forward:wv},[X.EncoderDecoder]:{can_generate:!1,forward:wv},[X.ImageTextToText]:{can_generate:!0,forward:Fv,prepare_inputs:Bv},[X.AudioTextToText]:{can_generate:!0,forward:Pv,prepare_inputs:Bv},[X.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Bv},[X.Phi3V]:{can_generate:!0,prepare_inputs:Bv},[X.MultiModality]:{can_generate:!0},[X.AutoEncoder]:{can_generate:!1,forward:Ev},[X.Chatterbox]:{can_generate:!0,forward:Tv},[X.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Rv},default:{can_generate:!1,forward:Tv}};function bv(e,t){let n=xv.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=xv.get(i);e!==void 0&&(n=e,r=!0)}let a=yv[n]??yv.default,o=uv[n]??uv.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var xv=/* @__PURE__ */ new Map,Sv=/* @__PURE__ */ new Map,Cv=/* @__PURE__ */ new Map,Z=class extends Vs{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=bv(Cv.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=Cv.get(this);n=f.config=await x0.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=bv(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&N.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${wh}.`)}if(t&&!(t instanceof Us)){let r={};try{let t=await mv(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>If(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){N.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new Us(t,r))}let _=[D0(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(Wv(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new V0;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new J0(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new q0(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new Z0(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new Y0(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new X0(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new H0(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new U0(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new W0(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new G0(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new Q0(e.guidance_scale)),e.temperature===0&&e.do_sample&&(N.warn(\"`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`.\"),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new $0(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=ev){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,Xs(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new nv;return e.max_length!==null&&n.push(new rv(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new iv(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[hv.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,hv.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,hv.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,hv.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Cv.get(this.constructor),n=/* @__PURE__ */ new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=Dv(t,n.past_key_values),n.input_ids=new H(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=U([n.decoder_attention_mask,um([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=U([n.attention_mask,um([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=Xs(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error(\"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...\")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...Xs(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Tv(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=U([i,lm(i,0)],0),`attention_mask`in t&&(t.attention_mask=U([t.attention_mask,pm(t.attention_mask)],0));else if(t.decoder_input_ids){let e=_v(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=U(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof H)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\\`decoder_start_token_id\\` expected to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=_v(o)}return s.decoder_attention_mask=dm(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=av.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate){if(t.output_attentions){let e=Ov(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,Xs(v,this._return_dict_in_generate_keys))}let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;t<e.dims.at(0);++t){let r=await h(e[t]);for(let[e,i]of r){let r=BigInt(e);g[t]+=i,_[t].push(r),n.push([r]);break}}if(i&&i.put(n),p(_).every(e=>e))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new H(`int64`,_.flat(),[_.length,_[0].length]),S=Dv(v,s.past_key_values),C=new Set(Object.values(S));for(let e of Object.values(v))e.location===`gpu-buffer`&&!C.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await S.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:S,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await J(r,Xs(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function wv(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Tv(e,Xs(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await Mv(e,o,!0)}async function Tv(e,t){let n=e.sessions.model,r=Xs(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error(\"Both `input_ids` and `inputs_embeds` are missing in the model inputs.\");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error(\"Both `input_ids` and `token_type_ids` are missing in the model inputs.\");r.token_type_ids=pm(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error(\"Both `pixel_values` and `pixel_mask` are missing in the model inputs.\");let e=r.pixel_values.dims;r.pixel_mask=um([e[0],e[2],e[3]])}return await J(n,r)}async function Ev(e,t){let n=await e.encode(t);return await e.decode(n)}function Dv(e,t){let n=/* @__PURE__ */ Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present_compressor`,`past_compressor`).replace(`present_indexer`,`past_indexer`).replace(`present`,`past_key_values`);n[i]=r.includes(`encoder`)&&t?t[i]:e[r]}return t?(t.update(n),t):new lv(n)}function Ov(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function kv(e,t){return e.map(e=>typeof e==`number`?e:t[e]??0)}function Av(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=v0(e.config),o=e.config?.normalized_config?.num_heads,s={batch_size:i};typeof o==`number`&&(s[`batch_size x num_heads`]=i*o);let c=/* @__PURE__ */ Object.create(null);for(let e of r.inputMetadata){if(!a.has(e.name))continue;let n=kv(e.shape,s),r=n.reduce((e,t)=>e*t,1),i=Up[e.type],o=new H(e.type,new i(r),n);t[e.name]=o,c[e.name]=o}return n?(n.update(c),n):new lv(c)}function jv(e,t,n){t.num_logits_to_keep||(e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes(`num_logits_to_keep`)&&(t.num_logits_to_keep=new H(`int64`,[n],[]))}async function Mv(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=vv(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=Lv(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),jv(e,a,0n),Av(e,a,i),await J(r,Xs(a,r.inputNames))}async function Nv(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,num_logits_to_keep:f=null,...p}){if(!c){c=await e.encode_text({input_ids:a,...p});let s=Xs(p,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...p});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=U([um([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`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:t,video_grid_thw:n}=p;[s]=e.get_rope_index(a,t,n,o)}return await Mv(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d,num_logits_to_keep:f},!0)}async function Pv(e,t){return await Nv(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 Fv(e,t){return await Nv(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 Iv(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;e<n;++e){let n=e*r,o=BigInt(t);for(let e=0;e<r;++e){let t=n+e;i[t]===0n?a[t]=BigInt(1):(a[t]=o,o+=i[t])}}return{data:a,dims:e.dims}}function Lv(e,t=null,n=0){let{input_ids:r,inputs_embeds:i,attention_mask:a}=e,{data:o,dims:s}=Iv(a,n),c=new H(`int64`,o,s);if(t){let e=-(r??i).dims.at(1);c=c.slice(null,[e,null])}return c}function Rv(e,t,n,r){let i=n.past_key_values?n.past_key_values.get_seq_length():0;if(jv(e,n,1n),!n.attention_mask){let e;for(let t of[`input_ids`,`inputs_embeds`,`position_ids`])if(n[t]){e=n[t].dims;break}if(!e)throw Error(`attention_mask is not provided, and unable to infer its shape from model inputs.`);n.attention_mask=um([e[0],i+e[1]])}if(n.past_key_values){let{input_ids:e,attention_mask:t}=n;t&&t.dims[1]>e.dims[1]||i<e.dims[1]&&(n.input_ids=e.slice(null,[i,null]))}return n}function zv(e,t,n,r){return n.past_key_values&&(t=t.map(e=>[e.at(-1)])),jv(e,n,1n),{...n,decoder_input_ids:_v(t)}}function Bv(e,...t){return e.config.is_encoder_decoder?zv(e,...t):Rv(e,...t)}function Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e<a.length;++e){let r=a[e],i=t[e];for(let e=0;e<r.length;++e)i[r[e]].data.set(n[c++].data)}return{inputs_embeds:t,attention_mask:i}}function Hv({image_token_id:e,inputs_embeds:t,image_features:n,input_ids:r,attention_mask:i}){return Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}function Uv({audio_token_id:e,inputs_embeds:t,audio_features:n,input_ids:r,attention_mask:i}){return Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}async function Wv(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map(async r=>[r,await qf(e,t[r],!1,n)])))}var Gv={};us(Gv,{ASTForAudioClassification:()=>cy,ASTModel:()=>sy,ASTPreTrainedModel:()=>oy,AfmoeForCausalLM:()=>ny,AfmoeModel:()=>ty,AfmoePreTrainedModel:()=>ey,AlbertForMaskedLM:()=>Xv,AlbertForQuestionAnswering:()=>Yv,AlbertForSequenceClassification:()=>Jv,AlbertModel:()=>qv,AlbertPreTrainedModel:()=>Kv,ApertusForCausalLM:()=>$v,ApertusModel:()=>Qv,ApertusPreTrainedModel:()=>Zv,ArceeForCausalLM:()=>ay,ArceeModel:()=>iy,ArceePreTrainedModel:()=>ry,BartForConditionalGeneration:()=>dy,BartForSequenceClassification:()=>fy,BartModel:()=>uy,BartPretrainedModel:()=>ly,BaseModelOutput:()=>j0,BeitForImageClassification:()=>hy,BeitModel:()=>my,BeitPreTrainedModel:()=>py,BertForMaskedLM:()=>vy,BertForQuestionAnswering:()=>xy,BertForSequenceClassification:()=>yy,BertForTokenClassification:()=>by,BertModel:()=>_y,BertPreTrainedModel:()=>gy,BlenderbotForConditionalGeneration:()=>wy,BlenderbotModel:()=>Cy,BlenderbotPreTrainedModel:()=>Sy,BlenderbotSmallForConditionalGeneration:()=>Dy,BlenderbotSmallModel:()=>Ey,BlenderbotSmallPreTrainedModel:()=>Ty,BloomForCausalLM:()=>Ay,BloomModel:()=>ky,BloomPreTrainedModel:()=>Oy,CHMv2ForDepthEstimation:()=>Wy,CHMv2PreTrainedModel:()=>Uy,CLIPModel:()=>Xy,CLIPPreTrainedModel:()=>Yy,CLIPSegForImageSegmentation:()=>r2,CLIPSegModel:()=>n2,CLIPSegPreTrainedModel:()=>t2,CLIPTextModel:()=>Zy,CLIPTextModelWithProjection:()=>Qy,CLIPVisionModel:()=>$y,CLIPVisionModelWithProjection:()=>e2,CamembertForMaskedLM:()=>Ny,CamembertForQuestionAnswering:()=>Iy,CamembertForSequenceClassification:()=>Py,CamembertForTokenClassification:()=>Fy,CamembertModel:()=>My,CamembertPreTrainedModel:()=>jy,CausalLMOutput:()=>F0,CausalLMOutputWithPast:()=>I0,ChatterboxModel:()=>By,ChatterboxPreTrainedModel:()=>zy,ChineseCLIPModel:()=>Hy,ChineseCLIPPreTrainedModel:()=>Vy,ClapAudioModelWithProjection:()=>Jy,ClapModel:()=>Ky,ClapPreTrainedModel:()=>Gy,ClapTextModelWithProjection:()=>qy,CodeGenForCausalLM:()=>o2,CodeGenModel:()=>a2,CodeGenPreTrainedModel:()=>i2,Cohere2ForCausalLM:()=>f2,Cohere2Model:()=>d2,Cohere2PreTrainedModel:()=>u2,CohereAsrForConditionalGeneration:()=>h2,CohereAsrModel:()=>m2,CohereAsrPreTrainedModel:()=>p2,CohereForCausalLM:()=>l2,CohereModel:()=>c2,CoherePreTrainedModel:()=>s2,ConvBertForMaskedLM:()=>v2,ConvBertForQuestionAnswering:()=>x2,ConvBertForSequenceClassification:()=>y2,ConvBertForTokenClassification:()=>b2,ConvBertModel:()=>_2,ConvBertPreTrainedModel:()=>g2,ConvNextForImageClassification:()=>w2,ConvNextModel:()=>C2,ConvNextPreTrainedModel:()=>S2,ConvNextV2ForImageClassification:()=>D2,ConvNextV2Model:()=>E2,ConvNextV2PreTrainedModel:()=>T2,DFineForObjectDetection:()=>P2,DFineModel:()=>N2,DFinePreTrainedModel:()=>M2,DINOv3ConvNextModel:()=>D4,DINOv3ConvNextPreTrainedModel:()=>E4,DINOv3ViTModel:()=>k4,DINOv3ViTPreTrainedModel:()=>O4,DPTForDepthEstimation:()=>B4,DPTModel:()=>z4,DPTPreTrainedModel:()=>R4,DacDecoderModel:()=>B2,DacDecoderOutput:()=>I2,DacEncoderModel:()=>z2,DacEncoderOutput:()=>F2,DacModel:()=>R2,DacPreTrainedModel:()=>L2,DebertaForMaskedLM:()=>U2,DebertaForQuestionAnswering:()=>K2,DebertaForSequenceClassification:()=>W2,DebertaForTokenClassification:()=>G2,DebertaModel:()=>H2,DebertaPreTrainedModel:()=>V2,DebertaV2ForMaskedLM:()=>t4,DebertaV2ForQuestionAnswering:()=>i4,DebertaV2ForSequenceClassification:()=>n4,DebertaV2ForTokenClassification:()=>r4,DebertaV2Model:()=>e4,DebertaV2PreTrainedModel:()=>$2,DecisionTransformerModel:()=>o4,DecisionTransformerPreTrainedModel:()=>a4,DeepseekV3ForCausalLM:()=>Y2,DeepseekV3Model:()=>J2,DeepseekV3PreTrainedModel:()=>q2,DeepseekV4ForCausalLM:()=>Q2,DeepseekV4Model:()=>Z2,DeepseekV4PreTrainedModel:()=>X2,DeiTForImageClassification:()=>l4,DeiTModel:()=>c4,DeiTPreTrainedModel:()=>s4,DepthAnythingForDepthEstimation:()=>d4,DepthAnythingPreTrainedModel:()=>u4,DepthProForDepthEstimation:()=>p4,DepthProPreTrainedModel:()=>f4,DetrForObjectDetection:()=>g4,DetrForSegmentation:()=>_4,DetrModel:()=>h4,DetrObjectDetectionOutput:()=>v4,DetrPreTrainedModel:()=>m4,DetrSegmentationOutput:()=>y4,Dinov2ForImageClassification:()=>S4,Dinov2Model:()=>x4,Dinov2PreTrainedModel:()=>b4,Dinov2WithRegistersForImageClassification:()=>T4,Dinov2WithRegistersModel:()=>w4,Dinov2WithRegistersPreTrainedModel:()=>C4,DistilBertForMaskedLM:()=>F4,DistilBertForQuestionAnswering:()=>P4,DistilBertForSequenceClassification:()=>M4,DistilBertForTokenClassification:()=>N4,DistilBertModel:()=>j4,DistilBertPreTrainedModel:()=>A4,DonutSwinModel:()=>L4,DonutSwinPreTrainedModel:()=>I4,EdgeTamModel:()=>N7,EfficientNetForImageClassification:()=>U4,EfficientNetModel:()=>H4,EfficientNetPreTrainedModel:()=>V4,ElectraForMaskedLM:()=>K4,ElectraForQuestionAnswering:()=>Y4,ElectraForSequenceClassification:()=>q4,ElectraForTokenClassification:()=>J4,ElectraModel:()=>G4,ElectraPreTrainedModel:()=>W4,EmbeddingGemma2Model:()=>Z4,EmbeddingGemma2PreTrainedModel:()=>X4,Ernie4_5ForCausalLM:()=>e3,Ernie4_5Model:()=>$4,Ernie4_5PretrainedModel:()=>Q4,EsmForMaskedLM:()=>r3,EsmForSequenceClassification:()=>i3,EsmForTokenClassification:()=>a3,EsmModel:()=>n3,EsmPreTrainedModel:()=>t3,EuroBertForMaskedLM:()=>c3,EuroBertForSequenceClassification:()=>l3,EuroBertForTokenClassification:()=>u3,EuroBertModel:()=>s3,EuroBertPreTrainedModel:()=>o3,ExaoneForCausalLM:()=>p3,ExaoneModel:()=>f3,ExaonePreTrainedModel:()=>d3,FalconForCausalLM:()=>g3,FalconH1ForCausalLM:()=>y3,FalconH1Model:()=>v3,FalconH1PreTrainedModel:()=>_3,FalconModel:()=>h3,FalconPreTrainedModel:()=>m3,FastViTForImageClassification:()=>S3,FastViTModel:()=>x3,FastViTPreTrainedModel:()=>b3,Florence2ForConditionalGeneration:()=>w3,Florence2PreTrainedModel:()=>C3,GLPNForDepthEstimation:()=>i6,GLPNModel:()=>r6,GLPNPreTrainedModel:()=>n6,GPT2LMHeadModel:()=>y6,GPT2Model:()=>v6,GPT2PreTrainedModel:()=>_6,GPTBigCodeForCausalLM:()=>s6,GPTBigCodeModel:()=>o6,GPTBigCodePreTrainedModel:()=>a6,GPTJForCausalLM:()=>S6,GPTJModel:()=>x6,GPTJPreTrainedModel:()=>b6,GPTNeoForCausalLM:()=>u6,GPTNeoModel:()=>l6,GPTNeoPreTrainedModel:()=>c6,GPTNeoXForCausalLM:()=>p6,GPTNeoXModel:()=>f6,GPTNeoXPreTrainedModel:()=>d6,Gemma2ForCausalLM:()=>A3,Gemma2Model:()=>k3,Gemma2PreTrainedModel:()=>O3,Gemma3ForCausalLM:()=>R3,Gemma3ForConditionalGeneration:()=>L3,Gemma3Model:()=>I3,Gemma3PreTrainedModel:()=>F3,Gemma3nForCausalLM:()=>V3,Gemma3nForConditionalGeneration:()=>B3,Gemma3nPreTrainedModel:()=>z3,Gemma4ForCausalLM:()=>U3,Gemma4ForConditionalGeneration:()=>H3,GemmaForCausalLM:()=>D3,GemmaModel:()=>E3,GemmaPreTrainedModel:()=>T3,GlmForCausalLM:()=>K3,GlmModel:()=>G3,GlmMoeDsaForCausalLM:()=>Y3,GlmMoeDsaModel:()=>J3,GlmMoeDsaPreTrainedModel:()=>q3,GlmOcrForConditionalGeneration:()=>t6,GlmPreTrainedModel:()=>W3,GptOssForCausalLM:()=>g6,GptOssModel:()=>h6,GptOssPreTrainedModel:()=>m6,GraniteForCausalLM:()=>T6,GraniteModel:()=>w6,GraniteMoeHybridForCausalLM:()=>O6,GraniteMoeHybridModel:()=>D6,GraniteMoeHybridPreTrainedModel:()=>E6,GranitePreTrainedModel:()=>C6,GraniteSpeechForConditionalGeneration:()=>j6,GroundingDinoForObjectDetection:()=>N6,GroundingDinoPreTrainedModel:()=>M6,GroupViTModel:()=>F6,GroupViTPreTrainedModel:()=>P6,HeliumForCausalLM:()=>R6,HeliumModel:()=>L6,HeliumPreTrainedModel:()=>I6,HieraForImageClassification:()=>V6,HieraModel:()=>B6,HieraPreTrainedModel:()=>z6,HrmTextForCausalLM:()=>W6,HrmTextModel:()=>U6,HrmTextPreTrainedModel:()=>H6,HubertForCTC:()=>Q6,HubertForSequenceClassification:()=>$6,HubertModel:()=>Z6,HubertPreTrainedModel:()=>X6,HunYuanDenseV1ForCausalLM:()=>nb,HunYuanDenseV1Model:()=>tb,HunYuanDenseV1PreTrainedModel:()=>eb,IJepaForImageClassification:()=>ob,IJepaModel:()=>ab,IJepaPreTrainedModel:()=>ib,Idefics3ForConditionalGeneration:()=>rb,ImageMattingOutput:()=>R0,JAISLMHeadModel:()=>lb,JAISModel:()=>cb,JAISPreTrainedModel:()=>sb,JinaCLIPModel:()=>db,JinaCLIPPreTrainedModel:()=>ub,JinaCLIPTextModel:()=>fb,JinaCLIPVisionModel:()=>pb,Lfm2ForCausalLM:()=>gb,Lfm2Model:()=>hb,Lfm2MoeForCausalLM:()=>bb,Lfm2MoeModel:()=>yb,Lfm2MoePreTrainedModel:()=>vb,Lfm2PreTrainedModel:()=>mb,Lfm2VlForConditionalGeneration:()=>xb,Lfm3ForCausalLM:()=>wb,Lfm3Model:()=>Cb,Lfm3PreTrainedModel:()=>Sb,Lfm3VlForConditionalGeneration:()=>Tb,LightOnOcrForConditionalGeneration:()=>_b,LiteWhisperForConditionalGeneration:()=>HS,Llama4ForCausalLM:()=>Ab,Llama4PreTrainedModel:()=>kb,LlamaForCausalLM:()=>Ob,LlamaModel:()=>Db,LlamaPreTrainedModel:()=>Eb,LlavaForConditionalGeneration:()=>M3,LlavaOnevisionForConditionalGeneration:()=>M3,LlavaPreTrainedModel:()=>j3,LlavaQwen2ForCausalLM:()=>P3,LongT5ForConditionalGeneration:()=>Nb,LongT5Model:()=>Mb,LongT5PreTrainedModel:()=>jb,M2M100ForConditionalGeneration:()=>Ib,M2M100Model:()=>Fb,M2M100PreTrainedModel:()=>Pb,MBartForCausalLM:()=>qb,MBartForConditionalGeneration:()=>Gb,MBartForSequenceClassification:()=>Kb,MBartModel:()=>Wb,MBartPreTrainedModel:()=>Ub,MPNetForMaskedLM:()=>lx,MPNetForQuestionAnswering:()=>fx,MPNetForSequenceClassification:()=>ux,MPNetForTokenClassification:()=>dx,MPNetModel:()=>cx,MPNetPreTrainedModel:()=>sx,MT5ForConditionalGeneration:()=>vx,MT5Model:()=>_x,MT5PreTrainedModel:()=>gx,MarianMTModel:()=>zb,MarianModel:()=>Rb,MarianPreTrainedModel:()=>Lb,MaskFormerForInstanceSegmentation:()=>Hb,MaskFormerModel:()=>Vb,MaskFormerPreTrainedModel:()=>Bb,MaskedLMOutput:()=>N0,Metric3DForDepthEstimation:()=>Yb,Metric3DPreTrainedModel:()=>Jb,Metric3Dv2ForDepthEstimation:()=>Zb,Metric3Dv2PreTrainedModel:()=>Xb,MgpstrForSceneTextRecognition:()=>e8,MgpstrModelOutput:()=>Qb,MgpstrPreTrainedModel:()=>$b,MimiDecoderModel:()=>o8,MimiDecoderOutput:()=>n8,MimiEncoderModel:()=>a8,MimiEncoderOutput:()=>t8,MimiModel:()=>i8,MimiPreTrainedModel:()=>r8,Ministral3ForCausalLM:()=>f8,Ministral3Model:()=>d8,Ministral3PreTrainedModel:()=>u8,MinistralForCausalLM:()=>l8,MinistralModel:()=>c8,MinistralPreTrainedModel:()=>s8,Mistral3ForConditionalGeneration:()=>g8,Mistral4ForCausalLM:()=>y8,Mistral4Model:()=>v8,Mistral4PreTrainedModel:()=>_8,MistralForCausalLM:()=>h8,MistralModel:()=>m8,MistralPreTrainedModel:()=>p8,MobileBertForMaskedLM:()=>S8,MobileBertForQuestionAnswering:()=>w8,MobileBertForSequenceClassification:()=>C8,MobileBertModel:()=>x8,MobileBertPreTrainedModel:()=>b8,MobileLLMForCausalLM:()=>D8,MobileLLMModel:()=>E8,MobileLLMPreTrainedModel:()=>T8,MobileNetV1ForImageClassification:()=>A8,MobileNetV1ForSemanticSegmentation:()=>j8,MobileNetV1Model:()=>k8,MobileNetV1PreTrainedModel:()=>O8,MobileNetV2ForImageClassification:()=>P8,MobileNetV2ForSemanticSegmentation:()=>F8,MobileNetV2Model:()=>N8,MobileNetV2PreTrainedModel:()=>M8,MobileNetV3ForImageClassification:()=>R8,MobileNetV3ForSemanticSegmentation:()=>z8,MobileNetV3Model:()=>L8,MobileNetV3PreTrainedModel:()=>I8,MobileNetV4ForImageClassification:()=>H8,MobileNetV4ForSemanticSegmentation:()=>U8,MobileNetV4Model:()=>V8,MobileNetV4PreTrainedModel:()=>B8,MobileViTForImageClassification:()=>K8,MobileViTModel:()=>G8,MobileViTPreTrainedModel:()=>W8,MobileViTV2ForImageClassification:()=>Y8,MobileViTV2Model:()=>J8,MobileViTV2PreTrainedModel:()=>q8,ModelOutput:()=>A0,ModernBertDecoderForCausalLM:()=>rx,ModernBertDecoderModel:()=>nx,ModernBertDecoderPreTrainedModel:()=>tx,ModernBertForMaskedLM:()=>Q8,ModernBertForSequenceClassification:()=>$8,ModernBertForTokenClassification:()=>ex,ModernBertModel:()=>Z8,ModernBertPreTrainedModel:()=>X8,Moondream1ForConditionalGeneration:()=>N3,MoonshineForConditionalGeneration:()=>ox,MoonshineModel:()=>ax,MoonshinePreTrainedModel:()=>ix,MptForCausalLM:()=>hx,MptModel:()=>mx,MptPreTrainedModel:()=>px,MultiModalityCausalLM:()=>bx,MultiModalityPreTrainedModel:()=>yx,MusicgenForCausalLM:()=>Cx,MusicgenForConditionalGeneration:()=>wx,MusicgenModel:()=>Sx,MusicgenPreTrainedModel:()=>xx,NanoChatForCausalLM:()=>Dx,NanoChatModel:()=>Ex,NanoChatPreTrainedModel:()=>Tx,NemotronHForCausalLM:()=>Ax,NemotronHModel:()=>kx,NemotronHPreTrainedModel:()=>Ox,NeoBertForMaskedLM:()=>Nx,NeoBertForQuestionAnswering:()=>Ix,NeoBertForSequenceClassification:()=>Px,NeoBertForTokenClassification:()=>Fx,NeoBertModel:()=>Mx,NeoBertPreTrainedModel:()=>jx,NomicBertModel:()=>Rx,NomicBertPreTrainedModel:()=>Lx,OPTForCausalLM:()=>a5,OPTModel:()=>i5,OPTPreTrainedModel:()=>r5,Olmo2ForCausalLM:()=>Wx,Olmo2Model:()=>Ux,Olmo2PreTrainedModel:()=>Hx,Olmo3ForCausalLM:()=>qx,Olmo3Model:()=>Kx,Olmo3PreTrainedModel:()=>Gx,OlmoForCausalLM:()=>Vx,OlmoHybridForCausalLM:()=>Xx,OlmoHybridModel:()=>Yx,OlmoHybridPreTrainedModel:()=>Jx,OlmoModel:()=>Bx,OlmoPreTrainedModel:()=>zx,OpenAIPrivacyFilterForTokenClassification:()=>$x,OpenAIPrivacyFilterModel:()=>Qx,OpenAIPrivacyFilterPreTrainedModel:()=>Zx,OpenELMForCausalLM:()=>n5,OpenELMModel:()=>t5,OpenELMPreTrainedModel:()=>e5,OwlViTForObjectDetection:()=>d5,OwlViTModel:()=>u5,OwlViTPreTrainedModel:()=>l5,Owlv2ForObjectDetection:()=>c5,Owlv2Model:()=>s5,Owlv2PreTrainedModel:()=>o5,PaliGemmaForConditionalGeneration:()=>f5,ParakeetForCTC:()=>m5,ParakeetPreTrainedModel:()=>p5,PatchTSMixerForPrediction:()=>_5,PatchTSMixerModel:()=>g5,PatchTSMixerPreTrainedModel:()=>h5,PatchTSTForPrediction:()=>b5,PatchTSTModel:()=>y5,PatchTSTPreTrainedModel:()=>v5,Phi3ForCausalLM:()=>E5,Phi3Model:()=>T5,Phi3PreTrainedModel:()=>w5,Phi3VForCausalLM:()=>O5,Phi3VPreTrainedModel:()=>D5,PhiForCausalLM:()=>C5,PhiModel:()=>S5,PhiPreTrainedModel:()=>x5,PreTrainedModel:()=>Z,PvtForImageClassification:()=>j5,PvtModel:()=>A5,PvtPreTrainedModel:()=>k5,PyAnnoteForAudioFrameClassification:()=>P5,PyAnnoteModel:()=>N5,PyAnnotePreTrainedModel:()=>M5,QuestionAnsweringModelOutput:()=>P0,Qwen2ForCausalLM:()=>L5,Qwen2Model:()=>I5,Qwen2MoeForCausalLM:()=>B5,Qwen2MoeModel:()=>z5,Qwen2MoePreTrainedModel:()=>R5,Qwen2PreTrainedModel:()=>F5,Qwen2VLForCausalLM:()=>Q3,Qwen2VLForConditionalGeneration:()=>Z3,Qwen2VLPreTrainedModel:()=>X3,Qwen2_5_VLForCausalLM:()=>e6,Qwen2_5_VLForConditionalGeneration:()=>$3,Qwen3ForCausalLM:()=>U5,Qwen3Model:()=>H5,Qwen3MoeForCausalLM:()=>K5,Qwen3MoeModel:()=>G5,Qwen3MoePreTrainedModel:()=>W5,Qwen3NextForCausalLM:()=>Y5,Qwen3NextModel:()=>J5,Qwen3NextPreTrainedModel:()=>q5,Qwen3PreTrainedModel:()=>V5,Qwen3VLForCausalLM:()=>Z5,Qwen3VLForConditionalGeneration:()=>X5,Qwen3VLMoeForCausalLM:()=>$5,Qwen3VLMoeForConditionalGeneration:()=>Q5,Qwen3_5ForCausalLM:()=>t7,Qwen3_5ForConditionalGeneration:()=>e7,Qwen3_5MoeForCausalLM:()=>r7,Qwen3_5MoeForConditionalGeneration:()=>n7,RFDetrForObjectDetection:()=>l7,RFDetrModel:()=>c7,RFDetrObjectDetectionOutput:()=>u7,RFDetrPreTrainedModel:()=>s7,RTDetrForObjectDetection:()=>A2,RTDetrModel:()=>k2,RTDetrObjectDetectionOutput:()=>j2,RTDetrPreTrainedModel:()=>O2,RTDetrV2ForObjectDetection:()=>T7,RTDetrV2Model:()=>w7,RTDetrV2ObjectDetectionOutput:()=>E7,RTDetrV2PreTrainedModel:()=>C7,ResNetForImageClassification:()=>o7,ResNetModel:()=>a7,ResNetPreTrainedModel:()=>i7,RoFormerForMaskedLM:()=>y7,RoFormerForQuestionAnswering:()=>S7,RoFormerForSequenceClassification:()=>b7,RoFormerForTokenClassification:()=>x7,RoFormerModel:()=>v7,RoFormerPreTrainedModel:()=>_7,RobertaForMaskedLM:()=>p7,RobertaForQuestionAnswering:()=>g7,RobertaForSequenceClassification:()=>m7,RobertaForTokenClassification:()=>h7,RobertaModel:()=>f7,RobertaPreTrainedModel:()=>d7,Sam2ImageSegmentationOutput:()=>A7,Sam2Model:()=>M7,Sam2PreTrainedModel:()=>j7,Sam3TrackerModel:()=>P7,SamImageSegmentationOutput:()=>D7,SamModel:()=>k7,SamPreTrainedModel:()=>O7,SapiensForDepthEstimation:()=>L7,SapiensForNormalEstimation:()=>R7,SapiensForSemanticSegmentation:()=>I7,SapiensPreTrainedModel:()=>F7,SegformerForImageClassification:()=>V7,SegformerForSemanticSegmentation:()=>H7,SegformerModel:()=>B7,SegformerPreTrainedModel:()=>z7,Seq2SeqLMOutput:()=>L0,SequenceClassifierOutput:()=>Y,SiglipModel:()=>W7,SiglipPreTrainedModel:()=>U7,SiglipTextModel:()=>G7,SiglipVisionModel:()=>K7,SmolLM3ForCausalLM:()=>Y7,SmolLM3Model:()=>J7,SmolLM3PreTrainedModel:()=>q7,SmolVLMForConditionalGeneration:()=>X7,SnacDecoderModel:()=>e9,SnacEncoderModel:()=>$7,SnacModel:()=>Q7,SnacPreTrainedModel:()=>Z7,SolarOpenForCausalLM:()=>r9,SolarOpenModel:()=>n9,SolarOpenPreTrainedModel:()=>t9,SpeechT5ForSpeechToText:()=>o9,SpeechT5ForTextToSpeech:()=>s9,SpeechT5HifiGan:()=>c9,SpeechT5Model:()=>a9,SpeechT5PreTrainedModel:()=>i9,SqueezeBertForMaskedLM:()=>d9,SqueezeBertForQuestionAnswering:()=>p9,SqueezeBertForSequenceClassification:()=>f9,SqueezeBertModel:()=>u9,SqueezeBertPreTrainedModel:()=>l9,StableLmForCausalLM:()=>g9,StableLmModel:()=>h9,StableLmPreTrainedModel:()=>m9,Starcoder2ForCausalLM:()=>y9,Starcoder2Model:()=>v9,Starcoder2PreTrainedModel:()=>_9,StyleTextToSpeech2Model:()=>x9,StyleTextToSpeech2PreTrainedModel:()=>b9,SupertonicForConditionalGeneration:()=>C9,SupertonicPreTrainedModel:()=>S9,Swin2SRForImageSuperResolution:()=>A9,Swin2SRModel:()=>k9,Swin2SRPreTrainedModel:()=>O9,SwinForImageClassification:()=>E9,SwinForSemanticSegmentation:()=>D9,SwinModel:()=>T9,SwinPreTrainedModel:()=>w9,T5ForConditionalGeneration:()=>N9,T5Model:()=>M9,T5PreTrainedModel:()=>j9,TableTransformerForObjectDetection:()=>I9,TableTransformerModel:()=>F9,TableTransformerObjectDetectionOutput:()=>L9,TableTransformerPreTrainedModel:()=>P9,TokenClassifierOutput:()=>M0,TrOCRForCausalLM:()=>z9,TrOCRPreTrainedModel:()=>R9,UltravoxModel:()=>A6,UltravoxPreTrainedModel:()=>k6,UniSpeechForCTC:()=>H9,UniSpeechForSequenceClassification:()=>U9,UniSpeechModel:()=>V9,UniSpeechPreTrainedModel:()=>B9,UniSpeechSatForAudioFrameClassification:()=>J9,UniSpeechSatForCTC:()=>K9,UniSpeechSatForSequenceClassification:()=>q9,UniSpeechSatModel:()=>G9,UniSpeechSatPreTrainedModel:()=>W9,VaultGemmaForCausalLM:()=>Z9,VaultGemmaModel:()=>X9,VaultGemmaPreTrainedModel:()=>Y9,ViTForImageClassification:()=>tS,ViTMAEModel:()=>rS,ViTMAEPreTrainedModel:()=>nS,ViTMSNForImageClassification:()=>oS,ViTMSNModel:()=>aS,ViTMSNPreTrainedModel:()=>iS,ViTModel:()=>eS,ViTPreTrainedModel:()=>$9,VisionEncoderDecoderModel:()=>Q9,VitMatteForImageMatting:()=>cS,VitMattePreTrainedModel:()=>sS,VitPoseForPoseEstimation:()=>uS,VitPosePreTrainedModel:()=>lS,VitsModel:()=>pS,VitsModelOutput:()=>dS,VitsPreTrainedModel:()=>fS,VoxtralForConditionalGeneration:()=>mS,VoxtralRealtimeForConditionalGeneration:()=>wS,VoxtralRealtimePreTrainedModel:()=>CS,Wav2Vec2BertForCTC:()=>DS,Wav2Vec2BertForSequenceClassification:()=>OS,Wav2Vec2BertModel:()=>ES,Wav2Vec2BertPreTrainedModel:()=>TS,Wav2Vec2ForAudioFrameClassification:()=>Y6,Wav2Vec2ForCTC:()=>q6,Wav2Vec2ForSequenceClassification:()=>J6,Wav2Vec2Model:()=>K6,Wav2Vec2PreTrainedModel:()=>G6,WavLMForAudioFrameClassification:()=>FS,WavLMForCTC:()=>MS,WavLMForSequenceClassification:()=>NS,WavLMForXVector:()=>PS,WavLMModel:()=>jS,WavLMPreTrainedModel:()=>AS,WeSpeakerResNetModel:()=>LS,WeSpeakerResNetPreTrainedModel:()=>IS,WhisperForConditionalGeneration:()=>VS,WhisperModel:()=>BS,WhisperPreTrainedModel:()=>zS,XLMForQuestionAnswering:()=>JS,XLMForSequenceClassification:()=>KS,XLMForTokenClassification:()=>qS,XLMModel:()=>WS,XLMPreTrainedModel:()=>US,XLMRobertaForMaskedLM:()=>ZS,XLMRobertaForQuestionAnswering:()=>eC,XLMRobertaForSequenceClassification:()=>QS,XLMRobertaForTokenClassification:()=>$S,XLMRobertaModel:()=>XS,XLMRobertaPreTrainedModel:()=>YS,XLMWithLMHeadModel:()=>GS,XVectorOutput:()=>kS,YolosForObjectDetection:()=>rC,YolosModel:()=>nC,YolosObjectDetectionOutput:()=>iC,YolosPreTrainedModel:()=>tC,YoutuForCausalLM:()=>sC,YoutuModel:()=>oC,YoutuPreTrainedModel:()=>aC,ZayaForCausalLM:()=>uC,ZayaModel:()=>lC,ZayaPreTrainedModel:()=>cC});var Kv=class extends Z{},qv=class extends Kv{},Jv=class extends Kv{async _call(e){return new Y(await super._call(e))}},Yv=class extends Kv{async _call(e){return new P0(await super._call(e))}},Xv=class extends Kv{async _call(e){return new N0(await super._call(e))}},Zv=class extends Z{},Qv=class extends Zv{},$v=class extends Zv{},ey=class extends Z{},ty=class extends ey{},ny=class extends ey{},ry=class extends Z{},iy=class extends ry{},ay=class extends ry{},oy=class extends Z{},sy=class extends oy{},cy=class extends oy{},ly=class extends Z{},uy=class extends ly{},dy=class extends ly{},fy=class extends ly{async _call(e){return new Y(await super._call(e))}},py=class extends Z{},my=class extends py{},hy=class extends py{async _call(e){return new Y(await super._call(e))}},gy=class extends Z{},_y=class extends gy{},vy=class extends gy{async _call(e){return new N0(await super._call(e))}},yy=class extends gy{async _call(e){return new Y(await super._call(e))}},by=class extends gy{async _call(e){return new M0(await super._call(e))}},xy=class extends gy{async _call(e){return new P0(await super._call(e))}},Sy=class extends Z{},Cy=class extends Sy{},wy=class extends Sy{},Ty=class extends Z{},Ey=class extends Ty{},Dy=class extends Ty{},Oy=class extends Z{},ky=class extends Oy{},Ay=class extends Oy{},jy=class extends Z{},My=class extends jy{},Ny=class extends jy{async _call(e){return new N0(await super._call(e))}},Py=class extends jy{async _call(e){return new Y(await super._call(e))}},Fy=class extends jy{async _call(e){return new M0(await super._call(e))}},Iy=class extends jy{async _call(e){return new P0(await super._call(e))}},Ly=4299n,Ry=6561n,zy=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},By=class extends zy{async encode_speech(e){return J(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,audio_features:u=null,audio_tokens:d=null,speaker_embeddings:f=null,speaker_features:p=null,...m}){let h;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof H)){let t=e.dims[0];if(r==null)r=cm([t],.5);else if(typeof r==`number`)r=cm([t],r);else if(Array.isArray(r))r=new H(`float32`,r,[t]);else throw Error(\"Unsupported type for `exaggeration` input\")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await J(this.sessions.embed_tokens,c),u&&d&&f&&p&&(h={audio_features:u,audio_tokens:d,speaker_embeddings:f,speaker_features:p}),h||n)h??=await this.encode_speech(n),a=U([h.audio_features,a],1),t=um([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=um([a.dims[0],n+e])}}return{...await Mv(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1),...h}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.position_ids=t.input_ids.dims[1]===1?new H(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==Ry)-1),[e.length,1]):new H(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=Ry?0:t++)}).flat(),t.input_ids.dims)),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),Rv(this,e,t,n)}async generate(e){let t=e.past_key_values,{sequences:n,audio_tokens:r,speaker_embeddings:i,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{let t=n.slice(null,[e.input_ids.dims[1],-1]),o=U([r,t,cm([t.dims[0],3],Ly)],1),{waveform:s}=await J(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:a,speaker_embeddings:i});return s}finally{o!==t&&await o?.dispose()}}},Vy=class extends Z{},Hy=class extends Vy{},Uy=class extends Z{},Wy=class extends Uy{},Gy=class extends Z{},Ky=class extends Gy{},qy=class extends Gy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Jy=class extends Gy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},Yy=class extends Z{},Xy=class extends Yy{},Zy=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Qy=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},$y=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},e2=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},t2=class extends Z{},n2=class extends t2{},r2=class extends t2{},i2=class extends Z{},a2=class extends i2{},o2=class extends i2{},s2=class extends Z{},c2=class extends s2{},l2=class extends s2{},u2=class extends Z{},d2=class extends u2{},f2=class extends u2{},p2=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},m2=class extends p2{},h2=class extends p2{},g2=class extends Z{},_2=class extends g2{},v2=class extends g2{async _call(e){return new N0(await super._call(e))}},y2=class extends g2{async _call(e){return new Y(await super._call(e))}},b2=class extends g2{async _call(e){return new M0(await super._call(e))}},x2=class extends g2{async _call(e){return new P0(await super._call(e))}},S2=class extends Z{},C2=class extends S2{},w2=class extends S2{async _call(e){return new Y(await super._call(e))}},T2=class extends Z{},E2=class extends T2{},D2=class extends T2{async _call(e){return new Y(await super._call(e))}},O2=class extends Z{},k2=class extends O2{},A2=class extends O2{async _call(e){return new j2(await super._call(e))}},j2=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},M2=class extends Z{},N2=class extends M2{},P2=class extends M2{async _call(e){return new j2(await super._call(e))}},F2=class extends A0{constructor({audio_codes:e}){super(),this.audio_codes=e}},I2=class extends A0{constructor({audio_values:e}){super(),this.audio_values=e}},L2=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},R2=class extends L2{async encode(e){return new F2(await J(this.sessions.encoder_model,e))}async decode(e){return new I2(await J(this.sessions.decoder_model,e))}},z2=class extends L2{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},B2=class extends L2{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},V2=class extends Z{},H2=class extends V2{},U2=class extends V2{async _call(e){return new N0(await super._call(e))}},W2=class extends V2{async _call(e){return new Y(await super._call(e))}},G2=class extends V2{async _call(e){return new M0(await super._call(e))}},K2=class extends V2{async _call(e){return new P0(await super._call(e))}},q2=class extends Z{},J2=class extends q2{},Y2=class extends q2{},X2=class extends Z{},Z2=class extends X2{},Q2=class extends X2{},$2=class extends Z{},e4=class extends $2{},t4=class extends $2{async _call(e){return new N0(await super._call(e))}},n4=class extends $2{async _call(e){return new Y(await super._call(e))}},r4=class extends $2{async _call(e){return new M0(await super._call(e))}},i4=class extends $2{async _call(e){return new P0(await super._call(e))}},a4=class extends Z{},o4=class extends a4{},s4=class extends Z{},c4=class extends s4{},l4=class extends s4{async _call(e){return new Y(await super._call(e))}},u4=class extends Z{},d4=class extends u4{},f4=class extends Z{},p4=class extends f4{},m4=class extends Z{},h4=class extends m4{},g4=class extends m4{async _call(e){return new v4(await super._call(e))}},_4=class extends m4{async _call(e){return new y4(await super._call(e))}},v4=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},y4=class extends A0{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},b4=class extends Z{},x4=class extends b4{},S4=class extends b4{async _call(e){return new Y(await super._call(e))}},C4=class extends Z{},w4=class extends C4{},T4=class extends C4{async _call(e){return new Y(await super._call(e))}},E4=class extends Z{},D4=class extends E4{},O4=class extends Z{},k4=class extends O4{},A4=class extends Z{},j4=class extends A4{},M4=class extends A4{async _call(e){return new Y(await super._call(e))}},N4=class extends A4{async _call(e){return new M0(await super._call(e))}},P4=class extends A4{async _call(e){return new P0(await super._call(e))}},F4=class extends A4{async _call(e){return new N0(await super._call(e))}},I4=class extends Z{},L4=class extends I4{},R4=class extends Z{},z4=class extends R4{},B4=class extends R4{},V4=class extends Z{},H4=class extends V4{},U4=class extends V4{async _call(e){return new Y(await super._call(e))}},W4=class extends Z{},G4=class extends W4{},K4=class extends W4{async _call(e){return new N0(await super._call(e))}},q4=class extends W4{async _call(e){return new Y(await super._call(e))}},J4=class extends W4{async _call(e){return new M0(await super._call(e))}},Y4=class extends W4{async _call(e){return new P0(await super._call(e))}},X4=class extends Z{},Z4=class extends X4{async forward({input_ids:e,attention_mask:t,pixel_values:n=null,image_position_ids:r=null,pixel_values_videos:i=null,video_position_ids:a=null,input_features:o=null,input_features_mask:s=null}){let c={image_features:n&&await this.encode_image({pixel_values:n,pixel_position_ids:r}),video_features:i&&await this.encode_image({pixel_values:i,pixel_position_ids:a}),audio_features:o&&await this.encode_audio({input_features:o,input_features_mask:s})},{image_token_id:l,video_token_id:u,audio_token_id:d,text_config:f}=this.config,p={image:l,video:u,audio:d};for(let[t,n]of Object.entries(p)){let r=`${t}_features`;c[r]??=new H(`float32`,/* @__PURE__ */ new Float32Array,[0,f.hidden_size]);let i=0;for(let t of e.data)Number(t)===n&&++i;if(i!==c[r].dims[0])throw Error(`The number of ${t} tokens (${i}) and ${t} features (${c[r].dims[0]}) do not match.`)}return await J(this.sessions.model,{input_ids:e,attention_mask:t,...c})}},Q4=class extends Z{},$4=class extends Q4{},e3=class extends Q4{},t3=class extends Z{},n3=class extends t3{},r3=class extends t3{async _call(e){return new N0(await super._call(e))}},i3=class extends t3{async _call(e){return new Y(await super._call(e))}},a3=class extends t3{async _call(e){return new M0(await super._call(e))}},o3=class extends Z{},s3=class extends o3{},c3=class extends o3{async _call(e){return new N0(await super._call(e))}},l3=class extends o3{async _call(e){return new Y(await super._call(e))}},u3=class extends o3{async _call(e){return new M0(await super._call(e))}},d3=class extends Z{},f3=class extends d3{},p3=class extends d3{},m3=class extends Z{},h3=class extends m3{},g3=class extends m3{},_3=class extends Z{},v3=class extends _3{},y3=class extends _3{},b3=class extends Z{},x3=class extends b3{},S3=class extends b3{async _call(e){return new Y(await super._call(e))}},C3=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},w3=class extends C3{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:U([t,e],1),attention_mask:U([um(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error(\"Either `input_ids` or `pixel_values` should be provided.\");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c,num_logits_to_keep:l=null}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await Tv(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error(\"Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.\");c=await this.encode_text({input_ids:r})}let u={inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:l};return await Mv(this,u,!0)}},T3=class extends Z{},E3=class extends T3{},D3=class extends T3{},O3=class extends Z{},k3=class extends O3{},A3=class extends O3{},j3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},M3=class extends j3{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Hv({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},N3=class extends M3{},P3=class extends M3{},F3=class extends Z{},I3=class extends F3{},L3=class extends M3{},R3=class extends L3{},z3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},B3=class extends z3{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,num_logits_to_keep:d=null,...f}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await J(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...f});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await J(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Mv(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u,num_logits_to_keep:d},!0)}_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Hv({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Uv({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},V3=class extends B3{},H3=class extends B3{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},U3=class extends H3{},W3=class extends Z{},G3=class extends W3{},K3=class extends W3{},q3=class extends Z{},J3=class extends q3{},Y3=class extends q3{},X3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},Z3=class extends X3{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=Iv(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>$f(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new H(`int64`,r,[3,...n]),new H(`int64`,i,[i.length,1])]}{let[t,n]=e.dims;return[new H(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),fm([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e<t.length;++e)if(t[e]==1){for(let t=0;t<3;++t)n[t][r][e]=a[t*i/3+s];++s}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a,video_token_id:o,vision_start_token_id:s}=this.config,c=e,l=c.reduce((e,t,n)=>(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;e<l.length;++e){let e=c.findIndex((e,t)=>t>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l<u?([g,_,v]=t[i.image_index],++i.image_index,--m,d=l):([g,_,v]=n[i.video_index],++i.video_index,--h,d=u);let[y,b,x]=[Number(g),Math.floor(Number(_)/r),Math.floor(Number(v)/r)],S=d-p,C=f.length>0?$f(f.at(-1))[0]+1:0;f.push(Array.from({length:3*S},(e,t)=>C+t%S));let ee=S+C,w=y*b*x,te=Array.from({length:w},(e,t)=>ee+Math.floor(t/(b*x))),ne=Array.from({length:w},(e,t)=>ee+Math.floor(t/x)%b),re=Array.from({length:w},(e,t)=>ee+t%x);f.push([te,ne,re].flat()),p=d+w}if(p<c.length){let e=f.length>0?$f(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=dm(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;e<i.length;++e){let t=i[e].filter((t,n)=>o[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push($f(r)[0]+1-i[e].length)}return[new H(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new H(`int64`,d,[d.length,1])]}return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await J(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Hv({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(jv(this,t,1n),!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(e<t.input_ids.dims[1]){let[n,r]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=r,t.position_ids=n.slice(null,null,[e,null]),t.input_ids=t.input_ids.slice(null,[e,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));let n=BigInt(e),r=t.rope_deltas.map(e=>n+e);t.position_ids=nm([r,r,r],0)}}return t}},Q3=class extends Z3{},$3=class extends Z3{image_grid_thw_name=`image_grid_thw`},e6=class extends Q3{image_grid_thw_name=`image_grid_thw`},t6=class extends $3{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=t<e.length?+(e[t]==a):-1;n!==c&&(o.push([c,s,t]),s=t,c=n)}let l=0,u=[];for(let[e,n,a]of o)if(e===0){let e=a-n;u.push(Array.from({length:3*e},(t,n)=>l+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},n6=class extends Z{},r6=class extends n6{},i6=class extends n6{},a6=class extends Z{},o6=class extends a6{},s6=class extends a6{},c6=class extends Z{},l6=class extends c6{},u6=class extends c6{},d6=class extends Z{},f6=class extends d6{},p6=class extends d6{},m6=class extends Z{},h6=class extends m6{},g6=class extends m6{},_6=class extends Z{},v6=class extends _6{},y6=class extends _6{},b6=class extends Z{},x6=class extends b6{},S6=class extends b6{},C6=class extends Z{},w6=class extends C6{},T6=class extends C6{},E6=class extends Z{},D6=class extends E6{},O6=class extends E6{},k6=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},A6=class extends k6{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Uv({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},j6=class extends A6{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},M6=class extends Z{},N6=class extends M6{},P6=class extends Z{},F6=class extends P6{},I6=class extends Z{},L6=class extends I6{},R6=class extends I6{},z6=class extends Z{},B6=class extends z6{},V6=class extends z6{async _call(e){return new Y(await super._call(e))}},H6=class extends Z{},U6=class extends H6{},W6=class extends H6{forward_params=[`input_ids`,`attention_mask`,`token_type_ids`,`past_key_values`];prepare_inputs_for_generation(e,t,n){let r=Rv(this,e,t,n);return r.token_type_ids=(r.past_key_values?pm:dm)(r.input_ids),r}},G6=class extends Z{},K6=class extends G6{},q6=class extends G6{async _call(e){return new F0(await super._call(e))}},J6=class extends G6{async _call(e){return new Y(await super._call(e))}},Y6=class extends G6{async _call(e){return new M0(await super._call(e))}},X6=class extends Z{},Z6=class extends G6{},Q6=class extends G6{async _call(e){return new F0(await super._call(e))}},$6=class extends G6{async _call(e){return new Y(await super._call(e))}},eb=class extends Z{},tb=class extends eb{},nb=class extends eb{},rb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},ib=class extends Z{},ab=class extends ib{},ob=class extends ib{async _call(e){return new Y(await super._call(e))}},sb=class extends Z{},cb=class extends sb{},lb=class extends sb{},ub=class extends Z{},db=class extends ub{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error(\"Either `input_ids` or `pixel_values` should be provided.\");if(t&&(e.input_ids=um([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=cm([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},fb=class extends ub{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},pb=class extends ub{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},mb=class extends Z{},hb=class extends mb{},gb=class extends mb{},_b=class extends M3{},vb=class extends Z{},yb=class extends vb{},bb=class extends vb{},xb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},Sb=class extends Z{},Cb=class extends Sb{},wb=class extends Sb{},Tb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`image_grid_thw`,`position_ids`,`past_key_values`]},Eb=class extends Z{},Db=class extends Eb{},Ob=class extends Eb{},kb=class extends Z{},Ab=class extends kb{},jb=class extends Z{},Mb=class extends jb{},Nb=class extends jb{},Pb=class extends Z{},Fb=class extends Pb{},Ib=class extends Pb{},Lb=class extends Z{},Rb=class extends Lb{},zb=class extends Lb{},Bb=class extends Z{},Vb=class extends Bb{},Hb=class extends Bb{},Ub=class extends Z{},Wb=class extends Ub{},Gb=class extends Ub{},Kb=class extends Ub{async _call(e){return new Y(await super._call(e))}},qb=class extends Ub{},Jb=class extends Z{},Yb=class extends Jb{},Xb=class extends Z{},Zb=class extends Xb{},Qb=class extends A0{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},$b=class extends Z{},e8=class extends $b{async _call(e){return new Qb(await super._call(e))}},t8=class extends A0{constructor({audio_codes:e}){super(),this.audio_codes=e}},n8=class extends A0{constructor({audio_values:e}){super(),this.audio_values=e}},r8=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},i8=class extends r8{async encode(e){return new t8(await J(this.sessions.encoder_model,e))}async decode(e){return new n8(await J(this.sessions.decoder_model,e))}},a8=class extends r8{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},o8=class extends r8{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},s8=class extends Z{},c8=class extends s8{},l8=class extends s8{},u8=class extends Z{},d8=class extends u8{},f8=class extends u8{},p8=class extends Z{},m8=class extends p8{},h8=class extends p8{},g8=class extends M3{},_8=class extends Z{},v8=class extends _8{},y8=class extends _8{},b8=class extends Z{},x8=class extends b8{},S8=class extends b8{async _call(e){return new N0(await super._call(e))}},C8=class extends b8{async _call(e){return new Y(await super._call(e))}},w8=class extends b8{async _call(e){return new P0(await super._call(e))}},T8=class extends Z{},E8=class extends T8{},D8=class extends T8{},O8=class extends Z{},k8=class extends O8{},A8=class extends O8{async _call(e){return new Y(await super._call(e))}},j8=class extends O8{},M8=class extends Z{},N8=class extends M8{},P8=class extends M8{async _call(e){return new Y(await super._call(e))}},F8=class extends M8{},I8=class extends Z{},L8=class extends I8{},R8=class extends I8{async _call(e){return new Y(await super._call(e))}},z8=class extends I8{},B8=class extends Z{},V8=class extends B8{},H8=class extends B8{async _call(e){return new Y(await super._call(e))}},U8=class extends B8{},W8=class extends Z{},G8=class extends W8{},K8=class extends W8{async _call(e){return new Y(await super._call(e))}},q8=class extends Z{},J8=class extends q8{},Y8=class extends q8{async _call(e){return new Y(await super._call(e))}},X8=class extends Z{},Z8=class extends X8{},Q8=class extends X8{async _call(e){return new N0(await super._call(e))}},$8=class extends X8{async _call(e){return new Y(await super._call(e))}},ex=class extends X8{async _call(e){return new M0(await super._call(e))}},tx=class extends Z{},nx=class extends tx{},rx=class extends tx{},ix=class extends Z{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},ax=class extends ix{},ox=class extends ix{},sx=class extends Z{},cx=class extends sx{},lx=class extends sx{async _call(e){return new N0(await super._call(e))}},ux=class extends sx{async _call(e){return new Y(await super._call(e))}},dx=class extends sx{async _call(e){return new M0(await super._call(e))}},fx=class extends sx{async _call(e){return new P0(await super._call(e))}},px=class extends Z{},mx=class extends px{},hx=class extends px{},gx=class extends Z{},_x=class extends gx{},vx=class extends gx{},yx=class extends Z{},bx=class extends yx{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await J(t,Xs(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await J(t,Xs({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await Mv(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find \"${a}\" generation head`);let o=await J(a,Xs(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return jv(this,t,1n),n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=U([t.input_ids,t.input_ids],0):(t.input_ids=U([t.input_ids,lm(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=U([t.attention_mask,lm(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=cm([0,0,3,384,384],1)),r&&(t.images_seq_mask=new H(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new H(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),{decoded_image:r}=await J(this.sessions.image_decode,{generated_tokens:n}),i=r.add_(1).mul_(127.5).clamp_(0,255).to(`uint8`),a=[];for(let e of i){let t=Mg.fromTensor(e);a.push(t)}return a}},xx=class extends Z{},Sx=class extends xx{},Cx=class extends xx{},wx=class extends Z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t<e.size;++t){if(e.data[t]==this.config.decoder.pad_token_id)continue;let o=t%n-Math.floor(t/n)%r;o>0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new H(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e<i.length;++e)for(let t=0;t<i[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),zv(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await J(this.sessions.encodec_decode,{audio_codes:n});return r}},Tx=class extends Z{},Ex=class extends Tx{},Dx=class extends Tx{},Ox=class extends Z{},kx=class extends Ox{},Ax=class extends Ox{},jx=class extends Z{},Mx=class extends jx{},Nx=class extends jx{async _call(e){return new N0(await super._call(e))}},Px=class extends jx{async _call(e){return new Y(await super._call(e))}},Fx=class extends jx{async _call(e){return new M0(await super._call(e))}},Ix=class extends jx{async _call(e){return new P0(await super._call(e))}},Lx=class extends Z{},Rx=class extends Lx{},zx=class extends Z{},Bx=class extends zx{},Vx=class extends zx{},Hx=class extends Z{},Ux=class extends Hx{},Wx=class extends Hx{},Gx=class extends Z{},Kx=class extends Gx{},qx=class extends Gx{},Jx=class extends Z{},Yx=class extends Jx{},Xx=class extends Jx{},Zx=class extends Z{},Qx=class extends Zx{},$x=class extends Zx{async _call(e){return new Y(await super._call(e))}},e5=class extends Z{},t5=class extends e5{},n5=class extends e5{},r5=class extends Z{},i5=class extends r5{},a5=class extends r5{},o5=class extends Z{},s5=class extends o5{},c5=class extends o5{},l5=class extends Z{},u5=class extends l5{},d5=class extends l5{},f5=class extends M3{},p5=class extends Z{},m5=class extends p5{async _call(e){return new F0(await super._call(e))}},h5=class extends Z{},g5=class extends h5{},_5=class extends h5{},v5=class extends Z{},y5=class extends v5{},b5=class extends v5{},x5=class extends Z{},S5=class extends x5{},C5=class extends x5{},w5=class extends Z{},T5=class extends w5{},E5=class extends w5{},D5=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},O5=class extends D5{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,...u}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error(\"`image_sizes` must be provided when `pixel_values` is provided.\");({image_features:t}=await J(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else t=new H(`float32`,[],[0,this.config.normalized_config.hidden_size]);({inputs_embeds:a}=await J(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await Mv(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1)}},k5=class extends Z{},A5=class extends k5{},j5=class extends k5{async _call(e){return new Y(await super._call(e))}},M5=class extends Z{},N5=class extends M5{},P5=class extends M5{async _call(e){return new M0(await super._call(e))}},F5=class extends Z{},I5=class extends F5{},L5=class extends F5{},R5=class extends Z{},z5=class extends R5{},B5=class extends R5{},V5=class extends Z{},H5=class extends V5{},U5=class extends V5{},W5=class extends Z{},G5=class extends W5{},K5=class extends W5{},q5=class extends Z{},J5=class extends q5{},Y5=class extends q5{},X5=class extends $3{},Z5=class extends e6{},Q5=class extends X5{},$5=class extends Z5{},e7=class extends X5{},t7=class extends e7{},n7=class extends e7{},r7=class extends t7{},i7=class extends Z{},a7=class extends i7{},o7=class extends i7{async _call(e){return new Y(await super._call(e))}},s7=class extends Z{},c7=class extends s7{},l7=class extends s7{async _call(e){return new u7(await super._call(e))}},u7=class extends j2{},d7=class extends Z{},f7=class extends d7{},p7=class extends d7{async _call(e){return new N0(await super._call(e))}},m7=class extends d7{async _call(e){return new Y(await super._call(e))}},h7=class extends d7{async _call(e){return new M0(await super._call(e))}},g7=class extends d7{async _call(e){return new P0(await super._call(e))}},_7=class extends Z{},v7=class extends _7{},y7=class extends _7{async _call(e){return new N0(await super._call(e))}},b7=class extends _7{async _call(e){return new Y(await super._call(e))}},x7=class extends _7{async _call(e){return new M0(await super._call(e))}},S7=class extends _7{async _call(e){return new P0(await super._call(e))}},C7=class extends Z{},w7=class extends C7{},T7=class extends C7{async _call(e){return new E7(await super._call(e))}},E7=class extends j2{},D7=class extends A0{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},O7=class extends Z{},k7=class extends O7{async get_image_embeddings({pixel_values:e}){return await Tv(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=um(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 J(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new D7(await super._call(e))}},A7=class extends A0{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},j7=class extends Z{},M7=class extends j7{async get_image_embeddings({pixel_values:e}){return await Tv(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error(\"When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.\");let t=e.input_points.dims;e.input_labels??=um(t.slice(0,-1)),e.input_boxes??=cm([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=cm([t[0],t[1],0],-1n),e.input_points=cm([t[0],1,0,2],0)}else throw Error(\"At least one of `input_points` or `input_boxes` must be provided.\");let n=this.sessions.prompt_encoder_mask_decoder;return await J(n,Xs(e,n.inputNames))}async _call(e){return new A7(await super._call(e))}},N7=class extends M7{},P7=class extends M7{},F7=class extends Z{},I7=class extends F7{},L7=class extends F7{},R7=class extends F7{},z7=class extends Z{},B7=class extends z7{},V7=class extends z7{},H7=class extends z7{},U7=class extends Z{},W7=class extends U7{},G7=class extends U7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},K7=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},q7=class extends Z{},J7=class extends q7{},Y7=class extends q7{},X7=class extends rb{},Z7=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},Q7=class extends Z7{async encode(e){return await J(this.sessions.encoder_model,e)}async decode(e){return await J(this.sessions.decoder_model,e)}},$7=class extends Z7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},e9=class extends Z7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},t9=class extends Z{},n9=class extends t9{},r9=class extends t9{},i9=class extends Z{},a9=class extends i9{},o9=class extends i9{},s9=class extends i9{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:s,encoder_attention_mask:c}=await Tv(this,o),l=s.dims[1]/this.config.reduction_factor,u=Math.floor(l*i),d=Math.floor(l*r),f=this.config.num_mel_bins,p=[],m=null,h=null,g=0;for(;;){++g;let e=vv(!!h),r;r=h?h.output_sequence_out:new H(`float32`,new Float32Array(f),[1,1,f]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:s};Av(this,i,m),h=await J(this.sessions.decoder_model_merged,i),m=Dv(h,m);let{prob:a,spectrum:o}=h;if(p.push(o),g>=d&&(Array.from(a.data).filter(e=>e>=n).length>0||g>=u))break}let _=U(p),{waveform:v}=await J(a.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}},c9=class extends Z{main_input_name=`spectrogram`},l9=class extends Z{},u9=class extends l9{},d9=class extends l9{async _call(e){return new N0(await super._call(e))}},f9=class extends l9{async _call(e){return new Y(await super._call(e))}},p9=class extends l9{async _call(e){return new P0(await super._call(e))}},m9=class extends Z{},h9=class extends m9{},g9=class extends m9{},_9=class extends Z{},v9=class extends _9{},y9=class extends _9{},b9=class extends Z{},x9=class extends b9{},S9=class extends Z{},C9=class extends S9{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await J(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;e<g;++e)_.fill(1n,e*h,e*h+m[e]);let v=new H(`int64`,_,[g,h]),y=c*o,b=y*h,x=mm([g,y,h]),S=x.data;for(let e=0;e<g;++e)if(m[e]!==h)for(let t=0;t<y;++t)S.fill(0,e*b+t*h+m[e],e*b+(t+1)*h);let C=cm([g],r);for(let e=0;e<r;++e){let r=cm([g],e);({denoised_latents:x}=await J(this.sessions.latent_denoiser,{style:n,noisy_latents:x,latent_mask:v,encoder_outputs:l,attention_mask:t,timestep:r,num_inference_steps:C}))}let{waveform:ee}=await J(this.sessions.voice_decoder,{latents:x});return{waveform:ee,durations:d}}},w9=class extends Z{},T9=class extends w9{},E9=class extends w9{async _call(e){return new Y(await super._call(e))}},D9=class extends w9{},O9=class extends Z{},k9=class extends O9{},A9=class extends O9{},j9=class extends Z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},M9=class extends j9{},N9=class extends j9{},P9=class extends Z{},F9=class extends P9{},I9=class extends P9{async _call(e){return new L9(await super._call(e))}},L9=class extends v4{},R9=class extends Z{},z9=class extends R9{},B9=class extends Z{},V9=class extends B9{},H9=class extends B9{async _call(e){return new F0(await super._call(e))}},U9=class extends B9{async _call(e){return new Y(await super._call(e))}},W9=class extends Z{},G9=class extends W9{},K9=class extends W9{async _call(e){return new F0(await super._call(e))}},q9=class extends W9{async _call(e){return new Y(await super._call(e))}},J9=class extends W9{async _call(e){return new M0(await super._call(e))}},Y9=class extends Z{},X9=class extends Y9{},Z9=class extends Y9{},Q9=class extends Z{main_input_name=`pixel_values`;forward_params=[`pixel_values`,`decoder_input_ids`,`encoder_hidden_states`,`past_key_values`]},$9=class extends Z{},eS=class extends $9{},tS=class extends $9{async _call(e){return new Y(await super._call(e))}},nS=class extends Z{},rS=class extends nS{},iS=class extends Z{},aS=class extends iS{},oS=class extends iS{async _call(e){return new Y(await super._call(e))}},sS=class extends Z{},cS=class extends sS{async _call(e){return new R0(await super._call(e))}},lS=class extends Z{},uS=class extends lS{},dS=class extends A0{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},fS=class extends Z{},pS=class extends fS{async _call(e){return new dS(await super._call(e))}},mS=class extends A6{},hS=2,gS=1,_S=/* @__PURE__ */ new WeakMap;function vS(e,t){let{text_config:n,audio_config:r}=e.config,i=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=r,s=a+o,c=new lv,l=v0(r),u={batch_size:1},d=`float32`;for(let e of i.inputMetadata){if(e.name===`past_padding_cache`){d=e.type;continue}if(!l.has(e.name))continue;let t=kv(e.shape,u),n=t.reduce((e,t)=>e*t,1),r=Up[e.type];c[e.name]=new H(e.type,new r(n),t)}let f=Up[d],p=new H(d,new f(s*hS),[1,s,hS]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:m,text_hidden_size:n.hidden_size}}async function yS(e,t){let n=t.dims[2],r=Math.floor((gS+n-3)/2)+1,i=new H(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=um([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await J(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,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=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function bS(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let t=await e.chunks_iter.next();if(t.done){e.stream_exhausted=!0;break}let n=await yS(e,t.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function xS(e,t,n){if(e.audio_embed_queue.length===0)return;let r=t.data,i=0,a=n;for(;a>0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n<o*e.text_hidden_size;++n)r[i*e.text_hidden_size+n]+=t.data[s+n];i+=o,a-=o,e.audio_queue_offset+=o,e.audio_queue_offset>=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var SS=class extends tv{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)}},CS=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},wS=class extends CS{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=_S.get(this);i&&await bS(i,i.audio_consumed+r);let{inputs_embeds:a}=await J(this.sessions.embed_tokens,{input_ids:e});i&&xS(i,a,r);let o={inputs_embeds:a,...n};Av(this,o,t);let s=this.sessions.decoder_model_merged;return await J(s,Xs(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=vS(this,e);_S.set(this,r);let i=new nv;i.push(new SS(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),_S.delete(this)}}},TS=class extends Z{},ES=class extends TS{},DS=class extends TS{async _call(e){return new F0(await super._call(e))}},OS=class extends TS{async _call(e){return new Y(await super._call(e))}},kS=class extends A0{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},AS=class extends Z{},jS=class extends AS{},MS=class extends AS{async _call(e){return new F0(await super._call(e))}},NS=class extends AS{async _call(e){return new Y(await super._call(e))}},PS=class extends AS{async _call(e){return new kS(await super._call(e))}},FS=class extends AS{async _call(e){return new M0(await super._call(e))}},IS=class extends Z{},LS=class extends IS{},RS=class extends ev{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},zS=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},BS=class extends zS{},VS=class extends zS{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,RS)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(N.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${vh(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error(\"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\");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&&(N.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\"),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof H?vm(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new V0,n.push(new K0(t,a))),t.begin_suppress_tokens&&(n??=new V0,n.push(new G0(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error(\"Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\");t.task===`translate`&&N.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;d<l;){let e=Math.min(d+u,l),m=c.slice(null,null,[d,e]),h,g=m.dims[2];if(g<u){let e=c.dims[1],t=new Float32Array(e*u),n=m.data;for(let r=0;r<e;++r)t.set(n.subarray(r*g,(r+1)*g),r*u);h=new H(`float32`,t,[1,e,u])}else h=m;if(n)for(let e of n)`begin_index`in e&&(e.begin_index=r.length);let _=await super.generate({inputs:h,generation_config:t,logits_processor:n,decoder_input_ids:r,...i}),v=(s?_.sequences:_)[0].tolist().map(Number).slice(r.length),y;if(s){_.token_timestamps=this._extract_token_timestamps(_,t.alignment_heads,Math.floor((e-d)/2),.02,r.length);let n=d/2*.02;y=_.token_timestamps[0].tolist().slice(r.length).map(e=>e+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],S=[];for(let e=0;e<v.length-1;++e)b[e]&&b[e+1]&&S.push(e+1);let C,ee=v.length;if(S.length>0){if(x)C=e-d;else{let e=S.at(-1);C=(v[e-1]-a)*2,ee=e}}else C=e-d;let w=Math.floor(d/2),te=a+1500;for(let e=0;e<ee;++e)v[e]>=a&&(v[e]=Math.min(v[e]+w,te));f.push(...v.slice(0,ee)),y&&p.push(...y.slice(0,ee)),d+=C}f.push(o);let m=[...r,...f];if(s){let e=new H(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new H(`float32`,new Float32Array(t),[1,t.length])}}return new H(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error(\"Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.\");n??N.warn(\"`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\");let a=this.config.median_filter_width;a===void 0&&(N.warn(\"Model config has no `median_filter_width`, using default value of 7.\"),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>U(o.map(e=>e[t]),2)),c=nm(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).permute(1,0,2,3),[l,u]=im(c,-2,0,!0),d=c.clone();for(let e=0;e<d.dims[0];++e){let t=d[e];for(let n=0;n<t.dims[0];++n){let r=t[n],i=l[e][n][0].data,o=u[e][n][0].data;for(let e=0;e<r.dims[0];++e){let t=r[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-o[e])/i[e];t.set(ip(t,a))}}}let f=[am(i>0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new H(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;e<p[0];++e){let[t,n]=sp(f[e].neg().squeeze_(0).tolist()),a=qs([1],Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e<a.length;++e)a[e]&&o.push(n[e]*r);let s=Array(i).fill(0);s.push(...o),o.length>0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},HS=class extends VS{},US=class extends Z{},WS=class extends US{},GS=class extends US{async _call(e){return new N0(await super._call(e))}},KS=class extends US{async _call(e){return new Y(await super._call(e))}},qS=class extends US{async _call(e){return new M0(await super._call(e))}},JS=class extends US{async _call(e){return new P0(await super._call(e))}},YS=class extends Z{},XS=class extends YS{},ZS=class extends YS{async _call(e){return new N0(await super._call(e))}},QS=class extends YS{async _call(e){return new Y(await super._call(e))}},$S=class extends YS{async _call(e){return new M0(await super._call(e))}},eC=class extends YS{async _call(e){return new P0(await super._call(e))}},tC=class extends Z{},nC=class extends tC{},rC=class extends tC{async _call(e){return new iC(await super._call(e))}},iC=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},aC=class extends Z{},oC=class extends aC{},sC=class extends aC{},cC=class extends Z{},lC=class extends cC{},uC=class extends cC{},dC=/* @__PURE__ */ new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`],[`openai_privacy_filter`,`OpenAIPrivacyFilterModel`],[`embedding_gemma2`,`EmbeddingGemma2Model`]]),fC=/* @__PURE__ */ new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),pC=/* @__PURE__ */ new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),mC=/* @__PURE__ */ new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`lfm3`,`Lfm3Model`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`deepseek_v4`,`DeepseekV4Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`],[`zaya`,`ZayaModel`],[`hrm_text`,`HrmTextModel`]]),hC=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),gC=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),_C=/* @__PURE__ */ new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),vC=/* @__PURE__ */ 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`]]),yC=/* @__PURE__ */ new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`],[`openai_privacy_filter`,`OpenAIPrivacyFilterForTokenClassification`]]),bC=/* @__PURE__ */ new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),xC=/* @__PURE__ */ new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`lfm3`,`Lfm3ForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`deepseek_v4`,`DeepseekV4ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`zaya`,`ZayaForCausalLM`],[`hrm_text`,`HrmTextForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),SC=/* @__PURE__ */ new Map([[`multi_modality`,`MultiModalityCausalLM`]]),CC=/* @__PURE__ */ 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`]]),wC=/* @__PURE__ */ 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`]]),TC=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),EC=/* @__PURE__ */ new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`lfm3_vl`,`Lfm3VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),DC=/* @__PURE__ */ new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),OC=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),kC=/* @__PURE__ */ 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`]]),AC=/* @__PURE__ */ new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),jC=/* @__PURE__ */ new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),MC=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),NC=/* @__PURE__ */ new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),PC=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),FC=/* @__PURE__ */ new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),IC=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),LC=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),RC=/* @__PURE__ */ new Map([[`wavlm`,`WavLMForXVector`]]),zC=/* @__PURE__ */ new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),BC=/* @__PURE__ */ new Map([[`vitmatte`,`VitMatteForImageMatting`]]),VC=/* @__PURE__ */ new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),HC=/* @__PURE__ */ new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),UC=/* @__PURE__ */ new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),WC=/* @__PURE__ */ new Map([[`sapiens`,`SapiensForNormalEstimation`]]),GC=/* @__PURE__ */ new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),KC=/* @__PURE__ */ new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),qC=[[dC,X.EncoderOnly],[fC,X.EncoderDecoder],[mC,X.DecoderOnlyWithoutHead],[pC,X.AutoEncoder],[vC,X.EncoderOnly],[yC,X.EncoderOnly],[bC,X.Seq2Seq],[hC,X.Seq2Seq],[xC,X.DecoderOnly],[SC,X.MultiModality],[CC,X.EncoderOnly],[wC,X.EncoderOnly],[TC,X.Vision2Seq],[EC,X.ImageTextToText],[DC,X.AudioTextToText],[kC,X.EncoderOnly],[MC,X.EncoderOnly],[PC,X.EncoderOnly],[NC,X.EncoderOnly],[BC,X.EncoderOnly],[VC,X.EncoderOnly],[HC,X.EncoderOnly],[UC,X.EncoderOnly],[WC,X.EncoderOnly],[GC,X.EncoderOnly],[AC,X.EncoderOnly],[jC,X.EncoderOnly],[FC,X.MaskGeneration],[IC,X.EncoderOnly],[LC,X.EncoderOnly],[gC,X.Seq2Seq],[_C,X.EncoderOnly],[RC,X.EncoderOnly],[zC,X.EncoderOnly],[KC,X.EncoderOnly]];for(let[e,t]of qC)for(let n of e.values()){xv.set(n,t);let e=Gv[n];Cv.set(e,n),Sv.set(n,e)}var JC=[[`MusicgenForConditionalGeneration`,wx,X.Musicgen],[`Phi3VForCausalLM`,O5,X.Phi3V],[`CLIPTextModelWithProjection`,Qy,X.EncoderOnly],[`SiglipTextModel`,G7,X.EncoderOnly],[`JinaCLIPTextModel`,fb,X.EncoderOnly],[`ClapTextModelWithProjection`,qy,X.EncoderOnly],[`ClapAudioModelWithProjection`,Jy,X.EncoderOnly],[`DacEncoderModel`,z2,X.EncoderOnly],[`DacDecoderModel`,B2,X.EncoderOnly],[`MimiEncoderModel`,a8,X.EncoderOnly],[`MimiDecoderModel`,o8,X.EncoderOnly],[`SnacEncoderModel`,$7,X.EncoderOnly],[`SnacDecoderModel`,e9,X.EncoderOnly],[`Gemma3nForConditionalGeneration`,B3,X.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,H3,X.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,C9,X.Supertonic],[`ChatterboxModel`,By,X.Chatterbox],[`EmbeddingGemma2Model`,Z4,X.MultimodalEncoder],[`VoxtralRealtimeForConditionalGeneration`,wS,X.VoxtralRealtime]];for(let[e,t,n]of JC)xv.set(e,n),Cv.set(t,e),Sv.set(e,t);var YC=/* @__PURE__ */ new Map([[`modnet`,MC],[`birefnet`,MC],[`isnet`,MC],[`ben`,MC]]);for(let[e,t]of YC.entries())t.set(e,`PreTrainedModel`),xv.set(e,X.EncoderOnly),Sv.set(e,Z);var XC=new Set(YC.keys());xv.set(`PreTrainedModel`,X.EncoderOnly),Cv.set(Z,`PreTrainedModel`);var Q={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:vC,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:yC,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:gC,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:_C,MODEL_FOR_MASKED_LM_MAPPING_NAMES:CC,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:wC,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:kC,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:MC,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:NC,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:PC,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:AC,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:jC,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:FC,MODEL_FOR_CTC_MAPPING_NAMES:IC,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:LC,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:RC,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:zC,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:OC,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:BC,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:HC,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:UC,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:WC,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:GC,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:KC,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:EC,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:DC,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:bC,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:hC,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:xC,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:TC};gv(Q);var $=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await x0.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \"+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await Gv[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return XC.has(p)||N.warn(`Unknown model class \"${p}\", attempting to construct from base class.`),await Z.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},ZC=class extends ${static MODEL_CLASS_MAPPINGS=qC.map(e=>e[0]);static BASE_IF_FAIL=!0},QC=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},$C=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},ew=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},tw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},nw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},rw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},iw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},aw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},ow=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},sw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},cw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},lw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},uw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},dw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},fw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},pw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var mw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CTC_MAPPING_NAMES]},hw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var gw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var _w=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},vw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var yw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function bw(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>Mg.read(e)))}async function xw(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?Ih(e,t):e instanceof Float64Array?new Float32Array(e):e))}function Sw(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var Cw=class extends Vs{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},ww=class extends Cw{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new H(`float32`,Xf(e.data),e.dims),s=[];for(let e of r.logits){let n=await Yp(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},Tw=class extends Cw{async _call(e,{ignore_labels:t=[`O`],aggregation_strategy:n=`none`}={}){if(n!==`none`&&n!==`simple`)throw Error(`Invalid aggregation_strategy: \"${n}\". Must be one of \"none\" or \"simple\".`);let r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(i)).logits,o=this.model.config.id2label,s=[];for(let e=0;e<a.dims[0];++e){let r=i.input_ids[e].tolist(),c=a[e],l=[];for(let e=0;e<c.dims[0];++e){let n=c[e],i=$f(n.data)[1],a=o?o[i]:`LABEL_${i}`;if(t.includes(a))continue;let s=this.tokenizer.decode([r[e]],{skip_special_tokens:!0});if(s===``)continue;let u=Xf(n.data);l.push({entity:a,score:u[i],index:e,word:s})}s.push(n===`simple`?Dw(l,r,this.tokenizer):l)}return r?s:s[0]}};function Ew(e){let t=e[0];return e[1]===`-`&&(t===`B`||t===`I`||t===`E`||t===`S`)?[t,e.slice(2)]:[`I`,e]}function Dw(e,t,n){let r=[],i=null;for(let t=0;t<e.length;++t){let[n,a]=Ew(e[t].entity);i===a&&n!==`B`&&n!==`S`?(r[r.length-1].end=t+1,n===`E`&&(i=null)):(r.push({tag:a,start:t,end:t+1}),i=n===`S`?null:a)}return r.map(({tag:r,start:i,end:a})=>{let o=0,s=[];for(let n=i;n<a;++n)o+=e[n].score,s.push(t[e[n].index]);return{entity_group:r,score:o/(a-i),word:n.decode(s,{skip_special_tokens:!0})}})}var Ow=class extends Cw{async _call(e,t,{top_k:n=1}={}){let r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),i=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(r),s=r.input_ids.tolist(),c=r.attention_mask.tolist(),{all_special_ids:l,sep_token_id:u}=this.tokenizer,d=[];for(let e=0;e<a.dims[0];++e){let t=s[e],r=t.findIndex(e=>e==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;n<i.length;++n)(c[e]==0||n<=r||l.findIndex(e=>e==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=Xf(i).map((e,t)=>[e,t]),m=Xf(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=Js(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;e<Math.min(h.length,n);++e){let[n,r,i]=h[e],a=t.slice(n,r+1),o=this.tokenizer.decode(a,{skip_special_tokens:!0});g.push({answer:o,score:i})}n===1?d.push(...g):d.push(g)}return i?d:d[0]}},kw=class extends Cw{async _call(e,{top_k:t=5}={}){let{mask_token_id:n,mask_token:r}=this.tokenizer,i=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(i),o=[],s=i.input_ids.tolist();for(let e=0;e<s.length;++e){let i=s[e],c=i.findIndex(e=>e==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await Yp(new H(`float32`,Xf(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Aw=class extends Cw{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},jw=class extends Aw{_key=`summary_text`},Mw=class extends Aw{_key=`translation_text`};function Nw(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var Pw=class extends Cw{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:n,return_full_text:r,tools:i,documents:a,chat_template:o,tokenizer_encode_kwargs:s,...c}=t,l=!1,u=!1,d=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,f=s,p;if(typeof e==`string`)p=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))l=!0,p=e;else{if(Nw(e))e=[e];else if(Array.isArray(e)&&e.every(Nw))l=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);u=!0;let t={tokenize:!1,add_generation_prompt:!0,...Xs({tools:i,documents:a,chat_template:o},[`tools`,`documents`,`chat_template`]),...f};p=e.map(e=>this.tokenizer.apply_chat_template(e,t)),d=!1,f=void 0}let m=u?!1:r??!0;this.tokenizer.padding_side=`left`;let h=this.tokenizer(p,{add_special_tokens:d,padding:!0,truncation:!0,...f}),g=await this.model.generate({...h,...this._default_generation_config,...c}),_=this.tokenizer.batch_decode(g,{skip_special_tokens:!0}),v;!m&&h.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let y=Array.from({length:e.length},e=>[]);for(let t=0;t<_.length;++t){let n=Math.floor(t/g.dims[0]*e.length);v&&(_[t]=_[t].slice(v[n])),y[n].push({generated_text:u?[...e[n],{role:`assistant`,content:_[t]}]:_[t]})}return!l&&y.length===1?y[0]:y}},Fw=class extends Cw{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(N.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&&(N.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>Xf(e)[1]):Xf(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},Iw=class extends Cw{async _call(e,{top_k:t=5}={}){let n=await xw(e,this.processor.feature_extractor.config.sampling_rate),r=this.model.config.id2label,i=[];for(let e of n){let n=await this.processor(e),a=(await this.model(n)).logits[0],o=await Yp(new H(`float32`,Xf(a.data),a.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:r?r[e]:`LABEL_${e}`,score:s[t]}));i.push(c)}return Array.isArray(e)?i:i[0]}},Lw=class extends Cw{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await xw(e,o),c=[];for(let e of s){let n=await this.processor(e),r=Xf((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},Rw=class extends Cw{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&N.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".'),t.task&&N.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');let n=!Array.isArray(e),r=await xw(n?[e]:e,this.processor.feature_extractor.config.sampling_rate),i=[];for(let e of r){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push($f(e.data)[1]);let a=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();i.push({text:a})}return n?i[0]:i}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await xw(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>ap(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await xw(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.tokenizer.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=await xw(r,i.config.sampling_rate),o=t.language??`en`,s=this.processor.get_decoder_prompt_ids(o),c=[];for(let e of a){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:s,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,o);c.push({text:a})}return n?c[0]:c}},zw=class extends Cw{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await M.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new H(`float32`,e,[e.length]);else if(!(e instanceof H))throw Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e<a;++e){let t=s?Math.min(Math.ceil(s[e]),o):o,r=e*o;c.push(new tg(i.slice(r,r+t),n))}return Array.isArray(e)?c:c[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type===`supertonic`?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:n,speed:r}){if(!t)throw Error(`Speaker embeddings must be provided for Supertonic models.`);let{sampling_rate:i,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),s=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,s),t=t.view(s,-1,a);let{waveform:c,durations:l}=await this.model.generate_speech({...o,style:t,num_inference_steps:n,speed:r});return this._postprocess_waveform(e,c,i,l)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return this._postprocess_waveform(e,n,r)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||=(N.info(`No vocoder specified, using default HifiGan vocoder.`),await ZC.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:`fp32`}));let{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),r=n.dims[0];t=await this._prepare_speaker_embeddings(t,r),t=t.view(r,-1);let{waveform:i}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,i,a)}},Bw=class extends Cw{async _call(e,t={}){let n=Array.isArray(e),r=await bw(e),{pixel_values:i}=await this.processor(r),a=[];for(let e of i){e.dims=[1,...e.dims];let n=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},Vw=class extends Cw{async _call(e,{top_k:t=5}={}){let n=await bw(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await Yp(new H(`float32`,Xf(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},Hw={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},Uw=class extends Cw{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=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 s=await bw(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=Hw[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(Hw))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=f[d[0]];for(let t=0;t<c.length;++t){let n=c[t],r=e[t];r.data.some(e=>e<-1e-5||e>1.00001)&&r.sigmoid_();let i=await Mg.fromTensor(r.mul_(255).to(`uint8`)).resize(n[1],n[0]);h.push({label:null,score:null,mask:i})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n<o.data.length;++n)o.data[n]===t.id&&(e[n]=255);let n=new Mg(e,o.dims[1],o.dims[0],1);h.push({score:t.score,label:m[t.label_id],mask:n})}}else if(o===`semantic`){let{segmentation:e,labels:t}=p(f,a??c)[0];for(let n of t){let t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r)e.data[r]===n&&(t[r]=255);let r=new Mg(t,e.dims[1],e.dims[0],1);h.push({score:null,label:m[n],mask:r})}}else throw Error(`Subtask ${o} not supported.`);return h}};Object.freeze({\"text-classification\":{pipeline:ww,model:QC,default:{model:`Xenova/distilbert-base-uncased-finetuned-sst-2-english`},type:`text`},\"token-classification\":{pipeline:Tw,model:$C,default:{model:`Xenova/bert-base-multilingual-cased-ner-hrl`},type:`text`},\"question-answering\":{pipeline:Ow,model:ow,default:{model:`Xenova/distilbert-base-cased-distilled-squad`},type:`text`},\"fill-mask\":{pipeline:kw,model:aw,default:{model:`onnx-community/ettin-encoder-32m-ONNX`,dtype:`fp32`},type:`text`},summarization:{pipeline:jw,model:ew,default:{model:`Xenova/distilbart-cnn-6-6`},type:`text`},translation:{pipeline:Mw,model:ew,default:{model:`Xenova/t5-small`},type:`text`},\"text2text-generation\":{pipeline:Aw,model:ew,default:{model:`Xenova/flan-t5-small`},type:`text`},\"text-generation\":{pipeline:Pw,model:iw,default:{model:`onnx-community/Qwen3-0.6B-ONNX`,dtype:`q4`},type:`text`},\"zero-shot-classification\":{pipeline:Fw,model:QC,default:{model:`Xenova/distilbert-base-uncased-mnli`},type:`text`},\"audio-classification\":{pipeline:Iw,model:hw,default:{model:`Xenova/wav2vec2-base-superb-ks`},type:`audio`},\"zero-shot-audio-classification\":{pipeline:Lw,model:ZC,default:{model:`Xenova/clap-htsat-unfused`},type:`multimodal`},\"automatic-speech-recognition\":{pipeline:Rw,model:[tw,mw],default:{model:`Xenova/whisper-tiny.en`},type:`multimodal`},\"text-to-audio\":{pipeline:zw,model:[rw,nw],default:{model:`onnx-community/Supertonic-TTS-ONNX`,dtype:`fp32`},type:`text`},\"image-to-text\":{pipeline:Bw,model:sw,default:{model:`Xenova/vit-gpt2-image-captioning`},type:`multimodal`},\"image-classification\":{pipeline:Vw,model:cw,default:{model:`Xenova/vit-base-patch16-224`},type:`multimodal`},\"image-segmentation\":{pipeline:Uw,model:[lw,uw,dw],default:{model:`Xenova/detr-resnet-50-panoptic`},type:`multimodal`},\"background-removal\":{pipeline:class extends Uw{async _call(e,t={}){let n=await bw(e),r=await super._call(e,t),i=n.map((e,t)=>{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[lw,uw,dw],default:{model:`Xenova/modnet`},type:`image`},\"zero-shot-image-classification\":{pipeline:class extends Cw{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await bw(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type!==`siglip`||`max_length`,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>Xf(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:ZC,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},\"object-detection\":{pipeline:class extends Cw{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await bw(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:Sw(t,!n)})));return r?d:d[0]}},model:fw,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},\"zero-shot-object-detection\":{pipeline:class extends Cw{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await bw(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e<o.length;++e){let a=o[e],u=i?null:[[a.height,a.width]],d=c.pixel_values[e].unsqueeze_(0),f=await this.model({...s,pixel_values:d}),p;if(`post_process_grounded_object_detection`in this.processor){let e=this.processor.post_process_grounded_object_detection(f,s.input_ids,{box_threshold:n,text_threshold:n,target_sizes:u})[0];p=e.boxes.map((t,n)=>({score:e.scores[n],label:e.labels[n],box:Sw(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:Sw(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:pw,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},\"document-question-answering\":{pipeline:class extends Cw{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){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 r=(await bw(e))[0],{pixel_values:i}=await this.processor(r),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/<s_answer>(.*?)<\\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:gw,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},\"image-to-image\":{pipeline:class extends Cw{async _call(e){let t=await bw(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push(Mg.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:_w,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},\"depth-estimation\":{pipeline:class extends Cw{async _call(e){let t=await bw(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e<t.length;++e){let n=r[e],[a,o]=n.dims.slice(-2),[s,c]=t[e].size,l=(await qp(n.view(1,1,a,o),{size:[c,s],mode:`bilinear`})).view(c,s),u=l.min().item(),d=l.max().item(),f=l.sub(u).div_(d-u).mul_(255).to(`uint8`).unsqueeze(0),p=Mg.fromTensor(f);i.push({predicted_depth:l,depth:p})}return Array.isArray(e)?i:i[0]}},model:vw,default:{model:`onnx-community/depth-anything-v2-small`},type:`image`},\"feature-extraction\":{pipeline:class extends Cw{async _call(e,{pooling:t=`none`,normalize:n=!1,quantize:r=!1,precision:i=`binary`}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a),s=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case`none`:break;case`mean`:s=Qp(s,a.attention_mask);break;case`first_token`:case`cls`:s=s.slice(null,0);break;case`last_token`:case`eos`:s=s.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return n&&(s=s.normalize(2,-1)),r&&(s=hm(s,i)),s}},model:ZC,default:{model:`onnx-community/all-MiniLM-L6-v2-ONNX`,dtype:`fp32`},type:`text`},\"image-feature-extraction\":{pipeline:class extends Cw{async _call(e,{pool:t=null}={}){let n=await bw(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),a;if(t){if(!(`pooler_output`in i))throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}},model:[yw,ZC],default:{model:`onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX`,dtype:`fp32`},type:`image`}}),Object.freeze({\"sentiment-analysis\":`text-classification`,ner:`token-classification`,asr:`automatic-speech-recognition`,\"text-to-speech\":`text-to-audio`,embeddings:`feature-extraction`});var Ww=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}};j.IS_PROCESS_AVAILABLE,Object.keys(Vp);async function Gw({cacheName:e,url:t,size:n,name:r,onProgress:i}){let a=await caches.open(e),o=await a.match(t);if(!o){let e=await fetch(t,{credentials:`omit`});if(!e.ok||!e.body)throw Error(`Couldn't download ${r} (HTTP ${e.status}).`);let s=0,c=0,l=e.body.pipeThrough(new TransformStream({transform(e,t){s+=e.byteLength;let n=performance.now();n-c>=150&&(i(s),c=n),t.enqueue(e)},flush(){if(s!==n)throw Error(`The download for ${r} was incomplete.`)}}));if(await a.put(t,new Response(l)),o=await a.match(t),!o)throw Error(`The downloaded weights could not be read from browser storage.`)}let s=new Uint8Array(await o.arrayBuffer());if(s.byteLength!==n)throw await a.delete(t),Error(`The cached file for ${r} is incomplete. Try loading again.`);return i(n),s}let Kw=/^[\\w.-]+\\/[\\w.-]+$/,qw=/^[a-f0-9]{40}$/,Jw=/^[a-f0-9]{64}$/,Yw=/^(?!.*(?:^|\\/)\\.{1,2}(?:\\/|$))[\\w.@-]+(?:\\/[\\w.@-]+)*$/,Xw={\"litert-chat\":{task:`chat`},\"onnx-chat\":{task:`chat`},\"laya-choice\":{task:`classification`},\"janus-image\":{task:`image`},\"sd-turbo\":{task:`image`}},Zw=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`onnx/model_fp16.onnx`,`onnx/model_fp16.onnx_data`],Qw=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`processor_config.json`,`preprocessor_config.json`,`onnx/prepare_inputs_embeds_q4.onnx`,`onnx/language_model_q4f16.onnx`,`onnx/lm_head_fp16.onnx`,`onnx/gen_head_fp16.onnx`,`onnx/gen_img_embeds_fp16.onnx`,`onnx/image_decode.onnx`],$w=[`text_encoder/model.onnx`,`unet/model.onnx`,`vae_decoder/model.onnx`],eT=[`config.json`,`tokenizer.json`,`tokenizer_config.json`];function tT(e){let t=/^onnx\\/(model|decoder_model_merged)(?:_(q4f16|q4|quantized|fp16))?\\.onnx$/.exec(e);if(t)return{modelFile:t[1],dtype:t[2]===`quantized`?`q8`:t[2]??`fp32`}}function nT(e,t){let n=`${e}_data`,r=t.filter(e=>e===n||e.startsWith(`${n}_`)&&/^[1-9]\\d*$/.test(e.slice(n.length+1)));if(!r.length)return[];let i=r.map((e,t)=>t===0?n:`${n}_${t}`);return i.every(e=>r.includes(e))?i:void 0}function rT(e){return typeof e==`string`&&Kw.test(e)&&e.split(`/`).every(e=>Yw.test(e))}function iT(e){return typeof e==`string`&&Yw.test(e)}function aT(e,t,n){return`https://huggingface.co/${e}/resolve/${t}/${n.split(`/`).map(encodeURIComponent).join(`/`)}`}function oT(e){if(!e||e.version!==1||!Object.hasOwn(Xw,e.adapter)||!rT(e.repo)||typeof e.revision!=`string`||!qw.test(e.revision)||!Array.isArray(e.files)||e.files.length===0||e.files.length>24||!e.files.every(e=>e&&iT(e.path)&&Number.isSafeInteger(e.size)&&e.size>0&&(e.sha256===void 0||typeof e.sha256==`string`&&Jw.test(e.sha256))))return!1;let t=new Set(e.files.map(({path:e})=>e));if(t.size!==e.files.length)return!1;switch(e.adapter){case`litert-chat`:return e.files.length===1&&/\\.litertlm$/i.test(e.files[0].path)&&Jw.test(e.files[0].sha256);case`onnx-chat`:{let n=e.files[0].path;return!!(tT(n)&&eT.every(e=>t.has(e))&&nT(n,[...t]))}case`laya-choice`:return Zw.every(e=>t.has(e));case`janus-image`:return Qw.every(e=>t.has(e));case`sd-turbo`:return e.repo.toLowerCase()===`schmuell/sd-turbo-ort-web`&&$w.every(e=>t.has(e))}}let sT=[{key:`encoder`,path:`text_encoder/model.onnx`,dimensions:{batch_size:1}},{key:`unet`,path:`unet/model.onnx`,dimensions:{batch_size:1,num_channels:4,height:64,width:64,sequence_length:77}},{key:`decoder`,path:`vae_decoder/model.onnx`,dimensions:{batch_size:1,num_channels_latent:4,height_latent:64,width_latent:64}}],cT,lT=!1;function uT(e,t={}){self.postMessage({type:e,...t})}M.allowLocalModels=!1,M.backends.onnx.wasm.numThreads=1,w.wasm.numThreads=1,w.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/`,w.webgpu.powerPreference=`high-performance`;async function dT(e){let t=await G.from_pretrained(`Xenova/clip-vit-base-patch32`,{revision:`6b7c523703ae26e39be4b03774966f8571c7f523`});t.pad_token_id=0;let n={},r=0;for(let t of sT){let i=await Gw({cacheName:`browser-model-sdk-weights-v1`,url:aT(e.repo,e.revision,t.path),name:t.path,size:e.files.find(({path:e})=>e===t.path).size,onProgress:e=>uT(`load-progress`,{loaded:r+e})});r+=i.byteLength,uT(`load-progress`,{loaded:r,label:`Preparing ${t.key}`}),n[t.key]=await Pe.create(i,{executionProviders:[`webgpu`],freeDimensionOverrides:t.dimensions,enableMemPattern:!1,enableCpuMemArena:!1,extra:{session:{disable_prepacking:`1`,use_device_allocator_for_initializers:`1`,use_ort_model_bytes_directly:`1`,use_ort_model_bytes_for_initializers:`1`}}})}return{tokenizer:t,sessions:n}}function fT(e){let t=e>>>0;function n(){t=t+0x6d2b79f5>>>0;let e=Math.imul(t^t>>>15,t|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/2**32}let r=/* @__PURE__ */ new Float32Array(16384);for(let e=0;e<r.length;e++)r[e]=Math.sqrt(-2*Math.log(1-n()))*Math.cos(2*Math.PI*n());return r}async function pT(e,t){let{tokenizer:n,sessions:r}=cT,i=[1,4,64,64],a=n(e,{padding:`max_length`,truncation:!0,max_length:77,return_tensor:!1}),o=[];function s(e){return o.push(e),e}try{uT(`generate-progress`,{label:`Encoding prompt`,fraction:.15});let e=s(new Ae(`int32`,Int32Array.from(a.input_ids,Number),[1,77])),n=await r.encoder.run({input_ids:e});for(let e of Object.values(n))s(e);uT(`generate-progress`,{label:`Denoising image`,fraction:.35});let o=14.6146,c=fT(t),l=c.map(e=>e*o/Math.hypot(o,1)),u=s((await r.unet.run({sample:s(new Ae(`float32`,l,i)),timestep:s(new Ae(`int64`,BigInt64Array.of(999n),[1])),encoder_hidden_states:n.last_hidden_state})).out_sample).data,d=c.map((e,t)=>(e-u[t])*o/.18215);uT(`generate-progress`,{label:`Decoding pixels`,fraction:.8});let f=s((await r.decoder.run({latent_sample:s(new Ae(`float32`,d,i))})).sample),p=f.data,[,,m,h]=f.dims,g=m*h,_=new Uint8ClampedArray(g*4);for(let e=0;e<g;e++){for(let t=0;t<3;t++)_[e*4+t]=(p[t*g+e]+1)*127.5;_[e*4+3]=255}let v=new OffscreenCanvas(h,m);return v.getContext(`2d`).putImageData(new ImageData(_,h,m),0,0),{blob:await v.convertToBlob({type:`image/png`}),width:h,height:m}}finally{for(let e of o)e.dispose()}}async function mT(e){let t=/* @__PURE__ */ new Map,n=0,r={revision:e.revision,progress_callback(e){if(e.status!==`progress`)return;t.set(e.file,e.loaded);let r=performance.now();r-n<150||(n=r,uT(`load-progress`,{loaded:[...t.values()].reduce((e,t)=>e+t,0)}))}},{repo:i}=e;return{processor:await h0.from_pretrained(i,r),janus:await bx.from_pretrained(i,{...r,device:{prepare_inputs_embeds:`wasm`,language_model:`webgpu`,lm_head:`webgpu`,gen_head:`webgpu`,gen_img_embeds:`webgpu`,image_decode:`webgpu`},dtype:{prepare_inputs_embeds:`q4`,language_model:`q4f16`,lm_head:`fp16`,gen_head:`fp16`,gen_img_embeds:`fp16`,image_decode:`fp32`}})}}async function hT(e){let{processor:t,janus:n}=cT,r=await t([{role:`<|User|>`,content:e}],{chat_template:`text_to_image`}),i=t.num_image_tokens,a=-1;class o extends Ww{put(){a++,a>0&&(a%32==0||a===i)&&uT(`generate-progress`,{label:`Rendering image tokens · ${a} / ${i}`,fraction:a/i})}end(){uT(`generate-progress`,{label:`Decoding pixels`,fraction:.99})}}let[s]=await n.generate_images({...r,do_sample:!0,min_new_tokens:i,max_new_tokens:i,streamer:new o});return{blob:await s.toBlob(),width:s.width,height:s.height}}self.addEventListener(`message`,async({data:e})=>{if(!lT){lT=!0;try{if(e.type===`load`){let{registration:t}=e;if(!oT(t)||![`sd-turbo`,`janus-image`].includes(t.adapter))throw Error(`Choose a compatible image generation export.`);let n=t.adapter;cT={engine:n,...n===`sd-turbo`?await dT(t):await mT(t)},uT(`ready`)}else e.type===`generate`&&cT&&uT(`result`,cT.engine===`sd-turbo`?await pT(e.prompt,e.seed):await hT(e.prompt))}catch(t){uT(`error`,{message:t?.name===`QuotaExceededError`?`Browser storage is full. Free up site storage and try again.`:t?.message??String(t),during:e.type})}finally{lT=!1}}})})();", t = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", e], { type: "text/javascript;charset=utf-8" });
2
+ var e = "(function(){var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)},n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){\n/*!\n* ONNX Runtime Web v1.31.1\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\nif(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of \"`+e+`\" is not supported`)}),s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},l=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},u=e=>l(n({},`__esModule`,{value:!0}),e),d,f,p,m,h,g,_,v=s(()=>{\"use strict\";d=/* @__PURE__ */ new Map,f=[],p=/* @__PURE__ */ new WeakMap,m=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=d.get(e);if(r===void 0)d.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend \"${e}\" using priority ${n}`)}if(n>=0){let t=f.indexOf(e);t!==-1&&f.splice(t,1);for(let t=0;t<f.length;t++)if(d.get(f[t]).priority<=n){f.splice(t,0,e);return}f.push(e)}}else throw TypeError(`not a valid backend`)},h=async e=>{let t=d.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{if(!n){let n=t.backend,r=p.get(n);t.initPromise=r?r.then(async()=>n.init(e),async()=>n.init(e)):n.init(e),p.set(n,t.initPromise)}return await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},g=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?f:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await h(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider \"${e}\" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]},_=async()=>{let e=[];for(let t of f){if(typeof d.get(t).backend.createLoraAdapterHandler!=`function`)continue;let n=await h(t);if(typeof n!=`string`)return n;e.push({name:t,err:n})}let t=e.length===0?``:` ERR: ${e.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`;throw Error(`no available backend supports LoRA adapters.${t}`)}}),y=s(()=>{\"use strict\";v()}),b,x=s(()=>{\"use strict\";b=`1.31.1`}),S,C,ee=s(()=>{\"use strict\";x(),S=`warning`,C={wasm:{},webgl:{},webgpu:{},versions:{common:b},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},Object.defineProperty(C,\"logLevel\",{enumerable:!0})}),w,te=s(()=>{\"use strict\";ee(),w=C}),ne,re,ie,ae,oe,se,ce=s(()=>{\"use strict\";ee(),ne=(e,t)=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.timeStamp(`${e}::ORT::${t}`)},re=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\\r\\n|\\r|\\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ne(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},ie=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||re(`BEGIN`,e)},ae=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||re(`END`,e)},oe=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.time(`ORT::${e}`)},se=e=>{(typeof C.trace>`u`?!C.wasm.trace:!C.trace)||console.timeEnd(`ORT::${e}`)}}),le,ue=s(()=>{\"use strict\";v(),ce(),le=class e{constructor(e,t){this.backend=e,this.handler=t}static async create(t){if(ie(),typeof t!=`string`&&!(t instanceof Uint8Array))throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let n=await _(),r=await n.createLoraAdapterHandler(t);return ae(),new e(n,r)}async release(){return this.handler.dispose()}}}),T,de,fe=s(()=>{\"use strict\";T=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},de=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),pe,me,he,ge,_e,ve,ye=s(()=>{\"use strict\";ke(),pe=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new Oe(`float32`,u,[1,4,n,r]):new Oe(`float32`,u,[1,3,n,r])},me=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,pe(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(pe(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return pe(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},he=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new Oe({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ge=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Oe({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},_e=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new Oe({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},ve=(e,t,n)=>new Oe({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),be,xe,Se,Ce,we=s(()=>{\"use strict\";be=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),xe=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),Se=!1,Ce=()=>{if(!Se){Se=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(be.set(`int64`,BigInt64Array),xe.set(BigInt64Array,`int64`)),t&&(be.set(`uint64`,BigUint64Array),xe.set(BigUint64Array,`uint64`)),r?(be.set(`float16`,n),xe.set(n,`float16`)):be.set(`float16`,Uint16Array)}}}),Te,Ee,De=s(()=>{\"use strict\";ke(),Te=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},Ee=(e,t)=>{switch(e.location){case`cpu`:return new Oe(e.type,e.data,t);case`cpu-pinned`:return new Oe({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new Oe({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new Oe({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new Oe({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Oe,ke=s(()=>{\"use strict\";fe(),ye(),we(),De(),Oe=class{constructor(e,t,n){Ce();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=be.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=be.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=xe.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=Te(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return me(e,t)}static fromTexture(e,t){return he(e,t)}static fromGpuBuffer(e,t){return ge(e,t)}static fromMLTensor(e,t){return _e(e,t)}static fromPinnedBuffer(e,t,n){return ve(e,t,n)}toDataURL(e){return T(this,e)}toImageData(e){return de(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return Ee(this,e)}}}),Ae,je=s(()=>{\"use strict\";ke(),Ae=Oe}),Me,Ne=s(()=>{\"use strict\";v(),ue(),je(),ce(),Me=class e{constructor(e,t){this.handler=e,this.backend=t}async run(e,t,n){ie(),oe(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof Ae||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof Ae)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof Ae)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o;if(i.activeLoraAdapters!==void 0){if(!Array.isArray(i.activeLoraAdapters))throw TypeError(`'activeLoraAdapters' must be an array.`);o=i.activeLoraAdapters.map(e=>{if(!(e instanceof le))throw TypeError(`'activeLoraAdapters' must be an array of LoraAdapter objects.`);if(e.backend!==this.backend)throw Error(`LoRA adapter was created by a different backend than the session.`);return e.handler})}let s=await this.handler.run(e,r,i,o),c={};for(let e in s)if(Object.hasOwnProperty.call(s,e)){let t=s[e];c[e]=t instanceof Ae?t:new Ae(t.type,t.data,t.dims)}return se(`InferenceSession.run`),ae(),c}async release(){return this.handler.dispose()}static async create(t,n,r,i){ie(),oe(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await g(o),l=await s.createInferenceSessionHandler(a,c);return se(`InferenceSession.create`),ae(),new e(l,s)}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}}}),Pe,Fe=s(()=>{\"use strict\";Ne(),Pe=Me}),Ie,Le=s(()=>{\"use strict\";ue(),Ie=le}),Re=s(()=>{\"use strict\";}),ze=s(()=>{\"use strict\";}),Be=s(()=>{\"use strict\";}),Ve=s(()=>{\"use strict\";});c({},{InferenceSession:()=>Pe,LoraAdapter:()=>Ie,TRACE:()=>ne,TRACE_EVENT_BEGIN:()=>oe,TRACE_EVENT_END:()=>se,TRACE_FUNC_BEGIN:()=>ie,TRACE_FUNC_END:()=>ae,Tensor:()=>Ae,env:()=>w,registerBackend:()=>m});var He=s(()=>{\"use strict\";y(),te(),Fe(),Le(),je(),Re(),ze(),ce(),Be(),Ve()}),Ue=s(()=>{\"use strict\";}),We={};c(We,{default:()=>qe});var Ge,Ke,qe,Je=s(()=>{\"use strict\";Ln(),vt(),lt(),Ge=`ort-wasm-proxy-worker`,Ke=globalThis.self?.name===Ge,Ke&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:_t(n.wasm).then(()=>{bn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;xn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=Tn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;En(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Dn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Pn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},In([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Fn(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),qe=Ke?null:e=>new Worker(e??Qe,{type:`module`,name:Ge})}),Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot,st,ct,lt=s(()=>{\"use strict\";Ue(),Ye=typeof location>`u`?void 0:location.origin,Xe=self.location.href>`file:`&&self.location.href<`file;`,Ze=()=>Xe?new URL(new URL(`ort.webgpu.min.mjs`,self.location.href).href,Ye).href:self.location.href,Qe=Ze(),$e=()=>{if(Qe&&!Qe.startsWith(`blob:`))return Qe.substring(0,Qe.lastIndexOf(`/`)+1)},et=(e,t)=>{try{let n=t??Qe;return(n?new URL(e,n):new URL(e)).origin===Ye}catch{return!1}},tt=(e,t)=>{let n=t??Qe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},nt=(e,t)=>`${t??`./`}${e}`,rt=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},it=async e=>(await import(\n/*webpackIgnore:true*/\n/*@vite-ignore*/\ne)).default,at=(Je(),u(We)).default,ot=async()=>{if(!Qe)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(et(Qe))return[void 0,at()];let e=await rt(Qe);return[e,at(e)]},st=void 0,ct=async(e,t,n,r)=>{let i=st&&!(e||t);if(i){if(Qe)i=et(Qe)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,st];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??tt(r,t),a=n&&i&&!et(i,t),o=a?await rt(i):i??nt(r,t);return[a?o:void 0,await it(o)]}}}),ut,dt,ft,pt,mt,ht,gt,_t,E,vt=s(()=>{\"use strict\";lt(),dt=!1,ft=!1,pt=!1,mt=()=>{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}},ht=()=>{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}},gt=()=>{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}},_t=async e=>{if(dt)return Promise.resolve();if(ft)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(pt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ft=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!gt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!ht())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=mt();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, 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=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await ct(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=$e();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ft=!1,dt=!0,ut=t,e(),d&&URL.revokeObjectURL(d)},e=>{ft=!1,pt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},E=()=>{if(dt&&ut)return ut;throw Error(`WebAssembly is not initialized yet.`)}}),yt,bt,D,xt=s(()=>{\"use strict\";vt(),yt=(e,t)=>{let n=E(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},bt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)bt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},D=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),St,Ct=s(()=>{\"use strict\";vt(),xt(),St=(e,t)=>{let n=E(),r=0,i=[],a=e||{};try{if(e?.logSeverityLevel===void 0)a.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)a.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(a.terminate=!1);let o=0;e?.tag!==void 0&&(o=yt(e.tag,i)),r=n._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),r===0&&D(`Can't create run options.`),e?.extra!==void 0&&bt(e.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{let a=yt(e,i),o=yt(t,i);n._OrtAddRunConfigEntry(r,a,o)!==0&&D(`Can't set a run config entry: ${e} - ${t}.`)});for(let e of t)n._OrtRunOptionsAddActiveLoraAdapter(r,e)!==0&&D(`Can't add an active LoRA adapter.`);return[r,i]}catch(e){throw r!==0&&n._OrtReleaseRunOptions(r),i.forEach(e=>n._free(e)),e}}}),wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,Nt=s(()=>{\"use strict\";vt(),xt(),wt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},Tt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Et=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Dt=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);E()._OrtAddSessionConfigEntry(e,i,a)!==0&&D(`Can't set a session config entry: ${t} - ${n}.`)},Ot=(e,t,n,r)=>{let i=yt(t,r),a=yt(n,r);e.push([i,a])},kt=9,At=()=>{let e=E(),t=e.stackSave();try{let t=e.stackAlloc(e.PTR_SIZE),n=e.stackAlloc(e.PTR_SIZE),r=e._OrtGetEpDevices(t,n);if(r===kt)return;r!==0&&D(`Can't get execution provider devices.`);let i=Number(e.getValue(t,`*`)),a=Number(e.getValue(n,`*`)),o=/* @__PURE__ */ new Map;for(let t=0;t<a;t++){let n=Number(e.getValue(i+t*e.PTR_SIZE,`*`)),r=e.UTF8ToString(e._OrtEpDevice_EpName(n)),a=o.get(r);a?a.push(n):o.set(r,[n])}return o}finally{e.stackRestore(t)}},jt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[],o;switch(r){case`webnn`:if(r=`WEBNN`,Dt(e,`session.disable_quant_qdq`,`1`,n),Dt(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Dt(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e=At();if(e!==void 0&&(r=`WebGpuExecutionProvider`,o=e.get(r),o===void 0)){let t=[...e.keys()].join(`, `)||`(none)`;throw Error(`no execution provider device is registered for: ${r}. registered: ${t}.`)}let s;if(typeof i!=`string`){let e=i;if(e.device){if(typeof GPUDevice<`u`&&e.device instanceof GPUDevice)s=e.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:r}=t;if(typeof r==`boolean`&&r&&Ot(a,`enableGraphCapture`,`1`,n),typeof e.preferredLayout==`string`&&Ot(a,`preferredLayout`,e.preferredLayout,n),e.forceCpuNodeNames){let t=Array.isArray(e.forceCpuNodeNames)?e.forceCpuNodeNames:[e.forceCpuNodeNames];Ot(a,`forceCpuNodeNames`,t.join(`\n`),n)}e.validationMode&&Ot(a,`validationMode`,e.validationMode,n),typeof e.enableMatmulFp32Accumulation==`boolean`&&Ot(a,`enableMatmulFp32Accumulation`,e.enableMatmulFp32Accumulation?`1`:`0`,n);for(let t of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let r=e[t];if(r){if(r!==`disabled`&&r!==`lazyRelease`&&r!==`simple`&&r!==`bucket`)throw Error(`${t} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${r}`);Ot(a,t,r,n)}}}let c=E().webgpuRegisterDevice(s);if(c){let[e,t,r]=c;Ot(a,`deviceId`,e.toString(),n),Ot(a,`webgpuInstance`,t.toString(),n),Ot(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let s=a.length,c=0,l=0;if(s>0){c=E()._malloc(s*E().PTR_SIZE),n.push(c),l=E()._malloc(s*E().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)E().setValue(c+e*E().PTR_SIZE,a[e][0],`*`),E().setValue(l+e*E().PTR_SIZE,a[e][1],`*`)}let u;if(o!==void 0){let t=E()._malloc(E().PTR_SIZE);n.push(t),E().setValue(t,o[0],`*`),u=await E()._OrtAppendExecutionProviderV2(e,t,1,c,l,s)}else{let t=yt(r,n);u=await E()._OrtAppendExecutionProvider(e,t,c,l,s)}u!==0&&D(`Can't append execution provider: ${r}.`)}},Mt=async e=>{let t=E(),n=0,r=[],i=e||{};Et(i);try{let e=wt(i.graphOptimizationLevel??`all`),a=Tt(i.executionMode??`sequential`),o=typeof i.logId==`string`?yt(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?yt(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&D(`Can't create session options.`),i.executionProviders&&await jt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Dt(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=yt(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&D(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&bt(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{Dt(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&D(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Pt,Ft,It,Lt,Rt,zt,Bt,Vt,Ht=s(()=>{\"use strict\";Pt=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Ft=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},It=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Lt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Rt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},zt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Bt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Vt=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ut,Wt=s(()=>{\"use strict\";Ue(),Ut=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<0x40000000)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Gt,Kt=s(()=>{\"use strict\";Ht(),Gt=(e,t)=>new(Lt(t))(e)}),qt,Jt,Yt,Xt,Zt,Qt,$t,en=s(()=>{\"use strict\";Ht(),qt=[`V`,`I`,`W`,`E`,`F`],Jt=(e,t)=>{console.log(`[${qt[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Zt=(e,t)=>{Yt=e,Xt=t},Qt=(e,t)=>{let n=Rt(e);n>=Rt(Yt)&&Jt(n,typeof t==`function`?t():t)},$t=(...e)=>{Xt&&Qt(...e)}}),tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,pn=s(()=>{\"use strict\";Ht(),en(),tn=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),nn=(e,t)=>{if(t===`int32`)return e;let n=tn.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Lt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>0x7fffffff))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},rn=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},an=1,on=()=>an++,sn=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),cn=(e,t)=>{let n=tn.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},ln=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,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 cn(this.dataType,this.tensorShape)}destroy(){$t(`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),n=rn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},un=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,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=sn.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);$t(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==cn(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=nn(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}$t(`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?rn(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}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},dn=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=on();return this.tensorTrackersById.set(e,new un(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,n,r,i){$t(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){$t(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.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,n,r){let i=this.getMLContext(e),a=on(),o=new ln({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new un(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){$t(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}$t(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new ln({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},fn=(...e)=>new dn(...e)}),mn={};c(mn,{WebNNBackend:()=>_n});var hn,gn,_n,vn=s(()=>{\"use strict\";Ht(),vt(),Kt(),pn(),en(),hn=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),gn=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},_n=class{constructor(e){this.tensorManager=fn(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Zt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){$t(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){$t(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)$t(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>gn(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.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 n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){$t(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=hn.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){$t(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=hn.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!E().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);$t(`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 n=await this.tensorManager.download(e);return Gt(n,t)}}registerMLTensor(e,t,n,r){let i=hn.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return $t(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=hn.get(Pt(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln=s(()=>{\"use strict\";He(),Ct(),Nt(),Ht(),vt(),xt(),Wt(),yn=(e,t)=>{E()._OrtInit(e,t)!==0&&D(`Can't initialize onnxruntime.`)},bn=async e=>{yn(e.wasm.numThreads,Rt(e.logLevel))},xn=async(e,t)=>{E().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: \"${t}\"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: \"${r}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&E().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(vn(),u(mn)).WebNNBackend(e);E().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},Sn=/* @__PURE__ */ new Map,Cn=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&D(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},wn=(e,t)=>{let n=E(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&D(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Tn=e=>{let t=E(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},En=async(e,t)=>{let n,r,i=E();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Tn(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Mt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Ut(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&D(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=Cn(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=wn(a,t);e===0&&D(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:Ft(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=wn(a,n+e);r===0&&D(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:Ft(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&D(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Vt(e))}),Sn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&D(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&D(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&D(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},Dn=e=>{let t=E(),n=Sn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&D(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&D(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&D(`Can't release session.`),Sn.delete(e)},On=/* @__PURE__ */ new Map,kn=1,An=/* @__PURE__ */ new Map,jn=e=>{let t=E(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a LoRA adapter. failed to allocate a buffer of size ${e.byteLength}.`);try{t.HEAPU8.set(e,n);let r=t._OrtCreateLoraAdapter(n,e.byteLength);r===0&&D(`Can't create a LoRA adapter.`);let i=kn++;return On.set(i,r),i}finally{t._free(n)}},Mn=e=>{let t=E(),n=On.get(e);if(n===void 0)throw Error(`cannot release LoRA adapter. invalid adapter id: ${e}`);if(An.has(e))throw Error(`cannot release LoRA adapter. the adapter is used by a run in progress. adapter id: ${e}`);t._OrtReleaseLoraAdapter(n)!==0&&D(`Can't release LoRA adapter.`),On.delete(e)},Nn=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=E(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=It(Pt(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location \"gpu-buffer\" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=It(Pt(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);p=n(r,t,Pt(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,yt(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=Pt(l);m=It(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Pt(l),p,m,g,u.length,Vt(f));e===0&&D(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Pn=async(e,t,n,r,i,a,o=[])=>{let s=E(),c=s.PTR_SIZE,l=Sn.get(e);if(!l)throw Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],f=l[2],p=l[3],m=l[4],h=l[5],g=[];if(o.length>0){if(p)throw Error(`LoRA adapters are not supported for a session that uses IO binding, e.g. when an output is preferred to be on GPU, or when the WebNN execution provider produces an output.`);for(let e of o){let t=On.get(e);if(t===void 0)throw Error(`cannot run inference. invalid LoRA adapter id: ${e}`);g.push(t)}}let _=t.length,v=r.length,y=0,b=[],x=[],S=[],C=[],ee=[],w=s.stackSave(),te=s.stackAlloc(_*c),ne=s.stackAlloc(_*c),re=s.stackAlloc(v*c),ie=s.stackAlloc(v*c);try{for(let e of o)An.set(e,(An.get(e)??0)+1);[y,b]=St(a,g),oe(`wasm prepareInputOutputTensor`);for(let r=0;r<_;r++)await Nn(n[r],x,C,e,d[t[r]],t[r],m);for(let t=0;t<v;t++)await Nn(i[t],S,C,e,f[r[t]],_+r[t],m);se(`wasm prepareInputOutputTensor`);for(let e=0;e<_;e++)s.setValue(te+e*c,x[e],`*`),s.setValue(ne+e*c,d[t[e]],`*`);for(let e=0;e<v;e++)s.setValue(re+e*c,S[e],`*`),s.setValue(ie+e*c,f[r[e]],`*`);if(p&&!h){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:o}=p;if(d.length!==_)throw Error(`input count from feeds (${_}) is expected to be always equal to model's input count (${d.length}).`);oe(`wasm bindInputsOutputs`);for(let r=0;r<_;r++){let i=t[r];await s._OrtBindInput(n,d[i],x[r])!==0&&D(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<v;t++){let c=r[t];i[t]?.[3]?(ee.push(S[t]),s._OrtBindOutput(n,f[c],S[t],0)!==0&&D(`Can't bind pre-allocated output[${t}] for session=${e}.`)):s._OrtBindOutput(n,f[c],0,o[c])!==0&&D(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}se(`wasm bindInputsOutputs`),Sn.set(e,[u,d,f,p,m,!0])}s.jsepOnRunStart?.(u),s.webnnOnRunStart?.(u);let l;l=p?await s._OrtRunWithBinding(u,p.handle,v,re,y):await s._OrtRun(u,ne,te,_,ie,v,re,y),l!==0&&D(`failed to call OrtRun().`);let w=[],ae=[];oe(`wasm ProcessOutputTensor`);for(let t=0;t<v;t++){let n=Number(s.getValue(re+t*c,`*`));if(n===S[t]||ee.includes(S[t])){w.push(i[t]),n!==S[t]&&s._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`);continue}let a=s.stackSave(),o=s.stackAlloc(4*c),l=!1,u,d=0;try{s._OrtGetTensorData(n,o,o+c,o+2*c,o+3*c)!==0&&D(`Can't access output tensor data on index ${t}.`);let i=c===4?`i32`:`i64`,a=Number(s.getValue(o,i));d=s.getValue(o+c,`*`);let f=s.getValue(o+c*2,`*`),m=Number(s.getValue(o+c*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(s.getValue(f+e*c,i)));s._OrtFree(f)!==0&&D(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=Ft(a);let _=p?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=s.getValue(d+t*c,`*`),r=s.getValue(d+(t+1)*c,`*`),i=t===g-1?void 0:r-n;e.push(s.UTF8ToString(n,i))}w.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=s.webgpuGetBuffer;if(!t)throw Error(`preferredLocation \"gpu-buffer\" is not supported without using WebGPU.`);let r=t(d),i=It(a,g);if(i===void 0||!zt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{s.webgpuRegisterBuffer(r,e,d);let t=s.webgpuCreateDownloader(r,i,e);w.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Lt(u))(e)},dispose:()=>{s._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=s.webnnEnsureTensor,r=s.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation \"ml-tensor\" is not supported without using WebNN.`);if(It(a,g)===void 0||!Bt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation \"ml-tensor\" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,w.push([u,h,{mlTensor:i,download:s.webnnCreateMLTensorDownloader(d,u),dispose:()=>{s.webnnReleaseTensorId(d),s._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=s.webnnCreateMLTensorDownloader(d,u)(),t=w.length;l=!0,ae.push((async()=>{let r=[t,await e];return s.webnnReleaseTensorId(d),s._OrtReleaseTensor(n),r})()),w.push([u,h,[],`cpu`])}else{let e=new(Lt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s.HEAPU8.subarray(d,d+e.byteLength)),w.push([u,h,e,`cpu`])}}finally{s.stackRestore(a),u===`string`&&d&&s._free(d),l||s._OrtReleaseTensor(n)}}p&&!m&&(s._OrtClearBoundOutputs(p.handle)!==0&&D(`Can't clear bound outputs.`),Sn.set(e,[u,d,f,p,m,!1]));for(let[e,t]of await Promise.all(ae))w[e][2]=t;return se(`wasm ProcessOutputTensor`),w}finally{s.webnnOnRunEnd?.(u),s.stackRestore(w),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&s.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&s.webgpuUnregisterBuffer(e[2].gpuBuffer)}),x.forEach(e=>s._OrtReleaseTensor(e)),S.forEach(e=>s._OrtReleaseTensor(e)),C.forEach(e=>s._free(e)),y!==0&&s._OrtReleaseRunOptions(y),b.forEach(e=>s._free(e));for(let e of o){let t=An.get(e)-1;t===0?An.delete(e):An.set(e,t)}}},Fn=e=>{let t=E(),n=Sn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&D(`Can't get an profile file name.`),t._OrtFree(i)},In=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir=s(()=>{\"use strict\";He(),Ln(),vt(),lt(),Wt(),Rn=()=>!!w.wasm.proxy&&typeof document<`u`,Bn=!1,Vn=!1,Hn=!1,Gn=/* @__PURE__ */ new Map,Kn=(e,t)=>{let n=Gn.get(e);n?n.push(t):Gn.set(e,[t])},qn=()=>{if(Bn||!Vn||Hn||!zn)throw Error(`worker not ready`)},Jn=e=>{switch(e.data.type){case`init-wasm`:Bn=!1,e.data.err?(Hn=!0,Wn[1](e.data.err)):(Vn=!0,Wn[0]()),Un&&=(URL.revokeObjectURL(Un),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Gn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Yn=async()=>{if(!Vn){if(Bn)throw Error(`multiple calls to 'initWasm()' detected.`);if(Hn)throw Error(`previous call to 'initWasm()' failed.`);if(Bn=!0,Rn())return new Promise((e,t)=>{zn?.terminate(),ot().then(([n,r])=>{try{zn=r,zn.onerror=e=>t(e),zn.onmessage=Jn,Wn=[e,t];let i={type:`init-wasm`,in:w};if(!i.in.wasm.wasmPaths&&n){let e=$e();e&&(i.in.wasm.wasmPaths=e)}zn.postMessage(i),Un=n}catch(e){t(e)}},t)});try{await _t(w.wasm),await bn(w),Vn=!0}catch(e){throw Hn=!0,e}finally{Bn=!1}}},Xn=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:w}};zn.postMessage(r)});await xn(w,e)},Zn=async e=>Rn()?(qn(),new Promise((t,n)=>{Kn(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};zn.postMessage(r,[e.buffer])})):Tn(e),Qn=async(e,t)=>{if(Rn()){if(t?.preferredOutputLocation)throw Error(`session option \"preferredOutputLocation\" is not supported for proxy.`);return qn(),new Promise((n,r)=>{Kn(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),zn.postMessage(i,a)})}return En(e,t)},$n=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`release`,[t,n]);let r={type:`release`,in:e};zn.postMessage(r)});Dn(e)},er=async e=>{if(Rn())throw Error(`LoRA adapter is not supported for proxy.`);let t=typeof e==`string`?await Ut(e):e;return jn(t)},tr=async e=>{if(Rn())throw Error(`LoRA adapter is not supported for proxy.`);Mn(e)},nr=async(e,t,n,r,i,a,o)=>{if(Rn()){if(o.length>0)throw Error(`LoRA adapter is not supported for proxy.`);if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return qn(),new Promise((i,o)=>{Kn(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};zn.postMessage(c,In(s))})}return Pn(e,t,n,r,i,a,o)},rr=async e=>{if(Rn())return qn(),new Promise((t,n)=>{Kn(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};zn.postMessage(r)});Fn(e)}}),ar,or=s(()=>{\"use strict\";He(),ir(),ar=class{async loadAdapter(e){ie(),this.adapterId=await er(e),ae()}async dispose(){return tr(this.adapterId)}}}),sr,cr,lr,ur=s(()=>{\"use strict\";He(),or(),ir(),Ht(),Ue(),Wt(),sr=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},cr=e=>{switch(e[3]){case`cpu`:return new Ae(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!zt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Ae.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Bt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return Ae.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},lr=class{async fetchModelAndCopyToWasmMemory(e){return Zn(await Ut(e))}async loadModel(e,t){ie();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qn(n,t),ae()}async dispose(){return $n(this.sessionId)}async run(e,t,n,r=[]){ie();let i=r.map(e=>{if(!(e instanceof ar))throw Error(`LoRA adapter was not created by the WebAssembly backend.`);return e.adapterId}),a=[],o=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],r=this.inputNames.indexOf(t);if(r===-1)throw Error(`invalid input '${t}'`);a.push(n),o.push(r)});let s=[],c=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);s.push(n),c.push(r)});let l=a.map((e,t)=>sr(e,()=>`input \"${this.inputNames[o[t]]}\"`)),u=s.map((e,t)=>e?sr(e,()=>`output \"${this.outputNames[c[t]]}\"`):null),d=await nr(this.sessionId,o,l,c,u,n,i),f={};for(let e=0;e<d.length;e++)f[this.outputNames[c[e]]]=s[e]??cr(d[e]);return ae(),f}startProfiling(){}endProfiling(){rr(this.sessionId)}}}),dr,fr=s(()=>{\"use strict\";dr=e=>{if(e?.epContextDataRead)throw Error(`session option \"epContextDataRead\" is not supported by ONNX Runtime Web`)}}),pr={};c(pr,{OnnxruntimeWebAssemblyBackend:()=>hr,initializeFlags:()=>mr,wasmBackend:()=>gr});var mr,hr,gr,_r=s(()=>{\"use strict\";He(),or(),ir(),ur(),fr(),mr=()=>{(typeof w.wasm.initTimeout!=`number`||w.wasm.initTimeout<0)&&(w.wasm.initTimeout=0);let e=w.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.`),w.wasm.simd=!1),typeof w.wasm.proxy!=`boolean`&&(w.wasm.proxy=!1),typeof w.wasm.trace!=`boolean`&&(w.wasm.trace=!1),typeof w.wasm.numThreads!=`number`||!Number.isInteger(w.wasm.numThreads)||w.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)w.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;w.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},hr=class{async init(e){mr(),await Yn(),await Xn(e)}async createInferenceSessionHandler(e,t){dr(t);let n=new lr;return await n.loadModel(e,t),n}async createLoraAdapterHandler(e){let t=new ar;return await t.loadAdapter(e),t}},gr=new hr});He(),He(),He();var vr=`1.31.1`;{let e=(_r(),u(pr)).wasmBackend;m(`webgpu`,e,5),m(`webnn`,e,5),m(`cpu`,e,10),m(`wasm`,e,10)}Object.defineProperty(w.versions,\"web\",{value:vr,enumerable:!0});var yr=/* @__PURE__ */ t({InferenceSession:()=>yi,TRACE:()=>ui,TRACE_EVENT_BEGIN:()=>mi,TRACE_EVENT_END:()=>hi,TRACE_FUNC_BEGIN:()=>fi,TRACE_FUNC_END:()=>pi,Tensor:()=>ci,default:()=>Wo,env:()=>Br,registerBackend:()=>Ar}),br=Object.defineProperty,xr=Object.getOwnPropertyDescriptor,Sr=Object.getOwnPropertyNames,Cr=Object.prototype.hasOwnProperty,wr=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){\n/*!\n* ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\nif(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of \"`+e+`\" is not supported`)}),O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Tr=(e,t)=>{for(var n in t)br(e,n,{get:t[n],enumerable:!0})},Er=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of Sr(t))!Cr.call(e,i)&&i!==n&&br(e,i,{get:()=>t[i],enumerable:!(r=xr(t,i))||r.enumerable});return e},Dr=e=>Er(br({},`__esModule`,{value:!0}),e),Or,kr,Ar,jr,Mr,Nr=O(()=>{\"use strict\";Or=/* @__PURE__ */ new Map,kr=[],Ar=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=Or.get(e);if(r===void 0)Or.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend \"${e}\" using priority ${n}`)}if(n>=0){let t=kr.indexOf(e);t!==-1&&kr.splice(t,1);for(let t=0;t<kr.length;t++)if(Or.get(kr[t]).priority<=n){kr.splice(t,0,e);return}kr.push(e)}}else throw TypeError(`not a valid backend`)},jr=async e=>{let t=Or.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Mr=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?kr:n,i,a=[],o=/* @__PURE__ */ new Set;for(let e of r){let t=await jr(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider \"${e}\" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),Pr=O(()=>{\"use strict\";Nr()}),Fr,Ir=O(()=>{\"use strict\";Fr=`1.31.0-dev.20260911-2a43ec07e`}),Lr,Rr,zr=O(()=>{\"use strict\";Ir(),Lr=`warning`,Rr={wasm:{},webgl:{},webgpu:{},versions:{common:Fr},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Lr=e}},get logLevel(){return Lr}},Object.defineProperty(Rr,\"logLevel\",{enumerable:!0})}),Br,Vr=O(()=>{\"use strict\";zr(),Br=Rr}),Hr,Ur,Wr=O(()=>{\"use strict\";Hr=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},Ur=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),Gr,Kr,qr,Jr,Yr,Xr,Zr=O(()=>{\"use strict\";si(),Gr=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new oi(`float32`,u,[1,4,n,r]):new oi(`float32`,u,[1,3,n,r])},Kr=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,Gr(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(Gr(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return Gr(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},qr=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new oi({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Jr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new oi({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Yr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new oi({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},Xr=(e,t,n)=>new oi({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),Qr,$r,ei,ti,ni=O(()=>{\"use strict\";Qr=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),$r=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ei=!1,ti=()=>{if(!ei){ei=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(Qr.set(`int64`,BigInt64Array),$r.set(BigInt64Array,`int64`)),t&&(Qr.set(`uint64`,BigUint64Array),$r.set(BigUint64Array,`uint64`)),r?(Qr.set(`float16`,n),$r.set(n,`float16`)):Qr.set(`float16`,Uint16Array)}}}),ri,ii,ai=O(()=>{\"use strict\";si(),ri=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ii=(e,t)=>{switch(e.location){case`cpu`:return new oi(e.type,e.data,t);case`cpu-pinned`:return new oi({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new oi({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new oi({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new oi({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),oi,si=O(()=>{\"use strict\";Wr(),Zr(),ni(),ai(),oi=class{constructor(e,t,n){ti();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=Qr.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=Qr.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=$r.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=ri(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Kr(e,t)}static fromTexture(e,t){return qr(e,t)}static fromGpuBuffer(e,t){return Jr(e,t)}static fromMLTensor(e,t){return Yr(e,t)}static fromPinnedBuffer(e,t,n){return Xr(e,t,n)}toDataURL(e){return Hr(this,e)}toImageData(e){return Ur(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ii(this,e)}}}),ci,li=O(()=>{\"use strict\";si(),ci=oi}),ui,di,fi,pi,mi,hi,gi=O(()=>{\"use strict\";zr(),ui=(e,t)=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.timeStamp(`${e}::ORT::${t}`)},di=(e,t)=>{let n=(/* @__PURE__ */ Error()).stack?.split(/\\r\\n|\\r|\\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),ui(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},fi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||di(`BEGIN`,e)},pi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||di(`END`,e)},mi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.time(`ORT::${e}`)},hi=e=>{(typeof Rr.trace>`u`?!Rr.wasm.trace:!Rr.trace)||console.timeEnd(`ORT::${e}`)}}),_i,vi=O(()=>{\"use strict\";Nr(),li(),gi(),_i=class e{constructor(e){this.handler=e}async run(e,t,n){fi(),mi(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof ci||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof ci)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof ci)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof ci?t:new ci(t.type,t.data,t.dims)}return hi(`InferenceSession.run`),pi(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){fi(),mi(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await Mr(o),l=await s.createInferenceSessionHandler(a,c);return hi(`InferenceSession.create`),pi(),new e(l)}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}}}),yi,bi=O(()=>{\"use strict\";vi(),yi=_i}),xi=O(()=>{\"use strict\";}),Si=O(()=>{\"use strict\";}),Ci=O(()=>{\"use strict\";}),wi=O(()=>{\"use strict\";}),Ti={};Tr(Ti,{InferenceSession:()=>yi,TRACE:()=>ui,TRACE_EVENT_BEGIN:()=>mi,TRACE_EVENT_END:()=>hi,TRACE_FUNC_BEGIN:()=>fi,TRACE_FUNC_END:()=>pi,Tensor:()=>ci,env:()=>Br,registerBackend:()=>Ar});var Ei=O(()=>{\"use strict\";Pr(),Vr(),bi(),li(),xi(),Si(),gi(),Ci(),wi()}),Di=O(()=>{\"use strict\";}),Oi={};Tr(Oi,{default:()=>ji});var ki,Ai,ji,Mi=O(()=>{\"use strict\";mo(),na(),qi(),ki=`ort-wasm-proxy-worker`,Ai=globalThis.self?.name===ki,Ai&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:ta(n.wasm).then(()=>{to(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;no(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=oo(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;so(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:co(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;uo(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},po([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:fo(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),ji=Ai?null:e=>new Worker(e??Ii,{type:`module`,name:ki})}),Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi=O(()=>{\"use strict\";Di(),Ni=typeof location>`u`?void 0:location.origin,Pi=self.location.href>`file:`&&self.location.href<`file;`,Fi=()=>Pi?new URL(new URL(`ort.webgpu.min.mjs`,self.location.href).href,Ni).href:self.location.href,Ii=Fi(),Li=()=>{if(Ii&&!Ii.startsWith(`blob:`))return Ii.substring(0,Ii.lastIndexOf(`/`)+1)},Ri=(e,t)=>{try{let n=t??Ii;return(n?new URL(e,n):new URL(e)).origin===Ni}catch{return!1}},zi=(e,t)=>{let n=t??Ii;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Bi=(e,t)=>`${t??`./`}${e}`,Vi=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},Hi=async e=>(await import(\n/*webpackIgnore:true*/\n/*@vite-ignore*/\ne)).default,Ui=(Mi(),Dr(Oi)).default,Wi=async()=>{if(!Ii)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Ri(Ii))return[void 0,Ui()];let e=await Vi(Ii);return[e,Ui(e)]},Gi=void 0,Ki=async(e,t,n,r)=>{let i=Gi&&!(e||t);if(i){if(Ii)i=Ri(Ii)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,Gi];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??zi(r,t),a=n&&i&&!Ri(i,t),o=a?await Vi(i):i??Bi(r,t);return[a?o:void 0,await Hi(o)]}}}),Ji,Yi,Xi,Zi,Qi,$i,ea,ta,k,na=O(()=>{\"use strict\";qi(),Yi=!1,Xi=!1,Zi=!1,Qi=()=>{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}},$i=()=>{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}},ea=()=>{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}},ta=async e=>{if(Yi)return Promise.resolve();if(Xi)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(Zi)throw Error(`previous call to 'initializeWebAssembly()' failed.`);Xi=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!ea())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!$i())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=Qi();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, 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=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await Ki(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Li();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{Xi=!1,Yi=!0,Ji=t,e(),d&&URL.revokeObjectURL(d)},e=>{Xi=!1,Zi=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},k=()=>{if(Yi&&Ji)return Ji;throw Error(`WebAssembly is not initialized yet.`)}}),ra,ia,A,aa=O(()=>{\"use strict\";na(),ra=(e,t)=>{let n=k(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},ia=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)ia(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},A=e=>{let t=k(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),oa,sa=O(()=>{\"use strict\";na(),aa(),oa=e=>{let t=k(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=ra(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&A(`Can't create run options.`),e?.extra!==void 0&&ia(e.extra,``,/* @__PURE__ */ new WeakSet,(e,i)=>{let a=ra(e,r),o=ra(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&A(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),ca,la,ua,da,fa,pa,ma,ha=O(()=>{\"use strict\";na(),aa(),ca=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},la=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},ua=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},da=(e,t,n,r)=>{let i=ra(t,r),a=ra(n,r);k()._OrtAddSessionConfigEntry(e,i,a)!==0&&A(`Can't set a session config entry: ${t} - ${n}.`)},fa=(e,t,n,r)=>{let i=ra(t,r),a=ra(n,r);e.push([i,a])},pa=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,da(e,`session.disable_quant_qdq`,`1`,n),da(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&da(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&fa(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&fa(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];fa(a,`forceCpuNodeNames`,e.join(`\n`),n)}r.validationMode&&fa(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&fa(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);fa(a,e,t,n)}}}let o=k().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;fa(a,`deviceId`,e.toString(),n),fa(a,`webgpuInstance`,t.toString(),n),fa(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=ra(r,n),s=a.length,c=0,l=0;if(s>0){c=k()._malloc(s*k().PTR_SIZE),n.push(c),l=k()._malloc(s*k().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)k().setValue(c+e*k().PTR_SIZE,a[e][0],`*`),k().setValue(l+e*k().PTR_SIZE,a[e][1],`*`)}await k()._OrtAppendExecutionProvider(e,o,c,l,s)!==0&&A(`Can't append execution provider: ${r}.`)}},ma=async e=>{let t=k(),n=0,r=[],i=e||{};ua(i);try{let e=ca(i.graphOptimizationLevel??`all`),a=la(i.executionMode??`sequential`),o=typeof i.logId==`string`?ra(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?ra(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&A(`Can't create session options.`),i.executionProviders&&await pa(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);da(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=ra(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&A(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&ia(i.extra,``,/* @__PURE__ */ new WeakSet,(e,t)=>{da(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&A(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),ga,_a,va,ya,ba,xa,Sa,Ca,wa=O(()=>{\"use strict\";ga=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},_a=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},va=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},ya=e=>{switch(e){case`float16`:return typeof Float16Array<`u`?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},ba=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},xa=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Sa=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Ca=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Ta,Ea=O(()=>{\"use strict\";Di(),Ta=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<0x40000000)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Da,Oa=O(()=>{\"use strict\";wa(),Da=(e,t)=>new(ya(t))(e)}),ka,Aa,ja,Ma,Na,Pa,Fa,Ia=O(()=>{\"use strict\";wa(),ka=[`V`,`I`,`W`,`E`,`F`],Aa=(e,t)=>{console.log(`[${ka[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`)},Na=(e,t)=>{ja=e,Ma=t},Pa=(e,t)=>{let n=ba(e);n>=ba(ja)&&Aa(n,typeof t==`function`?t():t)},Fa=(...e)=>{Ma&&Pa(...e)}}),La,Ra,za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja=O(()=>{\"use strict\";wa(),Ia(),La=/* @__PURE__ */ new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Ra=(e,t)=>{if(t===`int32`)return e;let n=La.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(ya(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>0x7fffffff))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},za=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Ba=1,Va=()=>Ba++,Ha=/* @__PURE__ */ new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),Ua=(e,t)=>{let n=La.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},Wa=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,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 Ua(this.dataType,this.tensorShape)}destroy(){Fa(`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),n=za(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},Ga=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,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Ha.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Fa(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==Ua(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=Ra(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}Fa(`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?za(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}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},Ka=class{constructor(e){this.backend=e,this.tensorTrackersById=/* @__PURE__ */ new Map,this.freeTensors=[],this.externalTensors=/* @__PURE__ */ new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Va();return this.tensorTrackersById.set(e,new Ga(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,n,r,i){Fa(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Fa(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.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,n,r){let i=this.getMLContext(e),a=Va(),o=new Wa({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new Ga(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Fa(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Fa(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new Wa({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},qa=(...e)=>new Ka(...e)}),Ya={};Tr(Ya,{WebNNBackend:()=>Qa});var Xa,Za,Qa,$a=O(()=>{\"use strict\";wa(),na(),Oa(),Ja(),Ia(),Xa=/* @__PURE__ */ new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),Za=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},Qa=class{constructor(e){this.tensorManager=qa(this),this.mlContextBySessionId=/* @__PURE__ */ new Map,this.sessionIdsByMLContext=/* @__PURE__ */ new Map,this.mlContextCache=[],this.sessionGraphInputs=/* @__PURE__ */ new Map,this.sessionGraphOutputs=/* @__PURE__ */ new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=/* @__PURE__ */ new Map,this.mlOpSupportLimitsBySessionId=/* @__PURE__ */ new Map,Na(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Fa(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Fa(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Fa(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>Za(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=/* @__PURE__ */ new Set,this.sessionIdsByMLContext.set(t,n)),n.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 n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Fa(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=Xa.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Fa(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=Xa.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!k().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Fa(`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 n=await this.tensorManager.download(e);return Da(n,t)}}registerMLTensor(e,t,n,r){let i=Xa.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Fa(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=Xa.get(ga(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),eo,to,no,ro,io,ao,oo,so,co,lo,uo,fo,po,mo=O(()=>{\"use strict\";Ei(),sa(),ha(),wa(),na(),aa(),Ea(),eo=(e,t)=>{k()._OrtInit(e,t)!==0&&A(`Can't initialize onnxruntime.`)},to=async e=>{eo(e.wasm.numThreads,ba(e.logLevel))},no=async(e,t)=>{k().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: \"${t}\"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: \"${r}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&k().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new($a(),Dr(Ya)).WebNNBackend(e);k().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},ro=/* @__PURE__ */ new Map,io=e=>{let t=k(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&A(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},ao=(e,t)=>{let n=k(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&A(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},oo=e=>{let t=k(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},so=async(e,t)=>{let n,r,i=k();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=oo(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await ma(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Ta(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&A(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=io(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=ao(a,t);e===0&&A(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:_a(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=ao(a,n+e);r===0&&A(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:_a(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&A(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Ca(e))}),ro.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&A(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&A(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&A(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},co=e=>{let t=k(),n=ro.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&A(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&A(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&A(`Can't release session.`),ro.delete(e)},lo=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=k(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=va(ga(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location \"gpu-buffer\" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=va(ga(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);p=n(r,t,ga(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,ra(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=ga(l);m=va(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location \"ml-tensor\" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(ga(l),p,m,g,u.length,Ca(f));e===0&&A(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},uo=async(e,t,n,r,i,a)=>{let o=k(),s=o.PTR_SIZE,c=ro.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),ee=o.stackAlloc(h*s),w=o.stackAlloc(h*s),te=o.stackAlloc(g*s),ne=o.stackAlloc(g*s);try{[_,v]=oa(a),mi(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await lo(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await lo(i[t],b,x,e,d[r[t]],h+r[t],p);hi(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(ee+e*s,y[e],`*`),o.setValue(w+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(te+e*s,b[e],`*`),o.setValue(ne+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);mi(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&A(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&A(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&A(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}hi(`wasm bindInputsOutputs`),ro.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,te,_):await o._OrtRun(l,w,ee,h,ne,g,te,_),c!==0&&A(`failed to call OrtRun().`);let C=[],re=[];mi(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(te+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&A(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&A(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&A(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=_a(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation \"gpu-buffer\" is not supported without using WebGPU.`);let r=t(d),i=va(a,g);if(i===void 0||!xa(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(ya(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&A(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation \"ml-tensor\" is not supported without using WebNN.`);if(va(a,g)===void 0||!Sa(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation \"ml-tensor\" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(ya(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&A(`Can't clear bound outputs.`),ro.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))C[e][2]=t;return hi(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},fo=e=>{let t=k(),n=ro.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&A(`Can't get an profile file name.`),t._OrtFree(i)},po=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),ho,go,_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No=O(()=>{\"use strict\";Ei(),mo(),na(),qi(),ho=()=>!!Br.wasm.proxy&&typeof document<`u`,_o=!1,vo=!1,yo=!1,So=/* @__PURE__ */ new Map,Co=(e,t)=>{let n=So.get(e);n?n.push(t):So.set(e,[t])},wo=()=>{if(_o||!vo||yo||!go)throw Error(`worker not ready`)},To=e=>{switch(e.data.type){case`init-wasm`:_o=!1,e.data.err?(yo=!0,xo[1](e.data.err)):(vo=!0,xo[0]()),bo&&=(URL.revokeObjectURL(bo),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=So.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Eo=async()=>{if(!vo){if(_o)throw Error(`multiple calls to 'initWasm()' detected.`);if(yo)throw Error(`previous call to 'initWasm()' failed.`);if(_o=!0,ho())return new Promise((e,t)=>{go?.terminate(),Wi().then(([n,r])=>{try{go=r,go.onerror=e=>t(e),go.onmessage=To,xo=[e,t];let i={type:`init-wasm`,in:Br};if(!i.in.wasm.wasmPaths&&n){let e=Li();e&&(i.in.wasm.wasmPaths=e)}go.postMessage(i),bo=n}catch(e){t(e)}},t)});try{await ta(Br.wasm),await to(Br),vo=!0}catch(e){throw yo=!0,e}finally{_o=!1}}},Do=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:Br}};go.postMessage(r)});await no(Br,e)},Oo=async e=>ho()?(wo(),new Promise((t,n)=>{Co(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};go.postMessage(r,[e.buffer])})):oo(e),ko=async(e,t)=>{if(ho()){if(t?.preferredOutputLocation)throw Error(`session option \"preferredOutputLocation\" is not supported for proxy.`);return wo(),new Promise((n,r)=>{Co(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),go.postMessage(i,a)})}return so(e,t)},Ao=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`release`,[t,n]);let r={type:`release`,in:e};go.postMessage(r)});co(e)},jo=async(e,t,n,r,i,a)=>{if(ho()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return wo(),new Promise((i,o)=>{Co(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};go.postMessage(c,po(s))})}return uo(e,t,n,r,i,a)},Mo=async e=>{if(ho())return wo(),new Promise((t,n)=>{Co(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};go.postMessage(r)});fo(e)}}),Po,Fo,Io,Lo=O(()=>{\"use strict\";Ei(),No(),wa(),Di(),Ea(),Po=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Fo=e=>{switch(e[3]){case`cpu`:return new ci(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!xa(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return ci.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Sa(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return ci.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Io=class{async fetchModelAndCopyToWasmMemory(e){return Oo(await Ta(e))}async loadModel(e,t){fi();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ko(n,t),pi()}async dispose(){return Ao(this.sessionId)}async run(e,t,n){fi();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Po(e,()=>`input \"${this.inputNames[i[t]]}\"`)),c=a.map((e,t)=>e?Po(e,()=>`output \"${this.outputNames[o[t]]}\"`):null),l=await jo(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Fo(l[e]);return pi(),u}startProfiling(){}endProfiling(){Mo(this.sessionId)}}}),Ro={};Tr(Ro,{OnnxruntimeWebAssemblyBackend:()=>Bo,initializeFlags:()=>zo,wasmBackend:()=>Vo});var zo,Bo,Vo,Ho=O(()=>{\"use strict\";Ei(),No(),Lo(),zo=()=>{(typeof Br.wasm.initTimeout!=`number`||Br.wasm.initTimeout<0)&&(Br.wasm.initTimeout=0);let e=Br.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.`),Br.wasm.simd=!1),typeof Br.wasm.proxy!=`boolean`&&(Br.wasm.proxy=!1),typeof Br.wasm.trace!=`boolean`&&(Br.wasm.trace=!1),typeof Br.wasm.numThreads!=`number`||!Number.isInteger(Br.wasm.numThreads)||Br.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)Br.wasm.numThreads=1;else{let e=typeof navigator>`u`?wr(`node:os`).cpus().length:navigator.hardwareConcurrency;Br.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Bo=class{async init(e){zo(),await Eo(),await Do(e)}async createInferenceSessionHandler(e,t){let n=new Io;return await n.loadModel(e,t),n}},Vo=new Bo});Ei(),Ei(),Ei();var Uo=`1.31.0-dev.20260914-8d85527a0`,Wo=Ti;{let e=(Ho(),Dr(Ro)).wasmBackend;Ar(`webgpu`,e,5),Ar(`webnn`,e,5),Ar(`cpu`,e,10),Ar(`wasm`,e,10)}Object.defineProperty(Br.versions,\"web\",{value:Uo,enumerable:!0});let Go=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.31.0-dev.20260911-2a43ec07e`},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);Go=e}},get logLevel(){return Go}},\"logLevel\",{enumerable:!0});let Ko=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},qo=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r},Jo=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new os(`float32`,u,[1,4,n,r]):new os(`float32`,u,[1,3,n,r])},Yo=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,Jo(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(Jo(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return Jo(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},Xo=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new os({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},Zo=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new os({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},Qo=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new os({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},$o=(e,t,n)=>new os({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),es=/* @__PURE__ */ new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),ts=/* @__PURE__ */ new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),ns=!1,rs=()=>{if(!ns){ns=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(es.set(`int64`,BigInt64Array),ts.set(BigInt64Array,`int64`)),t&&(es.set(`uint64`,BigUint64Array),ts.set(BigUint64Array,`uint64`)),r?(es.set(`float16`,n),ts.set(n,`float16`)):es.set(`float16`,Uint16Array)}},is=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},as=(e,t)=>{switch(e.location){case`cpu`:return new os(e.type,e.data,t);case`cpu-pinned`:return new os({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new os({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new os({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new os({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var os=class{constructor(e,t,n){rs();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=es.get(r);if(!t)throw TypeError(`unsupported type \"${r}\" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type \"${r}\" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type \"${r}\" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=es.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=ts.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=is(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return Yo(e,t)}static fromTexture(e,t){return Xo(e,t)}static fromGpuBuffer(e,t){return Zo(e,t)}static fromMLTensor(e,t){return Qo(e,t)}static fromPinnedBuffer(e,t,n){return $o(e,t,n)}toDataURL(e){return Ko(this,e)}toImageData(e){return qo(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return as(this,e)}};let ss=os;var cs={url:self.location.href},ls=Object.defineProperty,us=(e,t)=>{for(var n in t)ls(e,n,{get:t[n],enumerable:!0})},ds={},fs={},ps={},ms=`4.3.2`,hs=typeof self<`u`,gs=!Bs(ds),_s=!Bs(fs),vs=hs&&`caches`in self,ys=globalThis.Deno!==void 0;globalThis.Bun;var bs=ys&&vs&&!gs,xs=typeof process<`u`,Ss=xs&&process?.release?.name===`node`&&!bs,Cs=typeof window<`u`&&window.document!==void 0,ws=hs&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),Ts=Cs||ws||bs,Es=Ss||typeof navigator<`u`&&`gpu`in navigator,Ds=typeof navigator<`u`&&`ml`in navigator,Os=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,ks=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,As=typeof ServiceWorkerGlobalScope<`u`&&hs&&self instanceof ServiceWorkerGlobalScope,js=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\\/(\\d+)/);return t?parseInt(t[1],10)<26:!1})(),j=Object.freeze({IS_BROWSER_ENV:Cs,IS_WEBWORKER_ENV:ws,IS_WEB_ENV:Ts,IS_SERVICE_WORKER_ENV:As,IS_DENO_WEB_RUNTIME:bs,IS_WEB_CACHE_AVAILABLE:vs,IS_WEBGPU_AVAILABLE:Es,IS_WEBNN_AVAILABLE:Ds,IS_SAFARI_BELOW_26:js,IS_PROCESS_AVAILABLE:xs,IS_NODE_ENV:Ss,IS_FS_AVAILABLE:gs,IS_PATH_AVAILABLE:_s,IS_CRYPTO_AVAILABLE:Os,IS_CHROME_AVAILABLE:ks}),Ms=gs&&_s,Ns=`./`;if(Ms){let e=self.location.href;e?Ns=fs.dirname(fs.dirname(ps.fileURLToPath(e))):typeof __dirname<`u`&&(Ns=fs.dirname(__dirname))}var Ps=Ms?fs.join(Ns,`/.cache/`):null,Fs=`/models/`,Is=Ms?fs.join(Ns,Fs):Fs,Ls=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Rs=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),zs=Rs.WARNING,M={version:ms,backends:{onnx:{}},get logLevel(){return zs},set logLevel(e){zs=e,M.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Cs||ws||bs),localModelPath:Is,useFS:gs,useBrowserCache:vs,useFSCache:gs,cacheDir:Ps,useCustomCache:!1,customCache:null,useWasmCache:vs||gs,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Ls};function Bs(e){return Object.keys(e).length===0}var Vs=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function Hs(e,t){e&&e(t)}var Us=class extends Vs{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=/* @__PURE__ */ new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function Ws(e){return Number.isInteger(e)||typeof e==`bigint`}function Gs(e){return e==null||e===-1}function Ks(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function qs(...e){return Array.prototype.concat.apply([],e)}function Js(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function Ys(e,t){return Math.abs((e+t)%(2*t)-t)}function Xs(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function Zs(e,t){let n=0;for(let r of e)r===t&&++n;return n}var N={error(...e){M.logLevel<=Rs.ERROR&&console.error(...e)},warn(...e){M.logLevel<=Rs.WARNING&&console.warn(...e)},info(...e){M.logLevel<=Rs.INFO&&console.log(...e)},debug(...e){M.logLevel<=Rs.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Qs=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=/* @__PURE__ */ Object.create(null);for(let n of e){let e=t;for(let t=0;t<n.length;++t){let r=n[t];e=e[r]??=/* @__PURE__ */ Object.create(null)}e.end=n}return t}split(e){let t=[],n=e.length,r=0,i=0;for(;i<n;){let a=this.trie,o=null,s=i;for(;s<n&&(a=a[e[s]]);)a.end&&(o=a.end),++s;o?(i>r&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r<n&&t.push(e.slice(r)),t}},$s=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}},ec=(e,t)=>{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=/* @__PURE__ */ new Map,i=e.replace(/(\\\\[pP])\\{([^}=]+)\\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},tc=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`),nc=(e,t=!0)=>{if(e.Regex!==void 0)return ec(Bc(Oc(e.Regex)),`gu`);if(e.String!==void 0){let n=Vc(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},rc=`\\\\p{Alphabetic}\\\\p{M}\\\\p{Nd}\\\\p{Pc}`,ic=`${rc}\\\\u00B2\\\\u00B3\\\\u00B9\\\\u00BC-\\\\u00BE`,ac=`[${ic}]`,oc=`[^${ic}]`,sc=`(?:(?<!${ac})(?=${ac})|(?<=${ac})(?!${ac}))`,cc=`(?:(?<!${ac})(?!${ac})|(?<=${ac})(?=${ac}))`,lc=`(?:(?<![\\\\s\\\\S])|(?<=\\\\n))`,uc=`(?:(?=\\\\n)|(?![\\\\s\\\\S]))`,dc=`0-9A-Fa-f`,fc=/* @__PURE__ */ new Map([[`A`,`(?<![\\\\s\\\\S])`],[`z`,`(?![\\\\s\\\\S])`],[`Z`,`(?=\\\\n?(?![\\\\s\\\\S]))`],[`h`,`[${dc}]`],[`H`,`[^${dc}]`],[`w`,ac],[`W`,oc],[`d`,`\\\\p{Nd}`],[`D`,`\\\\P{Nd}`],[`s`,`\\\\p{White_Space}`],[`S`,`\\\\P{White_Space}`],[`b`,sc],[`B`,cc],[`a`,`\\\\x07`],[`e`,`\\\\x1B`]]),pc=/* @__PURE__ */ new Map([[`h`,dc],[`w`,rc],[`d`,`\\\\p{Nd}`],[`D`,`\\\\P{Nd}`],[`s`,`\\\\p{White_Space}`],[`S`,`\\\\P{White_Space}`],[`a`,`\\\\x07`],[`e`,`\\\\x1B`]]),mc=/* @__PURE__ */ new Map([[`W`,`[^${rc}]`],[`H`,`[^${dc}]`]]),hc=/* @__PURE__ */ new Map([[`\n`,`\\\\n`],[`\\r`,`\\\\r`],[` `,`\\\\t`],[`\\f`,`\\\\f`],[`\\v`,`\\\\v`]]),gc=/* @__PURE__ */ new Map([[`alpha`,`\\\\p{Alphabetic}`],[`alnum`,`\\\\p{Alphabetic}\\\\p{Nd}`],[`digit`,`\\\\p{Nd}`],[`lower`,`\\\\p{Lowercase}`],[`upper`,`\\\\p{Uppercase}`],[`space`,`\\\\p{White_Space}`],[`blank`,`\\\\t\\\\p{Zs}`],[`punct`,`\\\\p{P}\\\\p{S}`],[`cntrl`,`\\\\p{Cc}`],[`word`,rc],[`xdigit`,dc]]),_c=`^$\\\\.*+?()[]{}|/`,vc=/^\\(\\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,yc=/^\\\\([pPxu])\\{([^}]*)\\}/,bc=/^\\{(\\d+(?:,\\d*)?|,\\d+)\\}/,xc=/^\\[:(\\^?)(\\p{Alphabetic}+):\\]/u,Sc=/^\\[:\\^:\\]/,Cc=/^\\[(?:\\.[^\\]]*\\.\\]|=[^\\]]*=\\])/,wc=/^(?:\\\\x[0-9A-Fa-f]{2}|\\\\u[0-9A-Fa-f]{4}|\\\\c[A-Za-z])/,Tc=e=>e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`,Ec=(e,t)=>String.fromCodePoint(e.codePointAt(t)),Dc=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let n=String.fromCharCode(t);return Tc(n)?`[${n.toLowerCase()}${n.toUpperCase()}]`:null},Oc=e=>e.replace(/\\[\\^\\(\\\\s\\|\\[([^\\]]+)\\]\\)\\]/g,`[^()|\\\\s$1]`),kc=`[\\\\s\\\\S]`,Ac=256,jc=()=>({fragment:``,alternatives:[],tail:null,contains_complex_set:!1}),Mc=e=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},Nc=(e,t,n,r=!0)=>{e.tail===`range`&&Mc(n),e.alternatives.push(t),e.tail=`set`,e.contains_complex_set=e.contains_complex_set||r},Pc=(e,t,n=!1,r=-1)=>{n&&e.tail===`range`&&Mc(r),e.tail===`range`?(e.fragment+=t,e.tail=`complete_range`):(e.fragment+=t,e.tail=n?`set`:`scalar`,e.contains_complex_set=e.contains_complex_set||n)},Fc=(e,t,n)=>{let r=yc.exec(e.slice(t));if(r){let[e,i,a]=r;return i===`P`&&a===`Word`?Nc(n,`[^${rc}]`,t):Pc(n,i===`x`?`\\\\u{${a}}`:i===`p`&&a===`Word`?rc:e,i===`p`||i===`P`,t),t+e.length}let i=wc.exec(e.slice(t));if(i)return Pc(n,i[0]),t+i[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=Ec(e,t+1),o=t+1+a.length,s=hc.get(a);if(s!==void 0)return Pc(n,s),o;let c=mc.get(a);if(c!==void 0)return Nc(n,c,t),o;let l=pc.get(a),u,d=!1;return l===void 0?u=/[A-Za-z0-9]/.test(a)||_c.includes(a)||a===`-`?`\\\\${a}`:a:(u=l,d=a!==`a`&&a!==`e`),Pc(n,u,d,t),o},Ic=e=>e.length===1?e[0]:`(?:(?=(?:${e.join(`|`)}))${kc})`,Lc=e=>Ic(e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives]),Rc=e=>{let t=ec(`^(?:${e})$`,`u`),n=``;for(let e=0;e<26;++e){let r=String.fromCharCode(65+e),i=String.fromCharCode(97+e),a=t.test(r);a!==t.test(i)&&(n+=a?i:r)}return n},zc=(e,t,n,r=!0,i=1)=>{if(i>Ac)throw SyntaxError(`Maximum character-class nesting depth of ${Ac} exceeded at index ${t}`);let a=t+1,o=e[a]===`^`;o&&++a;let s=a,c=[jc()],l=c[0],u=!1;for(;a<e.length;){let d=Ec(e,a);if(d===`\\\\`)a=Fc(e,a,l);else{if(d===`]`){if(a===s){Pc(l,`\\\\]`),++a;continue}if(l.tail===null)throw c.length>1?SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):SyntaxError(`Empty character class at index ${t}`);let e=c.some(e=>e.contains_complex_set);if(o&&c.length>1&&u)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let i=Lc(c[0]),d=i;if(c.length>1){let e=``;for(let t=1;t<c.length;++t)e+=`(?=${Lc(c[t])})`;d=`(?:${e}${i})`}let f=c.length===1&&l.alternatives.length===0,p=l.fragment;if(n&&r){let e=Rc(d);e.length>0&&(f?(p+=e,d=`[${p}]`):d=Ic([d,`[${e}]`]))}return{atom:o?f?`[^${p}]`:`(?:(?!${d})${kc})`:d,end:a+1,negated:o,contains_complex_set:e,contains_nested_negated_complex_set:u}}if(e.startsWith(`&&`,a)){if(l.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);l=jc(),c.push(l),a+=2}else if(d===`[`){let t=e.slice(a);if(Sc.test(t))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let r=xc.exec(t);if(r){let[,e,t]=r,i=gc.get(t);if(i===void 0)throw SyntaxError(`Unsupported POSIX character class \"${t}\" at index ${a}`);if(n&&e&&(t===`lower`||t===`upper`))throw SyntaxError(`Unsupported negated POSIX ${t} class inside an inline case-insensitive group`);e?Nc(l,`[^${i}]`,a):Pc(l,i,!0,a),a+=r[0].length;continue}if(Cc.test(t))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let o=zc(e,a,n,!1,i+1);Nc(l,o.atom,a,o.contains_complex_set),u||=o.contains_nested_negated_complex_set||o.negated&&o.contains_complex_set,a=o.end}else if(d===`-`){let t=e[a+1]===`]`||e.startsWith(`&&`,a+1);l.tail===`set`&&!t&&Mc(a),l.tail===null||l.tail===`range`||l.tail===`complete_range`||t?Pc(l,`\\\\-`):(l.fragment+=`-`,l.tail=`range`),++a}else Pc(l,d===`^`&&l.fragment.length===0?`\\\\^`:d),a+=d.length}}throw SyntaxError(`${c.length>1?`Unterminated character-class intersection`:`Unterminated character class`} at index ${t}`)},Bc=e=>{let t=``,n=-1,r=!1,i=!1,a=[],o=e=>{n=t.length,t+=e,r=!1};for(let s=0;s<e.length;){let c=Ec(e,s);if(c===`\\\\`){let n=yc.exec(e.slice(s));if(n){let[e,t,r]=n,a=e;if(t===`x`){let e=`\\\\u{${r}}`;a=i?Dc(r)??e:e}else r===`Word`&&(a=t===`p`?ac:oc);o(a),s+=e.length;continue}let r=wc.exec(e.slice(s));if(r){let e=r[0];o(i&&e[1]!==`c`?Dc(e.slice(2))??e:e),s+=e.length;continue}if(s+1>=e.length){t+=c;break}let a=Ec(e,s+1);if(s+=1+a.length,a===`G`)continue;let l=hc.get(a);if(l!==void 0){o(l);continue}let u=fc.get(a),d;d=u===void 0?/[A-Za-z0-9]/.test(a)||_c.includes(a)?`\\\\${a}`:a:u,o(d)}else switch(c){case`[`:{let t=zc(e,s,i);o(t.atom),s=t.end;continue}case`]`:o(`\\\\]`),++s;continue;case`.`:o(`[^\\\\n]`),++s;continue;case`^`:o(lc),++s;continue;case`$`:o(uc),++s;continue;case`(`:{let n=e.startsWith(`(?i:`,s),o=n?`(?i:`:vc.exec(e.slice(s))?.[0]??`(`,c=n||o===`(?>`?`(?:`:o;a.push([t.length,i]),n&&(i=!0),t+=c,r=!1,s+=o.length;continue}case`)`:t+=c,[n,i]=a.pop()??[-1,!1],r=!1,++s;continue;case`|`:t+=c,n=-1,r=!1,++s;continue;case`{`:{let i=bc.exec(e.slice(s));if(!i||n<0){o(`\\\\{`),++s;continue}let a=i[1].startsWith(`,`)?`0${i[1]}`:i[1];s+=i[0].length;let c=e[s];c===`+`||c===`*`?(t=`${t.slice(0,n)}(?:${t.slice(n)}{${a}})${c}`,++s):t+=`{${a}}`,r=!0;continue}case`}`:o(`\\\\}`),++s;continue;case`+`:if(r){++s;continue}t+=c,r=!0,++s;continue;case`*`:case`?`:t+=c,r=!0,++s;continue;default:o(i&&Tc(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),s+=c.length;continue}}return t},Vc=e=>e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`),Hc=(e,t,n)=>{let r=[],i=0;for(;i<e.length;)if(r.push(e[i]),(t.get(e[i])??n)!==n)++i;else for(;++i<e.length&&(t.get(e[i])??n)===n;)t.get(r.at(-1))!==n&&(r[r.length-1]+=e[i]);return r},Uc=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,Wc=e=>Number.isInteger(e)||typeof e==`bigint`,Gc=e=>{let t=0;for(let n of e)++t;return t},Kc=e=>Xc(e.toLowerCase()),qc=(...e)=>Array.prototype.concat.apply([],e),Jc=e=>new Map(Object.entries(e)),Yc=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r<i.index&&n.push(e.slice(r,i.index)),t.length>0&&n.push(t),r=i.index+t.length}return r<e.length&&n.push(e.slice(r)),n},Xc=e=>e.replace(/\\p{M}/gu,``),Zc=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a \"${r}\" property`;return null},Qc=e=>e.match(/\\S+/g)||[],$c=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},el=class extends $c{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},tl=class extends el{tokenize_chinese_chars(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];Uc(r.charCodeAt(0))?(t.push(` `),t.push(r),t.push(` `)):t.push(r)}return t.join(``)}strip_accents(e){return e.normalize(`NFD`).replace(/\\p{Mn}/gu,``)}is_control(e){switch(e){case` `:case`\n`:case`\\r`:return!1;default:return/^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let n of e){let e=n.charCodeAt(0);e===0||e===65533||this.is_control(n)||(/^\\s$/.test(n)?t.push(` `):t.push(n))}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=class extends el{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=e.includes(`~`)?e.split(`~`).map(e=>e.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},rl=class extends el{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>hl(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},il=class extends el{constructor(e){super(e),this.pattern=nc(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??``)}},al=class extends el{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},ol=class extends al{constructor(){super(...arguments),this.form=`NFC`}},sl=class extends al{constructor(){super(...arguments),this.form=`NFD`}},cl=class extends al{constructor(){super(...arguments),this.form=`NFKC`}},ll=class extends al{constructor(){super(...arguments),this.form=`NFKD`}},ul=class extends el{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}},dl=class extends el{normalize(e){return Xc(e)}},fl=class extends el{normalize(e){return e.toLowerCase()}},pl=class extends el{normalize(e){return e=this.config.prepend+e,e}};function ml(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new tl(e);case`Precompiled`:return new nl(e);case`Sequence`:return new rl(e);case`Replace`:return new il(e);case`NFC`:return new ol(e);case`NFD`:return new sl(e);case`NFKC`:return new cl(e);case`NFKD`:return new ll(e);case`Strip`:return new ul(e);case`StripAccents`:return new dl(e);case`Lowercase`:return new fl(e);case`Prepend`:return new pl(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var hl=ml,gl=class extends $c{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},_l=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),vl=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(_l),yl=`\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E`,bl=class extends gl{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu,this.byte_encoder=_l,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},xl=class extends gl{pre_tokenize_text(e,t){return e.match(/\\w+|[^\\w\\s]+/g)||[]}},Sl=class extends gl{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},Cl=class extends gl{constructor(e){super(),this.config=e,this.pattern=nc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):Yc(e,this.pattern)}},wl=class extends gl{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${yl}]+|[${yl}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Tl=class extends gl{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)||[]}},El=class extends gl{constructor(){super(),this.pattern=RegExp(`[^\\\\s${yl}]+|[${yl}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Dl=class extends gl{constructor(e){super(),this.config=e,this.pattern=nc(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},Ol=class extends gl{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>Ml(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},kl=class extends gl{pre_tokenize_text(e){return Qc(e)}},Al=class extends gl{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;n<e.length;n+=this._length)t.push(e.slice(n,n+this._length));return t}};function jl(e){if(e===null)return null;switch(e.type){case`BertPreTokenizer`:return new El;case`Sequence`:return new Ol(e);case`Whitespace`:return new xl;case`WhitespaceSplit`:return new kl;case`Metaspace`:return new Sl(e);case`ByteLevel`:return new bl(e);case`Split`:return new Cl(e);case`Punctuation`:return new wl(e);case`Digits`:return new Tl(e);case`Replace`:return new Dl(e);case`FixedLength`:return new Al(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}var Ml=jl,Nl=class extends $c{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=/* @__PURE__ */ 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=Hc(t,this.tokens_to_ids,this.unk_token_id)),t}},Pl=class extends Nl{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Jc(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){let t=[];for(let n of e){let e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i<e.length;){let t=e.length,n=null;for(;i<t;){let r=e.slice(i,t).join(``);if(i>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},Fl=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,/* @__PURE__ */ new Map)}},Il=class{constructor(){this.root=Fl.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=Fl.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e,t=0){let n=this.root;if(n===void 0)return;let r=``;for(let i=t;i<e.length;++i){let t=e[i];if(r+=t,n=n.children.get(t),n===void 0)return;n.is_leaf&&(yield r)}}},Ll=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},Rl=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Ll(this.bos_token_id??0,0,0,0,0),i=new Ll(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=new Ll(r,this.nodes.length,e,t,n);this.begin_nodes[e].push(i),this.end_nodes[e+t].push(i),this.nodes.push(i)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function zl(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}var Bl=class extends Nl{constructor(e,t){super(e);let n=e.vocab.length;this.vocab=Array(n),this.scores=Array(n);for(let t=0;t<n;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),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=zl(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Il,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;n<t.length;){let r=!1,i=this.trie.common_prefix_search(t,n);for(let t of i){let i=this.tokens_to_ids.get(t),a=this.scores[i],o=Gc(t);e.insert(n,o,a,i),!r&&o===1&&(r=!0)}r||e.insert(n,1,this.unk_score,this.unk_token_id),n+=1}}tokenize(e){let t=new Rl(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let n of e){let e=this.tokenize(n);t.push(...e)}return t}},Vl=class{constructor(e=(e,t)=>e>t,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 e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._sift_up_from(e))}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 n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_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}},Hl=class{constructor(e){this.capacity=e,this.cache=/* @__PURE__ */ 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()}},Ul=class extends Nl{constructor(e){super(e),this.tokens_to_ids=Jc(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),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 Hl(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 n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new Vl((e,t)=>e.score<t.score),t={token:n[0],bias:0,prev:null,next:null},i=t;for(let t=1;t<n.length;++t){let r={bias:t/n.length,token:n[t],prev:i,next:null};i.next=r,this.add_node(e,i),i=r}for(;!e.is_empty();){let n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;if(n.deleted=!0,n.next.deleted=!0,n.prev){let e={...n.prev};n.prev.deleted=!0,n.prev=e,e.prev?e.prev.next=e:t=e}let r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};r.prev?(r.prev.next=r,this.add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this.add_node(e,r))}for(let e=t;e!==null;e=e.next)r.push(e.token)}else r=n;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,r),r}add_node(e,t){let n=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));n!==void 0&&(t.score=n+t.bias,e.push(t))}encode(e){let t=[];for(let n of e){if(this.ignore_merges&&this.tokens_to_ids.has(n)){t.push(n);continue}let e=this.bpe(n);for(let n of e)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let e=Array.from(this.text_encoder.encode(n)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},Wl=class extends Nl{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=Jc(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function Gl(e,t){switch(e.type){case`WordPiece`:return new Pl(e);case`Unigram`:return new Bl(e,t.eos_token);case`BPE`:return new Ul(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Bl(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new Ul(e):new Pl(e):new Wl(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var Kl=Gl,ql=class extends $c{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Jl=class extends ql{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=qc(i,e),a=qc(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=qc(i,t),a=qc(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},Yl=class extends ql{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Xl=class extends ql{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=qc([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=qc(e,i,t,a),r=qc(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Zl=class extends ql{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=qc([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=qc(e,i,t,a),r=qc(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Ql=class extends ql{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>eu(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function $l(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new Jl(e);case`ByteLevel`:return new Yl(e);case`BertProcessing`:return new Xl(e);case`RobertaProcessing`:return new Zl(e);case`Sequence`:return new Ql(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var eu=$l,tu=class extends $c{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}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},nu=class extends tu{constructor(e){super(e),this.byte_decoder=vl,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(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},ru=class extends tu{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=tc(e)),e})}},iu=class extends tu{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement,` `);n==0&&r.startsWith(` `)&&(r=r.substring(1)),t.push(r)}return t}},au=class extends tu{constructor(e){super(e),this.suffix=e.suffix??``}decode_chain(e){return e.map((t,n)=>t.replaceAll(this.suffix,n===e.length-1?``:` `))}},ou=class extends tu{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 n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let n=t.filter(e=>e!==this.pad_token).join(``);return this.cleanup&&(n=tc(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},su=class extends tu{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>pu(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},cu=class extends tu{constructor(e){super(e),this.pattern=nc(this.config.pattern)}decode_chain(e){let t=this.config.content??``,n=this.pattern;return n===null?e:e.map(e=>e.replaceAll(n,t))}},lu=class extends tu{decode_chain(e){return[e.join(``)]}},uu=class extends tu{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n<this.start&&e[n]===this.content;++n)t=n+1;let n=e.length;for(let t=0;t<this.stop;++t){let r=e.length-t-1;if(e[r]===this.content)n=r;else break}return e.slice(t,n)})}},du=class extends tu{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],n=[];for(let r of e){let e=null;if(r.length===6&&r.startsWith(`<0x`)&&r.endsWith(`>`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function fu(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new nu(e);case`WordPiece`:return new ru(e);case`Metaspace`:return new iu(e);case`BPEDecoder`:return new au(e);case`CTC`:return new ou(e);case`Sequence`:return new su(e);case`Replace`:return new cu(e);case`Fuse`:return new lu(e);case`Strip`:return new uu(e);case`ByteFallback`:return new du(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var pu=fu,mu=class{constructor(e,t){let n=Zc(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=Zc(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=hl(this.tokenizer.normalizer),this.pre_tokenizer=Ml(this.tokenizer.pre_tokenizer),this.model=Kl(this.tokenizer.model,this.config),this.post_processor=eu(this.tokenizer.post_processor),this.decoder=pu(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=/* @__PURE__ */ new Map;for(let e of this.tokenizer.added_tokens){let t=new $s(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),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 Qs(i),this.splitter_normalized=new Qs(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:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Wc(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=tc(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((e,t)=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=Kc(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t<n.length-1&&(n[t+1]=n[t+1].trimStart()))}),n.flatMap(e=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:qc(r??[],i??[])}}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=/* @__PURE__ */ new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=/* @__PURE__ */ new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(e||!this.added_tokens_map.has(r))&&t.set(r,n)}return t}},hu=Object.defineProperty,gu=(e,t,n)=>t in e?hu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_u=(e,t,n)=>(gu(e,typeof t==`symbol`?t:t+``,n),n),P=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),vu=class{constructor(e,t){this.value=e,this.type=t}};function yu(e){return/\\w/.test(e)}function bu(e){return/[0-9]/.test(e)}function xu(e){return/\\s/.test(e)}var Su=[[`{%`,P.OpenStatement],[`%}`,P.CloseStatement],[`{{`,P.OpenExpression],[`}}`,P.CloseExpression],[`(`,P.OpenParen],[`)`,P.CloseParen],[`{`,P.OpenCurlyBracket],[`}`,P.CloseCurlyBracket],[`[`,P.OpenSquareBracket],[`]`,P.CloseSquareBracket],[`,`,P.Comma],[`.`,P.Dot],[`:`,P.Colon],[`|`,P.Pipe],[`<=`,P.ComparisonBinaryOperator],[`>=`,P.ComparisonBinaryOperator],[`==`,P.ComparisonBinaryOperator],[`!=`,P.ComparisonBinaryOperator],[`<`,P.ComparisonBinaryOperator],[`>`,P.ComparisonBinaryOperator],[`+`,P.AdditiveBinaryOperator],[`-`,P.AdditiveBinaryOperator],[`~`,P.AdditiveBinaryOperator],[`**`,P.ExponentiationBinaryOperator],[`*`,P.MultiplicativeBinaryOperator],[`//`,P.MultiplicativeBinaryOperator],[`/`,P.MultiplicativeBinaryOperator],[`%`,P.MultiplicativeBinaryOperator],[`=`,P.Equals]],Cu=/* @__PURE__ */ new Map([[`n`,`\n`],[`t`,` `],[`r`,`\\r`],[`b`,`\\b`],[`f`,`\\f`],[`v`,`\\v`],[`'`,`'`],[`\"`,`\"`],[`\\\\`,`\\\\`]]);function wu(e,t={}){return e.endsWith(`\n`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \\t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\\n/g,`$1`)),e.replace(/(\\s*){%(-?)\\s*(?:end)?generation\\s*(-?)%}(\\s*)/gs,(e,t,n,r,i)=>(n?``:t)+(r?``:i))}function Tu(e,t={}){let n=[],r=wu(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);)if(r[i]===`\\\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=Cu.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n}else if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`);return t},s=()=>{let e=n.at(-1);e&&e.type===P.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i<r.length&&xu(r[i]);)++i};e:for(;i<r.length;){let e=n.at(-1)?.type;if(e===void 0||e===P.CloseStatement||e===P.CloseExpression||e===P.Comment){let e=``;for(;i<r.length&&(r[i]!==`{`||r[i+1]!==`%`&&r[i+1]!==`{`&&r[i+1]!==`#`);)e+=r[i++];if(e.length>0){n.push(new vu(e,P.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new vu(t,P.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new vu(`{%`,P.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new vu(`{{`,P.OpenExpression)),a=0,i+=3;continue}if(o(xu),r.slice(i,i+3)===`-%}`){n.push(new vu(`%}`,P.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new vu(`}}`,P.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===P.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case P.Identifier:case P.NumericLiteral:case P.StringLiteral:case P.CloseParen:case P.CloseSquareBracket:break;default:{++i;let e=o(bu);if(e.length>0&&r[i]===`.`&&bu(r[i+1])){++i;let t=o(bu);e=`${e}.${t}`}n.push(new vu(`${t}${e}`,e.length>0?P.NumericLiteral:P.UnaryOperator));continue}}}for(let[e,t]of Su)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new vu(e,t)),t===P.OpenExpression?a=0:t===P.OpenCurlyBracket?++a:t===P.CloseCurlyBracket&&--a,i+=e.length;continue e}if(t===`'`||t===`\"`){++i;let e=o(e=>e!==t);n.push(new vu(e,P.StringLiteral)),++i}else if(bu(t)){let e=o(bu);if(n.at(-1)?.type!==P.Dot&&r[i]===`.`&&bu(r[i+1])){++i;let t=o(bu);e=`${e}.${t}`}n.push(new vu(e,P.NumericLiteral))}else if(yu(t)){let e=o(yu);n.push(new vu(e,P.Identifier))}else throw SyntaxError(`Unexpected character: ${t}`)}return n}var Eu=class{type=`Statement`},Du=class extends Eu{constructor(e){super(),this.body=e}type=`Program`},Ou=class extends Eu{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},ku=class extends Eu{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},Au=class extends Eu{type=`Break`},ju=class extends Eu{type=`Continue`},Mu=class extends Eu{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},Nu=class extends Eu{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},Pu=class extends Eu{constructor(e){super(),this.value=e}type=`Comment`},Fu=class extends Eu{type=`Expression`},Iu=class extends Fu{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},Lu=class extends Fu{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},Ru=class extends Fu{constructor(e){super(),this.value=e}type=`Identifier`},zu=class extends Fu{constructor(e){super(),this.value=e}type=`Literal`},Bu=class extends zu{type=`IntegerLiteral`},Vu=class extends zu{type=`FloatLiteral`},Hu=class extends zu{type=`StringLiteral`},Uu=class extends zu{type=`ArrayLiteral`},Wu=class extends zu{type=`TupleLiteral`},Gu=class extends zu{type=`ObjectLiteral`},Ku=class extends Fu{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},qu=class extends Fu{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},Ju=class extends Eu{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Yu=class extends Fu{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},Xu=class extends Fu{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},Zu=class extends Fu{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},Qu=class extends Fu{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},$u=class extends Fu{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},ed=class extends Fu{constructor(e){super(),this.argument=e}type=`SpreadExpression`},td=class extends Fu{constructor(e){super(),this.argument=e}type=`KeywordSpreadExpression`},nd=class extends Eu{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},rd=class extends Fu{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function id(e){let t=new Du([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case P.Comment:return new Pu(e[n++].value);case P.Text:return l();case P.OpenStatement:return u();case P.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===P.OpenStatement&&e[n+1]?.type===P.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new Hu(r(P.Text,`Expected text token`).value)}function u(){if(r(P.OpenStatement,`Expected opening statement token`),e[n].type!==P.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(P.OpenStatement,`Expected {% token`),i(`endif`),r(P.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(P.OpenStatement,`Expected {% token`),i(`endmacro`),r(P.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(P.OpenStatement,`Expected {% token`),i(`endfor`),r(P.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(P.OpenParen)&&(e=te(`parameters`));let t=ue();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=te(`call`);r(P.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(P.OpenStatement,`Expected '{%'`),i(`endcall`),r(P.CloseStatement,`Expected closing statement token`),c=new nd(new Lu(t,l),e,u);break}case`break`:++n,r(P.CloseStatement,`Expected closing statement token`),c=new Au;break;case`continue`:++n,r(P.CloseStatement,`Expected closing statement token`),c=new ju;break;case`filter`:{++n;let e=ue();e instanceof Ru&&o(P.OpenParen)&&(e=w(e)),r(P.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(P.OpenStatement,`Expected '{%'`),i(`endfilter`),r(P.CloseStatement,`Expected '%}'`),c=new Ju(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(P.OpenExpression,`Expected opening expression token`);let e=_();return r(P.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(P.Equals))++n,t=h();else{for(r(P.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(P.OpenStatement,`Expected {% token`),i(`endset`)}return r(P.CloseStatement,`Expected closing statement token`),new Mu(e,t,c)}function p(){let e=_();r(P.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(P.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new Ou(e,t,i)}function m(){let e=ue();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=te(`parameters`);r(P.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new Nu(e,t,n)}function h(e=!1){let t=e?ue:_,r=[t()],i=o(P.Comma);for(;i&&(++n,r.push(t()),o(P.Comma)););return i?new Wu(r):r[0]}function g(){let e=h(!0);if(!(e instanceof Ru||e instanceof Wu))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError(\"Expected `in` keyword following loop variable\");++n;let t=_();r(P.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(P.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new ku(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new rd(t,e,v())):new Yu(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new Ku(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new Ku(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new Zu(r,x())}return t??S()}function S(){let t=C();for(;;){let r;if(c(`not`,`in`))r=new vu(`not in`,P.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(P.ComparisonBinaryOperator))r=e[n++];else break;let i=C();t=new Ku(r,t,i)}return t}function C(){let t=ae();for(;o(P.AdditiveBinaryOperator);){let r=e[n];++n;let i=ae();t=new Ku(r,t,i)}return t}function ee(){let e=ie(ue());return o(P.OpenParen)?w(e):e}function w(e){let t=new Lu(e,te(`call`));return t=ie(t),o(P.OpenParen)&&(t=w(t)),t}function te(e){r(P.OpenParen,`Expected opening parenthesis for arguments list`);let t=ne(e);return r(P.CloseParen,`Expected closing parenthesis for arguments list`),t}function ne(t){let r=[],i=/* @__PURE__ */ new Set,a=!1,s=!1;for(;!o(P.CloseParen);){let c=o(P.ExponentiationBinaryOperator),l=o(P.MultiplicativeBinaryOperator)&&e[n].value===`*`;if(t===`parameters`&&(c||l))throw SyntaxError(`Argument unpacking is not allowed in parameter declarations`);if(c){if(++n,r.push(new td(_())),o(P.Comma)&&++n,!o(P.CloseParen))throw SyntaxError(\"Expected closing parenthesis: `**` must be applied to the final argument\");break}let u;if(l){if(s)throw SyntaxError(\"Only one `*` argument unpacking is allowed\");s=!0,++n,u=new ed(_())}else{if(u=_(),o(P.Equals)){if(++n,!(u instanceof Ru))throw SyntaxError(t===`parameters`?`Expected identifier for parameter declaration`:`Expected identifier for keyword argument`);let e=_();u=new $u(u,e)}if(t===`parameters`){if(!(u instanceof Ru||u instanceof $u))throw SyntaxError(`Expected identifier for parameter declaration`);let e=u instanceof Ru?u.value:u.key.value;if(i.has(e))throw SyntaxError(`Duplicate parameter name: ${e}`);i.add(e)}if(u instanceof $u)a=!0;else if(a)throw SyntaxError(t===`call`?`Positional arguments must come before keyword arguments`:`Non-default argument follows default argument`);else if(s)throw SyntaxError(\"Positional arguments must not follow `*` argument unpacking\")}r.push(u),o(P.Comma)&&++n}return r}function re(){let e=[],t=!1;for(;!o(P.CloseSquareBracket);)o(P.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(P.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new Qu(...e)}return e[0]}function ie(t){for(;o(P.Dot)||o(P.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===P.OpenSquareBracket;if(o)a=re(),r(P.CloseSquareBracket,`Expected closing square bracket`);else if(a=ue(),a.type!==`Identifier`&&a.type!==`IntegerLiteral`)throw SyntaxError(`Expected identifier or integer following dot operator`);t=new Iu(t,a,o)}return t}function ae(){let t=oe();for(;o(P.MultiplicativeBinaryOperator);){let r=e[n++],i=oe();t=new Ku(r,t,i)}return t}function oe(){let t=se();for(;o(P.ExponentiationBinaryOperator);){let r=e[n++],i=se();t=new Ku(r,t,i)}return t}function se(){let e=ce();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=ue();if(!(r instanceof Ru))throw SyntaxError(`Expected identifier for the test`);e=new Xu(e,t,r)}return e}function ce(){let e=le();for(;o(P.Pipe);){++n;let t=ue();if(!(t instanceof Ru))throw SyntaxError(`Expected identifier for the filter`);o(P.OpenParen)&&(t=w(t)),e=new qu(e,t)}return e}function le(){let t=e[n];return t&&(t.type===P.UnaryOperator||t.type===P.AdditiveBinaryOperator)&&(t.value===`-`||t.value===`+`)?new Zu(e[n++],le()):ee()}function ue(){let t=e[n++];switch(t.type){case P.NumericLiteral:{let e=t.value;return e.includes(`.`)?new Vu(Number(e)):new Bu(Number(e))}case P.StringLiteral:{let r=t.value;for(;o(P.StringLiteral);)r+=e[n++].value;return new Hu(r)}case P.Identifier:return new Ru(t.value);case P.OpenParen:{let e=h();return r(P.CloseParen,\"Expected closing parenthesis, got ${tokens[current].type} instead.\"),e}case P.OpenSquareBracket:{let e=[];for(;!o(P.CloseSquareBracket);)e.push(_()),o(P.Comma)&&++n;return++n,new Uu(e)}case P.OpenCurlyBracket:{let e=/* @__PURE__ */ new Map;for(;!o(P.CloseCurlyBracket);){let t=_();r(P.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(P.Comma)&&++n}return++n,new Gu(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n<e.length;)t.body.push(a());return t}function ad(e,t,n=1){if(t===void 0&&(t=e,e=0),n===0)throw Error(`range() step must not be zero`);let r=[];if(n>0)for(let i=e;i<t;i+=n)r.push(i);else for(let i=e;i>t;i+=n)r.push(i);return r}function od(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*o<i*n;o+=r)a.push(e[o]);return a}function sd(e){return e.replace(/\\b\\w/g,e=>e.toUpperCase())}function cd(e){return ld(/* @__PURE__ */ new Date,e)}function ld(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function ud(e){return e.replace(/[.*+?^${}()|[\\]\\\\]/g,`\\\\$&`)}function dd(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(ud(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var fd=class extends Error{},pd=class extends Error{},md=/* @__PURE__ */ new Map,hd=class{type=`RuntimeValue`;value;get builtins(){return md}constructor(e=void 0){this.value=e}__bool__(){return new R(!!this.value)}toString(){return String(this.value)}},F=class extends hd{type=`IntegerValue`},I=class extends hd{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},L=class extends hd{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new B(()=>new L(this.value.toUpperCase()))],[`lower`,new B(()=>new L(this.value.toLowerCase()))],[`strip`,new B(()=>new L(this.value.trim()))],[`title`,new B(()=>new L(sd(this.value)))],[`capitalize`,new B(()=>new L(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new F(this.value.length)],[`rstrip`,new B(()=>new L(this.value.trimEnd()))],[`lstrip`,new B(()=>new L(this.value.trimStart()))],[`startswith`,new B(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof L)return new R(this.value.startsWith(t.value));if(t instanceof z){for(let e of t.value){if(!(e instanceof L))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new R(!0)}return new R(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new B(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof L)return new R(this.value.endsWith(t.value));if(t instanceof z){for(let e of t.value){if(!(e instanceof L))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new R(!0)}return new R(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new B(e=>{let t=e[0]??new Cd;if(!(t instanceof L||t instanceof Cd))throw Error(`sep argument must be a string or null`);let n=e[1]??new F(-1);if(!(n instanceof F))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof Cd){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new z(r.map(e=>new L(e)))})],[`replace`,new B(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof L&&n instanceof L))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new Cd:e[2]:new Cd,!(r instanceof F||r instanceof Cd))throw Error(`replace() count argument must be a number or null`);return new L(dd(this.value,t.value,n.value,r.value))})]])}},R=class extends hd{type=`BooleanValue`},gd=/[\\x7f-\\uffff]/g;function _d(e){return e.replace(gd,e=>`\\\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function vd(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=_d(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`\n`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>vd(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=_d(s));let c=`${s}${l}${vd(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var yd=class extends hd{type=`ObjectValue`;_builtins;__bool__(){return new R(this.value.size>0)}get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`get`,new B(([e,t])=>{if(!(e instanceof L))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Cd})],[`items`,new B(()=>this.items())],[`keys`,new B(()=>this.keys())],[`values`,new B(()=>this.values())],[`dictsort`,new B(e=>{let t=/* @__PURE__ */ new Map,n=e.filter(e=>e instanceof bd?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new R(!1);if(!(r instanceof R))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new L(`key`);if(!(i instanceof L))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new R(!1);if(!(a instanceof R))throw Error(`reverse must be a boolean`);return new z(Array.from(this.value.entries()).map(([e,t])=>new z([new L(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=Md(e.value[n],t.value[n],r.value);return a.value?-o:o}))})]])}items(){return new z(Array.from(this.value.entries()).map(([e,t])=>new z([new L(e),t])))}keys(){return new z(Array.from(this.value.keys()).map(e=>new L(e)))}values(){return new z(Array.from(this.value.values()))}toString(){return vd(this,{},0,!1)}},bd=class extends yd{type=`KeywordArgumentsValue`},xd=class extends hd{type=`NamespaceValue`;toString(){return vd(this,{},0,!1)}},z=class extends hd{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`length`,new F(this.value.length)]])}__bool__(){return new R(this.value.length>0)}toString(){return vd(this,{},0,!1)}},Sd=class extends z{type=`TupleValue`},B=class extends hd{type=`FunctionValue`},Cd=class extends hd{type=`NullValue`},V=class extends hd{type=`UndefinedValue`};function wd(e){let t;if(e instanceof z?t=e.value:e instanceof L&&(t=Array.from(e.value,e=>new L(e))),!t||t.length!==2)throw Error(`namespace expected an object or an iterable of [key, value] pairs`);let[n,r]=t;if(!(n instanceof L))throw Error(`namespace keys must be strings`);return[n,r]}var Td=class{constructor(e){this.parent=e}variables=/* @__PURE__ */ new Map([[`namespace`,new B(e=>{let t=e.slice(),n;if(t.at(-1)instanceof bd&&(n=t.pop()),t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let r=/* @__PURE__ */ new Map;if(t.length===1){let e=t[0];if(e instanceof yd)for(let[t,n]of e.value)r.set(t,n);else if(e instanceof z)for(let t of e.value){let[e,n]=wd(t);r.set(e.value,n)}else throw Error(`'${e.type}' object is not iterable`)}if(n)for(let[e,t]of n.value)r.set(e,t);return new xd(r)})]]);tests=Td.TESTS;set(e,t){return this.declareVariable(e,Ld(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new V}catch{return new V}}},Ed=Td;_u(Ed,`TESTS`,/* @__PURE__ */ new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof B],[`odd`,e=>{if(!(e instanceof F))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof F))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof F||e instanceof I],[`integer`,e=>e instanceof F],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof yd],[`sequence`,e=>e instanceof z||e instanceof yd||e instanceof L],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function Dd(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,ad),e.set(`strftime_now`,cd),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function Od(e){return e instanceof yd||e instanceof xd}function kd(e){return e instanceof F||e instanceof I||e instanceof R}function Ad(e){return e instanceof R?Number(e.value):e.value}function jd(e,t){let n=t.split(`.`),r=e;for(let e of n)if(Od(r))r=r.value.get(e)??new V;else if(r instanceof z){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&t<r.value.length)r=r.value[t];else return new V}else return new V;return r}function Md(e,t,n=!1){if(e instanceof Cd&&t instanceof Cd)return 0;if(e instanceof Cd||t instanceof Cd)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof V&&t instanceof V)return 0;if(e instanceof V||t instanceof V)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(kd(e)&&kd(t)){let n=Ad(e),r=Ad(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type===`StringValue`){let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}throw Error(`Cannot compare type: ${e.type}`)}function Nd(e){if(e.type===`Identifier`)return{name:e.value};let t=e;return{name:t.key.value,defaultValue:t.value}}function Pd(e){return e===`kwargs`||e===`varargs`}function Fd(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=e=>{Pd(e)&&n.add(e)},a=e=>{if(e.type===`Identifier`)i(e.value);else if(e.type===`TupleLiteral`)for(let t of e.value)a(t)},o=e=>{i(Nd(e).name)},s=e=>{for(let t of e){let e=Nd(t);e.defaultValue&&l(e.defaultValue)}},c=e=>{e.type===`CallExpression`&&l(e.args)},l=e=>{if(Array.isArray(e))for(let t of e)l(t);else if(e instanceof Map)for(let[t,n]of e)l(t),l(n);else if(e instanceof Eu)switch(e.type){case`For`:{let t=e;if(a(t.loopvar),t.iterable.type===`SelectExpression`){let e=t.iterable;l(e.lhs),l(t.body),l(t.defaultBlock),l(e.test);return}l(t.iterable),l(t.body),l(t.defaultBlock);return}case`Set`:{let t=e;a(t.assignee),l(t.value),l(t.body);return}case`Macro`:{let t=e;for(let e of t.args)o(e);s(t.args),l(t.body);return}case`CallStatement`:{let t=e;l(t.call);for(let e of t.callerArgs??[])o(e);s(t.callerArgs??[]),l(t.body);return}case`FilterStatement`:{let t=e;l(t.body),c(t.filter);return}case`Identifier`:{let t=e.value;Pd(t)&&!n.has(t)&&r.add(t);return}case`MemberExpression`:{let t=e;l(t.object),t.computed&&l(t.property);return}case`FilterExpression`:{let t=e;l(t.operand),c(t.filter);return}case`TestExpression`:l(e.operand);return;case`SelectExpression`:{let t=e;l(t.test),l(t.lhs);return}case`KeywordArgumentExpression`:l(e.value);return;default:for(let t of Object.values(e))l(t)}};for(let t of e)o(t);return l(t),r}var Id=class{global;constructor(e){this.global=e??new Ed}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new R(n.value==r.value);case`!=`:return new R(n.value!=r.value)}if(n instanceof V||r instanceof V){if(r instanceof V&&[`in`,`not in`].includes(e.operator.value))return new R(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}if(n instanceof Cd||r instanceof Cd)throw Error(`Cannot perform operation on null values`);if(e.operator.value===`~`)return new L(n.value.toString()+r.value.toString());if(e.operator.value===`**`&&kd(n)&&kd(r)){let e=Ad(n),t=Ad(r);if(e===0&&t<0)throw Error(`0.0 cannot be raised to a negative power`);let i=e**t;if(!Number.isFinite(i))throw Error(`Exponentiation result is not a finite real number`);return n instanceof I||r instanceof I||t<0?new I(i):new F(i)}if((n instanceof F||n instanceof I)&&(r instanceof F||r instanceof I)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof I||r instanceof I?new I(a):new F(a)}case`/`:return new I(t/i);case`//`:{let e=Math.floor(t/i);return n instanceof I||r instanceof I?new I(e):new F(e)}case`%`:{let e=t%i;return n instanceof I||r instanceof I?new I(e):new F(e)}case`<`:return new R(t<i);case`>`:return new R(t>i);case`>=`:return new R(t>=i);case`<=`:return new R(t<=i)}}else if(n instanceof z&&r instanceof z)switch(e.operator.value){case`+`:return new z(n.value.concat(r.value))}else if(r instanceof z){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new R(t);case`not in`:return new R(!t)}}if(n instanceof L||r instanceof L)switch(e.operator.value){case`+`:return new L(n.value.toString()+r.value.toString())}if(n instanceof L&&r instanceof L)switch(e.operator.value){case`in`:return new R(r.value.includes(n.value));case`not in`:return new R(!r.value.includes(n.value))}if(n instanceof L&&r instanceof yd)switch(e.operator.value){case`in`:return new R(r.value.has(n.value));case`not in`:return new R(!r.value.has(n.value))}throw SyntaxError(`Unknown operator \"${e.operator.value}\" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=/* @__PURE__ */ new Map,i=(e,t)=>{if(r.has(e))throw Error(`Got multiple values for keyword argument '${e}'`);r.set(e,t)};for(let r of e)if(r.type===`SpreadExpression`){let e=r,i=this.evaluate(e.argument,t);if(!(i instanceof z))throw Error(`Cannot unpack non-iterable type: ${i.type}`);for(let e of i.value)n.push(e)}else r.type!==`KeywordArgumentExpression`&&r.type!==`KeywordSpreadExpression`&&n.push(this.evaluate(r,t));for(let n of e)if(n.type===`KeywordArgumentExpression`){let e=n;i(e.key.value,this.evaluate(e.value,t))}else if(n.type===`KeywordSpreadExpression`){let e=n,r=this.evaluate(e.argument,t);if(!(r instanceof yd))throw Error(`Argument after ** must be a mapping, not ${r.type}`);for(let[e,t]of r.value)i(e,t)}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new L(vd(e,{}));if(e instanceof z)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new F(e.value.length);case`reverse`:return new z(e.value.slice().reverse());case`sort`:return new z(e.value.slice().sort((e,t)=>Md(e,t,!1)));case`join`:return new L(e.value.map(e=>e.value).join(``));case`string`:return new L(vd(e,{},0,!1));case`unique`:{let t=/* @__PURE__ */ new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new z(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof L)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof B)return t.value([],n);if(t instanceof F)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new L(e.value.trim());case`indent`:return new L(e.value.split(`\n`).map((e,t)=>t===0||e.length===0?e:` `+e).join(`\n`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new F(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new I(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof F||e instanceof I)switch(r.value){case`abs`:return e instanceof F?new F(Math.abs(e.value)):new I(Math.abs(e.value));case`int`:return new F(Math.floor(e.value));case`float`:return new I(e.value);case`string`:return new L(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof yd)switch(r.value){case`items`:return new z(Array.from(e.value.entries()).map(([e,t])=>new z([new L(e),t])));case`length`:return new F(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof B?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof R)switch(r.value){case`bool`:return new R(e.value);case`int`:return new F(+!!e.value);case`float`:return new I(+!!e.value);case`string`:return new L(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter \"${r.value}\" to type: ${e.type}`)}if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new Cd;if(!(i instanceof F||i instanceof Cd))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new R(!1);if(!(a instanceof R))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new R(!1);if(!(o instanceof R))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new Cd,c=null;if(s instanceof z||s instanceof Sd){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof L)||!(t instanceof L))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof Cd))throw Error(`If set, separators must be a tuple of two strings`);return new L(vd(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}if(i===`join`){let t;if(e instanceof L)t=Array.from(e.value);else if(e instanceof z)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new L(``);if(!(s instanceof L))throw Error(`separator must be a string`);return new L(t.join(s.value))}if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new F(0):new I(0));if(e instanceof L){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new F(t):new I(t)}if(e instanceof F||e instanceof I)return e;if(e instanceof R)return i===`int`?new F(+!!e.value):new I(+!!e.value);throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`)}if(i===\"default\"){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new L(``),o=t[1]??i.get(`boolean`)??new R(!1);if(!(o instanceof R))throw Error(\"`default` filter flag must be a boolean\");return e instanceof V||o.value&&!e.__bool__().value?a:e}if(e instanceof z){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new R(!1);if(!(a instanceof R))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new R(!1);if(!(o instanceof R))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new Cd;if(!(s instanceof L||s instanceof F||s instanceof Cd))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof Cd?e:jd(e,s instanceof F?String(s.value):s.value);return new z(e.value.slice().sort((e,t)=>{let n=Md(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!Od(e)))throw Error(`\\`${i}\\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \\`${i}\\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new z(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof L))throw Error(`attribute must be a string`);let r=t.get(`default`);return new z(e.value.map(e=>{if(!Od(e))throw Error(`items in map must be an object`);let t=jd(e,n.value);return t instanceof V?r??new V:t}))}throw Error(\"`map` expressions without `attribute` set are not currently supported.\")}}throw Error(`Unknown ArrayValue filter: ${i}`)}if(e instanceof L){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new F(4);if(!(a instanceof F))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new R(!1),s=t.at(2)??i.get(`blank`)??new R(!1),c=e.value.split(`\n`),l=` `.repeat(a.value);return new L(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(`\n`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof B))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new bd(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}if(e instanceof yd){let t=e.builtins.get(i);if(t&&t instanceof B){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new bd(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}throw Error(`Cannot apply filter \"${i}\" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new R(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new V}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new R(!n.value);case`+`:case`-`:{let t=e.operator.value===`-`?-1:1;if(n instanceof F||n instanceof I||n instanceof R){let e=t*(n instanceof R?+!!n.value:n.value);return n instanceof I?new I(e):new F(e)}throw SyntaxError(`Unknown operator \"${e.operator.value}\" for ${n.type}`)}default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new L(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new bd(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof z||e instanceof L))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof F||r instanceof V))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof F||i instanceof V))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof F||a instanceof V))throw Error(`Slice step must be numeric or undefined`);return e instanceof z?new z(od(e.value,r.value,i.value,a.value)):new L(od(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=e.property.type===`IntegerLiteral`?new F(e.property.value):new L(e.property.value);let i;if(Od(n)){if(!(r instanceof L))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??(n instanceof yd?n.builtins.get(r.value):void 0)}else if(n instanceof z||n instanceof L){if(r instanceof F)i=n.value.at(r.value),n instanceof L&&(i=new L(n.value.at(r.value)));else if(r instanceof L)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`)}else{if(!(r instanceof L))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof hd?i:new V}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof z))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;e<r.value.length;++e){let n=r.value[e];if(n.type!==`Identifier`)throw Error(`Cannot unpack to non-identifier in set: ${n.type}`);t.setVariable(n.value,i[e])}}else if(e.assignee.type===`MemberExpression`){let r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof xd))throw Error(`cannot assign attribute on non-namespace object`);if(r.property.type!==`Identifier`)throw Error(`Cannot assign to member with non-identifier property`);i.value.set(r.property.value,n)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Cd}evaluateIf(e,t){let n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let n=new Ed(t),r,i;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=this.evaluate(t.lhs,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof z||i instanceof yd))throw Error(`Expected iterable or object type in for loop: got ${i.type}`);i instanceof yd&&(i=i.keys());let a=[],o=[];for(let t=0;t<i.value.length;++t){let s=new Ed(n),c=i.value[t],l;if(e.loopvar.type===`Identifier`)l=t=>t.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r<t.value.length;++r){if(t.value[r].type!==`Identifier`)throw Error(`Cannot unpack non-identifier type: ${t.value[r].type}`);e.setVariable(t.value[r].value,n.value[r])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);r&&(l(s),!this.evaluate(r,s).__bool__().value)||(a.push(c),o.push(l))}let s=``,c=!0;for(let t=0;t<a.length;++t){let r=/* @__PURE__ */ new Map([[`index`,new F(t+1)],[`index0`,new F(t)],[`revindex`,new F(a.length-t)],[`revindex0`,new F(a.length-t-1)],[`first`,new R(t===0)],[`last`,new R(t===a.length-1)],[`length`,new F(a.length)],[`previtem`,t>0?a[t-1]:new V],[`nextitem`,t<a.length-1?a[t+1]:new V]]);n.setVariable(`loop`,new yd(r)),o[t](n);try{let t=this.evaluateBlock(e.body,n);s+=t.value}catch(e){if(e instanceof pd)continue;if(e instanceof fd)break;throw e}c=!1}if(c){let t=this.evaluateBlock(e.defaultBlock,n);s+=t.value}return new L(s)}bindMacroArguments(e,t,n,r,i){let a=r.slice(),o=/* @__PURE__ */ new Map;a.at(-1)instanceof bd&&(o=new Map(a.pop().value));let s=[];for(let e=0;e<t.length;++e){let{name:n,defaultValue:r}=Nd(t[e]),c=a[e];c===void 0&&o.has(n)&&(c=o.get(n),o.delete(n)),c===void 0&&r!==void 0&&s.push([n,r]),i.setVariable(n,c??new V)}if(n.has(`kwargs`))i.setVariable(`kwargs`,new yd(o));else if(o.size>0)throw Error(`macro ${e} takes no keyword argument '${o.keys().next().value}'`);if(n.has(`varargs`))i.setVariable(`varargs`,new z(a.slice(t.length)));else if(a.length>t.length)throw Error(`macro ${e} takes not more than ${t.length} argument(s)`);for(let[e,t]of s)i.setVariable(e,this.evaluate(t,i))}evaluateMacro(e,t){let n=Fd(e.args,e.body);return t.setVariable(e.name.value,new B((t,r)=>{let i=new Ed(r);return this.bindMacroArguments(`'${e.name.value}'`,e.args,n,t,i),this.evaluateBlock(e.body,i)})),new Cd}evaluateCallStatement(e,t){let n=e.callerArgs??[],r=Fd(n,e.body),i=new B(i=>{let a=new Ed(t);return this.bindMacroArguments(`None`,n,r,i,a),this.evaluateBlock(e.body,a)}),[a,o]=this.evaluateArguments(e.call.args,t);a.push(new bd(o));let s=this.evaluate(e.call.callee,t);if(s.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${s.type}`);let c=new Ed(t);return c.setVariable(`caller`,i),s.value(a,c)}evaluateFilterStatement(e,t){let n=this.evaluateBlock(e.body,t);return this.applyFilter(n,e.filter,t)}evaluate(e,t){if(!e)return new V;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 fd;case`Continue`:throw new pd;case`IntegerLiteral`:return new F(e.value);case`FloatLiteral`:return new I(e.value);case`StringLiteral`:return new L(e.value);case`ArrayLiteral`:return new z(e.value.map(e=>this.evaluate(e,t)));case`TupleLiteral`:return new Sd(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=/* @__PURE__ */ new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof L))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new yd(n)}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 Cd;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function Ld(e){switch(typeof e){case`number`:return Number.isInteger(e)?new F(e):new I(e);case`string`:return new L(e);case`boolean`:return new R(e);case`undefined`:return new V;case`object`:return e===null?new Cd:Array.isArray(e)?new z(e.map(Ld)):new yd(new Map(Object.entries(e).map(([e,t])=>[e,Ld(t)])));case`function`:return new B((t,n)=>Ld(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var Rd=`\n`,zd=`{%- `,Bd=` -%}`,Vd=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function Hd(e){switch(e.operator.type){case`ExponentiationBinaryOperator`:return Vd.EXPONENTIATION;case`MultiplicativeBinaryOperator`:return Vd.MULTIPLICATIVE;case`AdditiveBinaryOperator`:return Vd.ADDITIVE;case`ComparisonBinaryOperator`:return Vd.COMPARISON;case`Identifier`:return e.operator.value===`and`?Vd.LOGICAL_AND:e.operator.value===`in`||e.operator.value===`not in`?Vd.COMPARISON:Vd.LOGICAL_OR}return Vd.LOGICAL_OR}function Ud(e){switch(e.type){case`SelectExpression`:case`Ternary`:return Vd.CONDITIONAL;case`BinaryExpression`:return Hd(e);case`UnaryExpression`:return e.operator.value===`not`?Vd.LOGICAL_NOT:Vd.UNARY_SIGN;case`TestExpression`:return Vd.TEST;case`FilterExpression`:return Vd.FILTER;default:return Vd.ATOM}}function Wd(e,t){let n=nf(e);return Ud(e)<t?`(${n})`:n}function Gd(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return qd(e.body,0,n).replace(/\\n$/,``)}function Kd(...e){return zd+e.join(` `)+Bd}function qd(e,t,n){return e.map(e=>Yd(e,t,n)).join(Rd)}function Jd(e){return e.map(e=>nf(e)).join(`, `)}function Yd(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return qd(e.body,t,n);case`If`:return Xd(e,t,n);case`For`:return Zd(e,t,n);case`Set`:return Qd(e,t,n);case`Macro`:return $d(e,t,n);case`Break`:return r+Kd(`break`);case`Continue`:return r+Kd(`continue`);case`CallStatement`:return ef(e,t,n);case`FilterStatement`:return tf(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+nf(e)+` -}}`}}function Xd(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+Kd(`if`,nf(i[0].test))+Rd+qd(i[0].body,t+1,n);for(let e=1;e<i.length;++e)o+=Rd+r+Kd(`elif`,nf(i[e].test))+Rd+qd(i[e].body,t+1,n);return a&&a.alternate.length>0&&(o+=Rd+r+Kd(`else`)+Rd+qd(a.alternate,t+1,n)),o+=Rd+r+Kd(`endif`),o}function Zd(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${nf(t.lhs)} if ${nf(t.test)}`}else i=nf(e.iterable);let a=r+Kd(`for`,nf(e.loopvar),`in`,i)+Rd+qd(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=Rd+r+Kd(`else`)+Rd+qd(e.defaultBlock,t+1,n)),a+=Rd+r+Kd(`endfor`),a}function Qd(e,t,n){let r=n.repeat(t),i=nf(e.assignee),a=e.value?nf(e.value):``,o=r+Kd(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+Rd+qd(e.body,t+1,n)+Rd+r+Kd(`endset`)}function $d(e,t,n){let r=n.repeat(t),i=Jd(e.args);return r+Kd(`macro`,`${e.name.value}(${i})`)+Rd+qd(e.body,t+1,n)+Rd+r+Kd(`endmacro`)}function ef(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${Jd(e.callerArgs)})`:``,a=nf(e.call),o=r+Kd(`call${i}`,a)+Rd;return o+=qd(e.body,t+1,n)+Rd,o+=r+Kd(`endcall`),o}function tf(e,t,n){let r=n.repeat(t),i=r+Kd(`filter`,e.filter.type===`Identifier`?e.filter.value:nf(e.filter))+Rd;return i+=qd(e.body,t+1,n)+Rd,i+=r+Kd(`endfilter`),i}function nf(e){switch(e.type){case`SpreadExpression`:return`*${nf(e.argument)}`;case`KeywordSpreadExpression`:return`**${nf(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:{let t=e.value;return Object.is(t,-0)?`-0.0`:t%1==0?t.toFixed(1):t.toString()}case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let t=e,n=Hd(t),r=Wd(t.left,n),i=Wd(t.right,n+1);return`${r} ${t.operator.value} ${i}`}case`UnaryExpression`:{let t=e,n=t.argument.type===`UnaryExpression`?Ud(t):Vd.ATOM;return t.operator.value+(t.operator.value===`not`?` `:``)+Wd(t.argument,n)}case`CallExpression`:{let t=e,n=Jd(t.args);return`${nf(t.callee)}(${n})`}case`MemberExpression`:{let t=e,n=Wd(t.object,Vd.ATOM),r=nf(t.property);return!t.computed&&t.property.type!==`Identifier`&&t.property.type!==`IntegerLiteral`&&(r=`(${r})`),t.computed?`${n}[${r}]`:`${n}.${r}`}case`FilterExpression`:{let t=e,n=Wd(t.operand,Vd.FILTER);return t.filter.type===`CallExpression`?`${n} | ${nf(t.filter)}`:`${n} | ${t.filter.value}`}case`SelectExpression`:{let t=e;return`${Wd(t.lhs,Vd.LOGICAL_OR)} if ${Wd(t.test,Vd.LOGICAL_OR)}`}case`TestExpression`:{let t=e;return`${Wd(t.operand,Vd.TEST)} is${t.negate?` not`:``} ${t.test.value}`}case`ArrayLiteral`:case`TupleLiteral`:{let t=Jd(e.value),n=e.type===`ArrayLiteral`?`[]`:`()`;return`${n[0]}${t}${n[1]}`}case`ObjectLiteral`:return`{${Array.from(e.value.entries()).map(([e,t])=>`${nf(e)}: ${nf(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?nf(t.start):``}:${t.stop?nf(t.stop):``}${t.step?`:${nf(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${nf(t.value)}`}case`Ternary`:{let t=e;return`${Wd(t.trueExpr,Vd.LOGICAL_OR)} if ${Wd(t.condition,Vd.LOGICAL_OR)} else ${Wd(t.falseExpr,Vd.CONDITIONAL)}`}default:throw Error(`Unknown expression type: ${e.type}`)}}var rf=class{parsed;constructor(e){let t=Tu(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=id(t)}render(e){let t=new Ed;if(Dd(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new Id(t).run(this.parsed).value}format(e){return Gd(this.parsed,e?.indent||` `)}},af={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`},of=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=ds.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=ds.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=ds.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,af[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await ds.promises.readFile(this.filePath)).buffer}async blob(){let e=await ds.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await ds.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},sf=class{constructor(e){this._mt=/* @__PURE__ */ 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(j.IS_CRYPTO_AVAILABLE){let t=/* @__PURE__ */ new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0}Number.isSafeInteger(e)&&(e=Math.abs(e));let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t|0);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(0x6c078965,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,0x5d588b65))-i>>>0;t[0]=0x80000000,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&0x80000000|e[(t+1)%624]&0x7fffffff;e[t]=(e[(t+397)%624]^n>>>1^(n&1?0x9908b0df:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&0x9d2c5680,t^=t<<15&0xefc60000,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/0x20000000000000}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[cf(this._random_fn,t)]}};function cf(e,t){let n=0;for(let e=0;e<t.length;++e)n+=t[e];let r=e()*n;for(let e=0;e<t.length;++e)if(r-=t[e],r<0)return e;return t.length-1}var lf=new sf,uf=Object.freeze({Random:sf,seed:lf.seed.bind(lf),random:lf.random.bind(lf),gauss:lf.gauss.bind(lf),shuffle:lf.shuffle.bind(lf),choices:lf.choices.bind(lf)}),df=e=>cf(uf.random,e),ff=new sf,pf=class{constructor(e){this.path=e}async match(e){let t=new of(fs.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=fs.join(this.path,e),i=r+`.tmp.${j.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${ff._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await ds.promises.mkdir(fs.dirname(r),{recursive:!0});let s=ds.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{t?n(t):e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await ds.promises.rename(i,r)}catch(e){try{await ds.promises.unlink(i)}catch{}throw e}}async delete(e){let t=fs.join(this.path,e);try{return await ds.promises.unlink(t),!0}catch{return!1}}},mf={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`},hf=100,gf=/^(\\b[\\w\\-.]+\\b\\/)?\\b[\\w\\-.]{1,96}\\b$/;function _f(...e){return e=e.map((t,n)=>(n&&(t=t.replace(/* @__PURE__ */ RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(/* @__PURE__ */ RegExp(`/$`),``)),t)),e.join(`/`)}function vf(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function yf(e){return!(!gf.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function bf(e,t={},...n){return JSON.stringify([e,t.revision??`main`,t.cache_dir??null,t.local_files_only??!1,...n])}var xf=class extends Error{constructor(e,{status:t=null}={}){super(e),this.name=`ModelFileNotFoundError`,this.status=t}},Sf=/* @__PURE__ */ new Set([401,403,404]);function Cf(e,t,n){if(!n)return null;let r=`${mf[e]??`Error (${e}) occurred while trying to load file`}: \"${t}\".`;throw Sf.has(e)?new xf(r,{status:e}):Error(r)}async function wf(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&N.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function Tf(e){return vf(e,[`blob:`])}function Ef(e,{allowUnresolved:t=!1}={}){let n;if(typeof location<`u`&&location.href)n=location.href;else if(cs!==void 0&&self.location.href)n=self.location.href;else return e;try{return new URL(e,n).href}catch(n){if(!t)throw n;return e}}var Df=`SHA-256`,Of=`experimental_transformers-hash-cache`,kf=e=>({algorithm:Df,value:e}),Af=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Of),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let e=await(await navigator.crossOriginStorage.requestFileHandle(kf(t))).getFile();return new Response(e,{headers:{\"Content-Length\":String(e.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(kf(t),{create:!0,origins:`*`})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(Df,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function jf(e=null){let t=null;if(M.useCustomCache){if(!M.customCache)throw Error(\"`env.useCustomCache=true`, but `env.customCache` is not defined.\");if(!M.customCache.match||!M.customCache.put)throw Error(\"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\");t=M.customCache}if(!t&&M.experimental_useCrossOriginStorage&&Af.isAvailable()&&(t=new Af),!t&&M.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(M.cacheKey)}catch(e){N.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&M.useFSCache){if(!j.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new pf(e??M.cacheDir)}return t}async function Mf(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Nf=new class{#e;#t;constructor(e){this.#e=e,this.#t=/* @__PURE__ */ new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function Pf(e,t){let n=Nf.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Nf.delete(e),Promise.reject(t)));return Nf.put(e,r),r}async function Ff(e){if(!vf(e,[`http:`,`https:`]))return null;let t=zf(e);return t.set(`Range`,`bytes=0-0`),M.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function If(e,t,n={}){return Pf(bf(e,n,t),()=>Lf(e,t,n))}async function Lf(e,t,n){let r=await jf(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=Bf(e,t,n,r),c=await Vf(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(M.allowLocalModels&&!vf(i,[`http:`,`https:`]))try{let e=await Rf(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(M.allowRemoteModels&&!n.local_files_only&&s){let e=await Ff(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \\d+-\\d+\\/(\\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}e&&e.status!==404&&e.status!==416&&Cf(e.status,a,!0)}return{exists:!1,fromCache:!1}}async function Rf(e){return M.useFS&&!vf(e,[`http:`,`https:`,`blob:`])?new of(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):M.fetch(e,{headers:zf(e)})}function zf(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!process.env?.TESTING_REMOTELY,r=M.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),vf(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function Bf(e,t,n={},r=null){let i=n.revision??`main`,a=_f(e,t),o=yf(e),s=o?_f(M.localModelPath,a):a,c=_f(M.remoteHost,M.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof pf?i===`main`?a:_f(e,i,t):c,validModelId:o}}async function Vf(e,t,n){if(e)return await Mf(e,t,n)}async function Hf(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0&&!(typeof Cache<`u`&&n instanceof Cache&&!vf(Ef(r,{allowUnresolved:!0}),[`http:`,`https:`]))){if(!a){let a=o.progress_callback?n=>Hs(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}else if(typeof i!=`string`){let e=new Headers(i.headers);e.set(`content-length`,a.byteLength.toString()),await n.put(r,new Response(a,{headers:e})).catch(e=>{N.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Uf(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=Bf(e,t,r,a),d,f=!1,p;p=await Vf(a,s,l);let m=p!==void 0;if(m)d=l;else{if(M.allowLocalModels){if(!vf(o,[`http:`,`https:`]))try{p=await Rf(s),d=s}catch(e){N.warn(`Unable to load from local path \"${s}\": \"${e}\"`)}else if(r.local_files_only)throw Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${o}.`);else if(!M.allowRemoteModels)throw Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!M.allowRemoteModels){if(n)throw new xf(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${s}\".`);return null}if(!u)throw new xf(`Local file missing at \"${s}\" and download aborted due to invalid model ID \"${e}\".`);if(p=await Rf(c),p.status!==200)return Cf(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}Hs(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(j.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`){if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),Hs(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await If(e,t,r);n.size&&(i=n.size)}catch{}n=await wf(p,n=>{Hs(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}}h=n}if(f&&d&&typeof p!=`string`&&await Hf(e,t,a,d,p,h,r),j.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;Hs(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(Hs(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!j.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof of)return p.filePath;let g=await a?.match(d);if(g instanceof of)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}var Wf=/* @__PURE__ */ new Map;async function Gf(e,t,n=!0,r={},i=!1){if(!M.allowLocalModels){if(r.local_files_only)throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\");if(!M.allowRemoteModels)throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")}let a=bf(e,r,t,n,i),{progress_callback:o}=r,s=o instanceof Us?o.loads:Wf,c=s.get(a);return c||(Hs(o,{status:`initiate`,name:e,file:t}),c=jf(r.cache_dir).then(a=>Uf(e,t,n,r,i,a)),s===Wf&&(c=c.finally(()=>Wf.delete(a))),s.set(a,c)),await c}async function Kf(e,t,n=!0,r={}){let i=await Gf(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function qf(e,t,n=!0,r={}){let i=await Kf(e,t,n,r);return i===null?{}:JSON.parse(i)}function Jf(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o<i;++o)for(let i=0;i<a;++i){let s=o*a+i,p=(i+.5)/c-.5,m=(o+.5)/l-.5,h=Math.floor(p),g=Math.floor(m),_=Math.min(h+1,r-1),v=Math.min(g+1,n-1);h=Math.max(h,0),g=Math.max(g,0);let y=p-h,b=m-g,x=(1-y)*(1-b),S=y*(1-b),C=(1-y)*b,ee=y*b,w=g*r,te=v*r,ne=w+h,re=w+_,ie=te+h,ae=te+_;for(let n=0;n<t;++n){let t=n*d;u[n*f+s]=x*e[t+ne]+S*e[t+re]+C*e[t+ie]+ee*e[t+ae]}}return u}function Yf(e,t,n){let r=Array(n.length),i=Array(n.length);for(let e=n.length-1,a=1;e>=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n<e.length;++n){let r=0;for(let e=t.length-1,i=n;e>=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function Xf(e){let t=$f(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function Zf(e){let t=$f(e)[0],n=0;for(let r=0;r<e.length;++r)n+=Math.exp(e[r]-t);let r=Math.log(n);return e.map(e=>e-t-r)}function Qf(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}function $f(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]>t&&(t=e[r],n=r);return[t,n]}function ep(e){return e>0&&!(e&e-1)}var tp=class{constructor(e){if(this.size=e|0,this.size<=1||!ep(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;e<this.table.length;e+=2){let t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){let n=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let n=t||Array(e.length>>>1);for(let t=0;t<e.length;t+=2)n[t>>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t<n.length;t+=2)n[t]=e[t>>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleTransform2(t,e,o,n,i)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleTransform4(t,e,o,r,i,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o<r;o+=a){let r=o+t-1;for(let a=o,s=0;a<r;a+=2,s+=i){let r=a,i=r+t,o=i+t,c=o+t,u=e[r],d=e[r+1],f=e[i],p=e[i+1],m=e[o],h=e[o+1],g=e[c],_=e[c+1],v=l[s],y=n*l[s+1],b=f*v-p*y,x=f*y+p*v,S=l[2*s],C=n*l[2*s+1],ee=m*S-h*C,w=m*C+h*S,te=l[3*s],ne=n*l[3*s+1],re=g*te-_*ne,ie=g*ne+_*te,ae=u+ee,oe=d+w,se=u-ee,ce=d-w,le=b+re,ue=x+ie,T=n*(b-re),de=n*(x-ie);e[r]=ae+le,e[r+1]=oe+ue,e[i]=se+de,e[i+1]=ce-T,e[o]=ae-le,e[o+1]=oe-ue,e[c]=se-de,e[c+1]=ce+T}}}}_singleTransform2(e,t,n,r,i){let a=e[r],o=e[r+1],s=e[r+i],c=e[r+i+1];t[n]=a+s,t[n+1]=o+c,t[n+2]=a-s,t[n+3]=o-c}_singleTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+1],u=e[r+i],d=e[r+i+1],f=e[r+o],p=e[r+o+1],m=e[r+s],h=e[r+s+1],g=c+f,_=l+p,v=c-f,y=l-p,b=u+m,x=d+h,S=a*(u-m),C=a*(d-h);t[n]=g+b,t[n+1]=_+x,t[n+2]=v+C,t[n+3]=y-S,t[n+4]=g-b,t[n+5]=_-x,t[n+6]=v-C,t[n+7]=y+S}_realTransform4(e,t,n){let r=this._csize,i=1<<this._width,a=r/i<<1,o,s,c=this._bitrev;if(a===4)for(o=0,s=0;o<r;o+=a,++s){let n=c[s];this._singleRealTransform2(t,e,o,n>>>1,i>>>1)}else for(o=0,s=0;o<r;o+=a,++s){let r=c[s];this._singleRealTransform4(t,e,o,r>>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o<r;o+=a)for(let r=0,a=0;r<=c;r+=2,a+=i){let i=o+r,u=i+s,d=u+s,f=d+s,p=e[i],m=e[i+1],h=e[u],g=e[u+1],_=e[d],v=e[d+1],y=e[f],b=e[f+1],x=p,S=m,C=l[a],ee=n*l[a+1],w=h*C-g*ee,te=h*ee+g*C,ne=l[2*a],re=n*l[2*a+1],ie=_*ne-v*re,ae=_*re+v*ne,oe=l[3*a],se=n*l[3*a+1],ce=y*oe-b*se,le=y*se+b*oe,ue=x+ie,T=S+ae,de=x-ie,fe=S-ae,pe=w+ce,me=te+le,he=n*(w-ce),ge=n*(te-le);if(e[i]=ue+pe,e[i+1]=T+me,e[u]=de+ge,e[u+1]=fe-he,r===0){e[d]=ue-pe,e[d+1]=T-me;continue}if(r===c)continue;let _e=o+s-r,ve=o+t-r;e[_e]=de-n*ge,e[_e+1]=-fe-n*he,e[ve]=ue-n*pe,e[ve+1]=-T+n*me}}let u=r>>>1;for(let t=2;t<u;t+=2)e[r-t]=e[t],e[r-t+1]=-e[t+1]}_singleRealTransform2(e,t,n,r,i){let a=e[r],o=e[r+i];t[n]=a+o,t[n+1]=0,t[n+2]=a-o,t[n+3]=0}_singleRealTransform4(e,t,n,r,i,a){let o=i*2,s=i*3,c=e[r],l=e[r+i],u=e[r+o],d=e[r+s],f=c+u,p=c-u,m=l+d,h=a*(l-d);t[n]=f+m,t[n+1]=0,t[n+2]=p,t[n+3]=-h,t[n+4]=f-m,t[n+5]=0,t[n+6]=p,t[n+7]=h}},np=class{constructor(e){let t=2*(e-1),n=2*(2*e-1),r=2**Math.ceil(Math.log2(n));this.bufferSize=r,this._a=t;let i=new Float64Array(n),a=new Float64Array(r);this._chirpBuffer=new Float64Array(r),this._buffer1=new Float64Array(r),this._buffer2=new Float64Array(r),this._outBuffer1=new Float64Array(r),this._outBuffer2=new Float64Array(r);let o=-2*Math.PI/e,s=Math.cos(o),c=Math.sin(o);for(let t=0;t<n>>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new tp(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e<c.length;e+=2){let n=e+1,i=t[e>>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e<c.length;e+=2){let n=e+1;r[e]=t[e]*c[e]-t[n]*c[n],r[n]=t[e]*c[n]+t[n]*c[e]}this._f.transform(a,r);for(let e=0;e<s.length;e+=2){let t=e+1;i[e]=a[e]*s[e]-a[t]*s[t],i[t]=a[e]*s[t]+a[t]*s[e]}this._f.inverseTransform(o,i);for(let t=0;t<o.length;t+=2){let n=o[t+l],r=o[t+l+1],i=c[t],a=c[t+1];e[t]=n*i-r*a,e[t+1]=n*a+r*i}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},rp=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=ep(e),this.isPowerOfTwo?(this.fft=new tp(e),this.outputBufferSize=2*e):(this.fft=new np(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function ip(e,t){if(t%2==0||t<=0)throw Error(`Window size must be a positive odd number`);let n=new e.constructor(e.length),r=new e.constructor(t),i=Math.floor(t/2);for(let t=0;t<e.length;++t){let a=0;for(let n=-i;n<=i;++n){let i=t+n;i<0?i=Math.abs(i):i>=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function ap(e,t){let n=10**t;return Math.round(e*n)/n}function op(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function sp(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t<r[1];++t)for(let n=1;n<r[0];++n){let r=i[n-1][t-1],o=i[n-1][t],s=i[n][t-1],c,l;r<o&&r<s?(c=r,l=0):o<r&&o<s?(c=o,l=1):(c=s,l=2),i[n][t]=e[n-1][t-1]+c,a[n][t]=l}for(let e=0;e<r[1];++e)a[0][e]=2;for(let e=0;e<r[0];++e)a[e][0]=1;let o=t,s=n,c=[],l=[];for(;o>0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var cp=/* @__PURE__ */ (function(){let e=null;return function(t){if(!e){e=/* @__PURE__ */ new Float32Array(65536);let t=/* @__PURE__ */ new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;++t){let i=0,a=(t&32768)<<16,o=(t&31744)>>10,s=t&1023;if(o===31)i=a|0x7f800000|s<<13;else if(o===0){if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;e<n;++e)i[e]=r[t[e]];return i}})(),lp={};async function up(e){let t=e.split(`/`).pop(),n;try{if(n=await jf(),n){let t=await n.match(e);if(t)return t}}catch(e){N.warn(`Failed to load ${t} from cache:`,e)}let r=await M.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){N.warn(`Failed to cache ${t}:`,e)}return r}async function dp(e){let t=await up(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return N.warn(`Failed to read WASM binary:`,e),null}}async function fp(e){if(j.IS_SERVICE_WORKER_ENV||j.IS_CHROME_AVAILABLE)return e;let t=await up(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return N.warn(`Failed to read WASM factory:`,e),null}}var pp=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},\"webnn-npu\":{name:`webnn`,deviceType:`npu`},\"webnn-gpu\":{name:`webnn`,deviceType:`gpu`},\"webnn-cpu\":{name:`webnn`,deviceType:`cpu`}});function mp(e){return e<=Rs.DEBUG?0:e<=Rs.INFO?2:e<=Rs.WARNING||e<=Rs.ERROR?3:4}var hp={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},gp=[],_p,vp,yp=/* @__PURE__ */ Symbol.for(`onnxruntime`);if(yp in globalThis)vp=globalThis[yp];else if(j.IS_NODE_ENV){switch(vp=lp,process.platform){case`win32`:gp.push(`dml`);break;case`linux`:process.arch===`x64`&&gp.push(`cuda`);break;case`darwin`:gp.push(`coreml`)}gp.push(`webgpu`),gp.push(`cpu`),_p=[`cpu`]}else vp=yr,j.IS_WEBNN_AVAILABLE&&gp.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),j.IS_WEBGPU_AVAILABLE&&gp.push(`webgpu`),gp.push(`wasm`),_p=[`wasm`];function bp(){return[...gp]}var xp=vp.InferenceSession;function Sp(e=null){if(!e)return _p;switch(e){case`auto`:return gp;case`gpu`:return gp.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(gp.includes(e))return[pp[e]??e];throw Error(`Unsupported device: \"${e}\". Should be one of: ${gp.join(`, `)}.`)}var Cp=Promise.resolve(),wp=null;async function Tp(){if(wp)return wp;if(!(M.useWasmCache&&typeof Ap?.wasm?.wasmPaths==`object`&&Ap?.wasm?.wasmPaths?.wasm&&Ap?.wasm?.wasmPaths?.mjs)){if(j.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return wp=Promise.resolve(),wp}return wp=(async()=>{let e=Ap.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!Tf(e.wasm)?(async()=>{try{let n=await dp(Ef(e.wasm));n&&(Ap.wasm.wasmBinary=n,t=!0)}catch(e){N.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!Tf(e.mjs)?(async()=>{try{let t=await fp(Ef(e.mjs));t&&(Ap.wasm.wasmPaths.mjs=t)}catch(e){N.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Ap.wasm.wasmPaths.mjs=e.mjs)})(),wp}async function Ep(e,t,n){await Tp();let r=mp(M.logLevel??Rs.WARNING),i=()=>xp.create(e,{logSeverityLevel:r,...t}),a=await(j.IS_WEB_ENV?Cp=Cp.then(i):i());return a.config=n,a}var Dp=Promise.resolve();async function Op(e,t){let n=()=>e.run(t);return j.IS_WEB_ENV?Dp=Dp.then(n):n()}function kp(e){return e instanceof vp.Tensor}var Ap=vp?.env;function jp(){return Ap?.wasm?.proxy}if(Ap){let e=function(e){Ap.logLevel=hp[mp(e)]};if(Ap.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Ap.versions?.web&&!Ap.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ap.versions.web}/dist/`,t=`.asyncify`;j.IS_SAFARI_BELOW_26&&!j.IS_WEBGPU_AVAILABLE&&(t=``),Ap.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${t}.mjs`,wasm:`${e}ort-wasm-simd-threaded${t}.wasm`}}Ap.wasm.proxy=!1}Ap.webgpu&&(Ap.webgpu.powerPreference=`high-performance`),e(M.logLevel??Rs.WARNING),M.backends.onnx={...Ap,setLogLevel:e,getSupportedDevices:bp}}var Mp=async(e,t,n)=>{let r=await Ep(new Uint8Array(e),t);return(async e=>{let t=jp(),i=Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])),a=await Op(r,i);return Array.isArray(n)?n.map(e=>new H(a[e])):new H(a[n])})},Np=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=Mp([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||=Mp([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||=Mp([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||=Mp([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||=Mp([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||=Mp([8,9,58,93,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=Mp([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||=Mp([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}},Pp=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`}),Fp=j.IS_NODE_ENV?`cpu`:`wasm`;function Ip(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for \"${t}\". Using the default device (${Fp}).`),Fp):Fp}var Lp=/* @__PURE__ */ (function(){let e;return async function(){if(e===void 0){if(!j.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}}return e}})(),Rp=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`,q2:`q2`,q2f16:`q2f16`,q1:`q1`,q1f16:`q1f16`}),zp=Rp.fp32,Bp=Object.freeze({[Pp.wasm]:Rp.q8}),Vp=Object.freeze({[Rp.fp32]:``,[Rp.fp16]:`_fp16`,[Rp.int8]:`_int8`,[Rp.uint8]:`_uint8`,[Rp.q8]:`_quantized`,[Rp.q4]:`_q4`,[Rp.q2]:`_q2`,[Rp.q1]:`_q1`,[Rp.q4f16]:`_q4f16`,[Rp.q2f16]:`_q2f16`,[Rp.q1f16]:`_q1f16`,[Rp.bnb4]:`_bnb4`});function Hp(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===Rp.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==Rp.auto&&Rp.hasOwnProperty(e))return e}s=Bp[n]??zp}else s=a&&Rp.hasOwnProperty(a)?a:Bp[n]??zp;return o&&i&&i(`dtype not specified for \"${t}\". Using the default dtype (${s}) for this device (${n}).`),s}var Up=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}),H=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return this.ort_tensor=kp(e[0])?e[0]:new ss(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r<e;++r)yield this._subarray(r,n,t)}else yield*this.data}_getitem(t){let[n,...r]=this.dims;if(t=tm(t,n),r.length>0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}return new e(this.type,[this.data[t]],r)}_subarray(t,n,r){let i=t*n,a=(t+1)*n,o=`subarray`in this.data?this.data.subarray(i,a):this.data.slice(i,a);return new e(this.type,o,r)}item(){let e=this.data;if(e.length!==1)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return Wp(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]=e(t[n],n,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let t=this.data;for(let n=0;n<t.length;++n)t[n]-=e;return this}remainder(e){return this.clone().remainder_(e)}remainder_(e){let t=this.data,n=t instanceof BigInt64Array||t instanceof BigUint64Array?BigInt(e):Number(e);if((n===0||n===0n)&&(this.type.includes(`int`)||this.type===`bool`))throw RangeError(`Division by zero`);if(n<0&&(this.type.startsWith(`uint`)||this.type===`bool`))throw RangeError(`Negative divisors are not supported for unsigned or boolean tensors`);for(let e=0;e<t.length;++e){let r=t[e]%n;t[e]=r<0&&n>0||r>0&&n<0?r+n:r}return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let n=[],r=[];for(let e=0;e<this.dims.length;++e){let i=t[e];if(i==null)r.push([0,this.dims[e]]),n.push(this.dims[e]);else if(typeof i==`number`)i=tm(i,this.dims[e],e),r.push([i,i+1]);else if(Array.isArray(i)&&i.length===2){let[t,a]=i;if(t=t===null?0:tm(t,this.dims[e],e,!1),a=a===null?this.dims[e]:tm(a,this.dims[e],e,!1),t>a)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e<i.length;++e)if(r[e][0]!==0||r[e][1]!==this.dims[e]){l=!1;break}if(l){let e=r[0][0]*c[0],t=r[0][1]*c[0];if(ArrayBuffer.isView(o))s.set(o.subarray(e,t));else if(Array.isArray(o)){let n=o.slice(e,t);for(let e=0;e<n.length;++e)s[e]=n[e]}else throw Error(`Unsupported data type for slicing`)}else for(let e=0;e<a;++e){let t=0;for(let n=i.length-1,a=e;n>=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return Gp(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=rm(o,this,n,r);if(t!==1)for(let e=0;e<l.length;++e)l[e]=l[e]**(1/t);return new e(c,l,u)}normalize_(e=2,t=1){t=tm(t,this.dims.length);let n=this.norm(e,t,!0),r=this.data,i=n.data;for(let e=0;e<r.length;++e){let n=0;for(let r=this.dims.length-1,i=e,a=1;r>=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return om(this.dims)}squeeze(t=null){return new e(this.type,this.data,$p(this.dims,t))}squeeze_(e=null){return this.dims=$p(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,em(this.dims,t))}unsqueeze_(e){return this.dims=em(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;e<t.length;++e)if(t[e]===-1){if(n!==-1)throw Error(`Only one dimension can be inferred`);n=e}let r=this.data;if(n!==-1){let e=t.reduce((e,t,r)=>r===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]>t);return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;e<r.length;++e)n[e]=+(r[e]<t);return new e(`bool`,n,this.dims)}clamp_(e,t){let n=this.data;for(let r=0;r<n.length;++r)n[r]=Math.min(Math.max(n[r],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return am(this,e,t)}min(t=null,n=!1){if(t===null){let t=Qf(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=rm((e,t)=>Math.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=$f(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=rm((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error(\"`dim !== null` not yet implemented.\");let r=Qf(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error(\"`dim !== null` not yet implemented.\");let r=$f(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(e=>e===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=om(r),l=om(i);for(let e=0;e<a;++e){let t=e,n=0;for(let e=0;e<i.length;++e){let i=Math.floor(t/l[e]);t%=l[e];let a=i%r[e];n+=a*c[e]}s[e]=o[n]}return new e(this.type,s,i)}tile(...e){if(e.length<this.dims.length){let t=this.dims.length-e.length;e=Array(t).fill(1).concat(e)}return this.repeat(...e)}to(t){if(this.type===t)return this;if(!Up.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let n,r=[`int64`,`uint64`].includes(this.type),i=[`int64`,`uint64`].includes(t);if(r&&!i)n=Number;else if(!r&&i)n=[`float16`,`float32`,`float64`].includes(this.type)?e=>BigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,cp(this.data),this.dims);return new e(t,Up[t].from(this.data,n),this.dims)}};function Wp(e,t){let n=e.length;if(n!==(t.length===0?1:t.reduce((e,t)=>e*t)))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.length<t[e]?i.push(r):n.push([r]),n},[[]]);return r[0]}function Gp(e,t){let[n,r]=Yf(e.data,e.dims,t);return new H(e.type,n,r)}function Kp(e,[t,n],r=`bilinear`,i=!1){let a=e.dims.at(-3)??1,o=e.dims.at(-2),s=e.dims.at(-1),c=Jf(e.data,[a,o,s],[t,n],r,i);return new H(e.type,c,[a,t,n])}async function qp(e,{size:t=null,mode:n=`bilinear`}={}){if(e.dims.length!==4)throw Error(\"`interpolate_4d` currently only supports 4D input.\");if(!t)throw Error(\"`interpolate_4d` requires a `size` argument.\");let r;if(t.length===2)r=[...e.dims.slice(0,2),...t];else if(t.length===3)r=[e.dims[0],...t];else if(t.length===4)r=t;else throw Error(\"`size` must be of length 2, 3, or 4.\");let i;if(n===`nearest`)i=await Np.nearest_interpolate_4d;else if(n===`bilinear`)i=await Np.bilinear_interpolate_4d;else if(n===`bicubic`)i=await Np.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${n}`);let a=new H(`int64`,new BigInt64Array(r.map(BigInt)),[r.length]);return await i({x:e,s:a})}async function Jp(e,t){return await(await Np.matmul)({a:e,b:t})}async function Yp(e,t){let n=await Np.top_k;return t=t==null?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await n({x:e,k:new H(`int64`,[BigInt(t)],[1])})}var Xp=e=>new H(`int64`,e,[e.length]);async function Zp(e,t,n,r,i){return await(await Np.slice)({x:e,s:Xp(t),e:Xp(n),a:Xp(r),t:Xp(i??Array(r.length).fill(1))})}function Qp(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;e<o;++e){let t=e*c*s;for(let i=0;i<c;++i){let o=0,u=0,d=e*s,f=t+i;for(let e=0;e<s;++e){let t=Number(r[d+e]);u+=t,o+=n[f+e*c]*t}let p=o/u;a[l++]=p}}return new H(e.type,a,i)}function $p(e,t){return e=e.slice(),t===null?e=e.filter(e=>e!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function em(e,t){return t=tm(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function tm(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function U(e,t=0){t=tm(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a<e.length;++a){let{data:o,dims:s}=e[a];for(let e=0;e<o.length;++e){let a=0;for(let i=s.length-1,o=e,c=1;i>=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new H(a,i,n)}function nm(e,t=0){return U(e.map(e=>e.unsqueeze(t)),t)}function rm(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=tm(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t<a.length;++t){let r=0;for(let e=o.length-1,i=t,a=1;e>=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function im(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new H(e.type,[t],[]);return[new H(e.type,[r],[]),a]}t=tm(t,a.length);let o=am(e,t,r),s=o.data,[c,l,u]=rm((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;e<l.length;++e)l[e]=Math.sqrt(l[e]/(a[t]-n));return[new H(c,l,u),o]}function am(e,t=null,n=!1){let r=e.dims,i=e.data;if(t===null){let t=i.reduce((e,t)=>e+t,0);return new H(e.type,[t/i.length],[])}t=tm(t,r.length);let[a,o,s]=rm((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e<o.length;++e)o[e]/=r[t];return new H(a,o,s)}function om(e){let t=Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}function sm(e,t,n,r){return new H(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function cm(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return sm(e,t,n,r)}function lm(e,t){return cm(e.dims,t)}function um(e){return sm(e,1n,`int64`,BigInt64Array)}function dm(e){return um(e.dims)}function fm(e){return sm(e,0n,`int64`,BigInt64Array)}function pm(e){return fm(e.dims)}function mm(e){let t=e.reduce((e,t)=>e*t,1);return new H(`float32`,Float32Array.from({length:t},()=>uf.gauss()),e)}function hm(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e<a.length;++e){let t=+(a[e]>0),r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new H(r,o,[e.dims[0],e.dims[1]/8])}async function gm(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await If(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function _m(e,t){let n=await gm(e);return await Promise.all(n.map(n=>qf(e,n,!0,t)))}function vm(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error(\"Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.\");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var ym=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function bm(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?qs(e[i],s):qs(s,e[i])}}function xm(e,t){for(let n of Object.keys(e))e[n].length=t}function Sm(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t){if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}return t}}return null}function Cm(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var W=class extends Vs{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new mu(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Sm(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Sm(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Sm(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Sm(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Sm(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Sm(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=/* @__PURE__ */ Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with \"name\" and \"template\" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=/* @__PURE__ */ new Map;let n=Cm(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await _m(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let{text_pair:n=null,add_special_tokens:r=!0,padding:i=!1,return_token_type_ids:a=null}=t,{truncation:o=null,max_length:s=null}=t,c=t.return_tensor??!0,l=Array.isArray(e),u;if(l){if(e.length===0)throw Error(`text array must be non-empty`);if(n!==null){if(!Array.isArray(n))throw Error(`text_pair must also be an array`);if(e.length!==n.length)throw Error(`text and text_pair must have the same length`);u=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:a}))}else u=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:a}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(n))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(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:a})]}if(s===null?s=this.model_max_length:o===null&&(i===!0?(N.warn(\"`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`.\"),s=this.model_max_length):i===!1&&(N.warn(\"Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length.\"),o=!0)),i===!0&&(s=Math.min($f(u.map(e=>e.input_ids.length))[0],s??1/0)),s=Math.min(s,this.model_max_length??1/0),i||o)for(let e=0;e<u.length;++e)if(u[e].input_ids.length===s)continue;else u[e].input_ids.length>s?o&&xm(u[e],s):i&&bm(u[e],s,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let d={};if(c){if(!(i&&o)&&u.some(e=>{for(let t of Object.keys(e))if(e[t].length!==u[0][t]?.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 e=[u.length,u[0].input_ids.length];for(let t of Object.keys(u[0]))d[t]=new H(`int64`,BigInt64Array.from(u.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(u[0]))d[e]=u.map(t=>t[e]);if(!l)for(let e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof H&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof H&&(e=vm(e)),!Array.isArray(e)||e.length===0||!Ws(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null){if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=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(e===null){if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`)}return e}apply_chat_template(e,t={}){let{tools:n=null,documents:r=null,chat_template:i=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:s=!1,truncation:c=!1,max_length:l=null,return_tensor:u=!0,return_dict:d=!0,tokenizer_kwargs:f={},...p}=t;if(i=this.get_chat_template({chat_template:i,tools:n}),typeof i!=`string`)throw Error(`chat_template must be a string, but got ${typeof i}`);let m=this._compiled_template_cache.get(i);m===void 0&&(m=new rf(i),this._compiled_template_cache.set(i,m));let h=/* @__PURE__ */ Object.create(null);for(let e of ym){let t=Sm(this.config,e);t&&(h[e]=t)}let g=m.render({messages:e,add_generation_prompt:a,tools:n,documents:r,...h,...p});if(o){let e=this._call(g,{add_special_tokens:!1,padding:s,truncation:c,max_length:l,return_tensor:u,...f});return d?e:e.input_ids}return g}};function wm(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error(\"Tokenizer must have `language_codes` attribute set and it should be an array of language ids.\");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error(\"Tokenizer must have `languageRegex` attribute set and it should be a regular expression.\");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error(\"Tokenizer must have `lang_to_token` attribute set and it should be a function.\");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code \"${a}\" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code \"${i}\" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);let t=e._tokenizer.post_processor?.config;if(t&&`single`in t){for(let n of t.single)if(`SpecialToken`in n&&e.languageRegex.test(n.SpecialToken.id)){n.SpecialToken.id=e.lang_to_token(i);break}}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var Tm={};us(Tm,{AlbertTokenizer:()=>Em,AutoTokenizer:()=>G,BartTokenizer:()=>Dm,BertTokenizer:()=>Om,BlenderbotSmallTokenizer:()=>km,BlenderbotTokenizer:()=>Am,BloomTokenizer:()=>jm,CLIPTokenizer:()=>Nm,CamembertTokenizer:()=>Mm,CodeGenTokenizer:()=>Fm,CodeLlamaTokenizer:()=>Pm,CohereAsrTokenizer:()=>Lm,CohereTokenizer:()=>Im,ConvBertTokenizer:()=>Rm,DebertaTokenizer:()=>Bm,DebertaV2Tokenizer:()=>zm,DistilBertTokenizer:()=>Vm,ElectraTokenizer:()=>Hm,EsmTokenizer:()=>Um,FalconTokenizer:()=>Wm,GPT2Tokenizer:()=>qm,GPTNeoXTokenizer:()=>Km,GemmaTokenizer:()=>Gm,HerbertTokenizer:()=>Jm,LlamaTokenizer:()=>Ym,M2M100Tokenizer:()=>Xm,MBart50Tokenizer:()=>$m,MBartTokenizer:()=>Qm,MPNetTokenizer:()=>nh,MarianTokenizer:()=>Zm,MgpstrTokenizer:()=>eh,MobileBertTokenizer:()=>th,NllbTokenizer:()=>rh,NougatTokenizer:()=>ih,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>ah,RoFormerTokenizer:()=>sh,RobertaTokenizer:()=>oh,SiglipTokenizer:()=>ch,SpeechT5Tokenizer:()=>lh,SqueezeBertTokenizer:()=>uh,T5Tokenizer:()=>dh,TokenizersBackend:()=>W,VitsTokenizer:()=>ph,Wav2Vec2CTCTokenizer:()=>mh,WhisperTokenizer:()=>xh,XLMRobertaTokenizer:()=>Sh,XLMTokenizer:()=>Ch});var Em=class extends W{return_token_type_ids=!0},Dm=class extends W{},Om=class extends W{return_token_type_ids=!0},km=class extends W{},Am=class extends W{},jm=class extends W{},Mm=class extends W{},Nm=class extends W{},Pm=class extends W{},Fm=class extends W{},Im=class extends W{},Lm=class extends W{},Rm=class extends W{return_token_type_ids=!0},zm=class extends W{return_token_type_ids=!0},Bm=class extends W{return_token_type_ids=!0},Vm=class extends W{},Hm=class extends W{return_token_type_ids=!0},Um=class extends W{},Wm=class extends W{},Gm=class extends W{},Km=class extends W{},qm=class extends W{},Jm=class extends W{return_token_type_ids=!0},Ym=class extends W{padding_side=`left`},Xm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},Zm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^(>>\\w+<<)\\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),N.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,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||N.warn(`Unsupported language code \"${e}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),qs([e],super._encode_text(t))}}},Qm=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},$m=class extends Qm{},eh=class extends W{},th=class extends W{return_token_type_ids=!0},nh=class extends W{},rh=class extends W{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return wm(this,e,t,n)}},ih=class extends W{},ah=class extends W{},oh=class extends W{},sh=class extends W{return_token_type_ids=!0},ch=class extends W{},lh=class extends W{},uh=class extends W{return_token_type_ids=!0},dh=class extends W{},fh=class extends tu{decode_chain(e){let t=``;for(let n=1;n<e.length;n+=2)t+=e[n];return[t]}},ph=class extends W{constructor(e,t){super(e,t),this._tokenizer.decoder=new fh({type:`VitsDecoder`})}},mh=class extends W{},hh=[[`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`]],gh=new Map(hh),_h=new Map([...hh.map(([e,t])=>[t,e]),[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]);function vh(e){e=e.toLowerCase();let t=_h.get(e);if(t===void 0){let n=e.match(/^<\\|([a-z]{2})\\|>$/);if(n&&(e=n[1]),gh.has(e))t=e;else{let t=e.length===2?gh.keys():gh.values();throw Error(`Language \"${e}\" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var yh=/* @__PURE__ */ RegExp(`^[\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E]+$`,`gu`),bh=.1,xh=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r<g)break;v=n}}}let b=[],x=[];for(let n=0;n<e.length;++n){let g=Number(e[n]);if(_.has(g)){let e=this.decode([g]),n=gh.get(e.slice(2,-2));if(n!==void 0){if(a!==null&&n!==a&&!t){p.push(b);let e=this.findLongestCommonSequence(p)[0],t=this.decode(e);l.text=t,c.push(l),p=[],b=[],l=s()}a=l.language=n}}else if(g>=d&&g<=f){let e=ap((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g<y)h=!1;else if(l.timestamp[0]===null)l.timestamp[0]=e;else if(e!==l.timestamp[0]){l.timestamp[1]=e,p.push(b),o&&m.push(x);let[t,n]=this.findLongestCommonSequence(p,m),r=this.decode(t);if(l.text=r,o&&(l.words=this.collateWordTimestamps(t,n,a),l.words.length>0&&l.timestamp[1]!==null))for(let e of l.words)e.timestamp[1]>l.timestamp[1]&&l.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=l.timestamp[1]);c.push(l),p=[],b=[],m=[],x=[],l=s()}}else if(b.push(g),o){let e=ap(i[n]+u,2),t;if(n+1<i.length){t=ap(i[n+1]+u,2);let a=this.decode([g]);yh.test(a)&&(t=ap(Math.min(e+r,t),2))}else t=null;x.push([e,t])}}if(`stride`in n){let[e,t,r]=n.stride;u+=e-r}b.length>0?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=/* @__PURE__ */ Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e<c.length;++e){let r=c[e];t||delete r.timestamp,n||delete r.language}if(o){let e=[];for(let t of c)for(let n of t.words)e.push(n);v={chunks:e}}else v={chunks:c}}return[y,v]}findLongestCommonSequence(e,t=null){let n=e[0],r=n.length,i=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,s=a?t[0]:null;for(let c=1;c<e.length;++c){let l=e[c],u=0,d=[r,r,0,0],f=l.length;for(let e=1;e<r+f;++e){let i=Math.max(0,r-e),o=Math.min(r,r+f-e),p=n.slice(i,o),m=Math.max(0,e-r),h=Math.min(f,e),g=l.slice(m,h);if(p.length!==g.length)throw Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");let _;_=a?p.filter((e,n)=>e===g[n]&&s[i+n][0]-bh<=t[c][m+n][0]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);if(a&&u===0&&r>0){let e=s[r-1][0],n=t[c].findIndex(t=>t[0]>=e);v=n===-1?l.length:n}i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e<r.length;++e){let n=a[e];o.push({text:r[e],timestamp:[t[n.at(0)][0],t[n.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,n=`\"'“¡¿([{-`,r=`\"'.。,,!!??::”)]}、`){t??=`english`;let i,a,o;return[`chinese`,`japanese`,`thai`,`lao`,`myanmar`].includes(t)?[i,a,o]=this.splitTokensOnUnicode(e):[i,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(i,a,o,n,r)}decode(e,t){let n;return t?.decode_with_timestamps?(e instanceof H&&(e=vm(e)),n=this.decodeWithTimestamps(e,t)):n=super.decode(e,t),n}decodeWithTimestamps(e,t){let n=t?.time_precision??.02,r=this.all_special_ids.at(-1)+1,i=[[]];for(let t of e)if(t=Number(t),t>=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c<e.length;++c){let l=e[c];a.push(l),o.push(c);let u=this.decode(a,{decode_with_timestamps:!0});u.includes(`�`)&&t[s+u.indexOf(`�`)]!==`�`||(n.push(u),r.push(a),i.push(o),a=[],o=[],s+=u.length)}return[n,r,i]}splitTokensOnSpaces(e){let[t,n,r]=this.splitTokensOnUnicode(e),i=[],a=[],o=[];for(let e=0;e<t.length;++e){let s=t[e],c=n[e],l=r[e],u=c[0]>=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=yh.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=qs(o[c],o[l]),s[l]=qs(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;l<a.length;)!a[c].endsWith(` `)&&i.includes(a[l])?(a[c]+=a[l],o[c]=qs(o[c],o[l]),s[c]=qs(s[c],s[l]),a[l]=``,o[l]=[],s[l]=[]):c=l,++l;return[a.filter(e=>e),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Sh=class extends W{},Ch=class extends W{return_token_type_ids=!0;constructor(e,t){super(e,t),N.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},G=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await _m(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Tm[c];return l||=(N.warn(`Unknown tokenizer class \"${c}\", attempting to construct from base class.`),W),new l(o,s)}},wh=`https://github.com/huggingface/transformers.js/issues/new/choose`,Th=`preprocessor_config.json`,Eh=`preprocessor_config.json`,Dh=`processor_config.json`,Oh=`chat_template.jinja`,K=class extends Vs{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?qf(e,Dh,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?Kf(e,Oh,!0,t):null]);return new this(n,r,i)}},kh={};us(kh,{ChatterboxProcessor:()=>Cg,CohereAsrProcessor:()=>Tg,EmbeddingGemma2Processor:()=>Bg,EmbeddingGemma2VideoProcessor:()=>Lg,Florence2Processor:()=>y1,Gemma3Processor:()=>b1,Gemma3nProcessor:()=>x1,Gemma4Processor:()=>Ig,Glm46VProcessor:()=>C1,GraniteSpeechProcessor:()=>w1,GroundingDinoProcessor:()=>E1,Idefics3Processor:()=>A1,JinaCLIPProcessor:()=>M1,Lfm2VlProcessor:()=>N1,Lfm3VlProcessor:()=>P1,LlavaProcessor:()=>F1,MgpstrProcessor:()=>L1,MoonshineProcessor:()=>R1,OwlViTProcessor:()=>z1,PaliGemmaProcessor:()=>H1,Phi3VProcessor:()=>G1,PixtralProcessor:()=>K1,Processor:()=>K,PyAnnoteProcessor:()=>q1,Qwen2VLProcessor:()=>S1,Qwen2_5_VLProcessor:()=>J1,Qwen3VLProcessor:()=>Y1,Sam2Processor:()=>Z1,Sam2VideoProcessor:()=>Q1,SamProcessor:()=>X1,SmolVLMProcessor:()=>A1,SpeechT5Processor:()=>$1,UltravoxProcessor:()=>e0,VLChatProcessor:()=>j1,VoxtralProcessor:()=>a0,VoxtralRealtimeProcessor:()=>d0,Wav2Vec2Processor:()=>f0,Wav2Vec2ProcessorWithLM:()=>p0,WhisperProcessor:()=>m0});var Ah=class extends Vs{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await qf(e,Th,!0,t);return new this(n)}};function jh(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \\`load_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`)}var Mh={};us(Mh,{ASTFeatureExtractor:()=>ng,ChatterboxFeatureExtractor:()=>ig,ClapFeatureExtractor:()=>ag,CohereAsrFeatureExtractor:()=>cg,DacFeatureExtractor:()=>lg,EncodecFeatureExtractor:()=>rg,FeatureExtractor:()=>Ah,Gemma3nAudioFeatureExtractor:()=>ug,Gemma4AudioFeatureExtractor:()=>dg,GraniteSpeechFeatureExtractor:()=>fg,MoonshineFeatureExtractor:()=>pg,ParakeetFeatureExtractor:()=>sg,PyAnnoteFeatureExtractor:()=>mg,SeamlessM4TFeatureExtractor:()=>hg,SnacFeatureExtractor:()=>gg,SpeechT5FeatureExtractor:()=>_g,VoxtralRealtimeFeatureExtractor:()=>bg,Wav2Vec2FeatureExtractor:()=>vg,WeSpeakerFeatureExtractor:()=>yg,WhisperFeatureExtractor:()=>xg});var Nh={fromWeb:()=>{}};async function Ph(e,t){if(j.IS_BROWSER_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(j.IS_FS_AVAILABLE){let n=t.stream();Nh.fromWeb(n),ds.createWriteStream(e),await void 0}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function Fh(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 n=await(await Rf(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&N.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r<i.length;++r)a[r]=e*(t[r]+n[r])/2}else a=i.getChannelData(0);return a}async function Ih(e,t){return await Fh(e,t)}function Lh(e,t){if(e<1)return/* @__PURE__ */ new Float64Array;if(e===1)return new Float64Array([1]);let n=1-t,r=2*Math.PI/(e-1),i=new Float64Array(e);for(let a=0;a<e;++a)i[a]=t-n*Math.cos(a*r);return i}function Rh(e){return Lh(e,.5)}function zh(e){return Lh(e,.54)}var Bh={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function Vh(e,t=`htk`){let n=Bh[t];if(!n)throw Error(`mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var Hh={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function Uh(e,t=`htk`){let n=Hh[t];if(!n)throw Error(`mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function Wh(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;n<e.length;++n){let i=r[n];for(let r=0;r<t.length;++r)i[r]=t[r]-e[n]}let i=t.length-2,a=Array.from({length:i},()=>Array(e.length));for(let t=0;t<e.length;++t){let e=r[t];for(let r=0;r<i;++r){let i=-e[r]/n[r],o=e[r+2]/n[r+1];a[r][t]=Math.max(0,Math.min(i,o))}}return a}function Gh(e,t,n){let r=(t-e)/(n-1);return Float64Array.from({length:n},(t,n)=>e+r*n)}function Kh(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or \"slaney\"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=Gh(Vh(n,o),Vh(r,o),t+2),l=Uh(c,o),u;if(s){let t=i/((e-1)*2);u=Vh(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=Gh(0,Math.floor(i/2),e);let d=Wh(u,l);if(a!==null&&a===`slaney`)for(let n=0;n<t;++n){let t=d[n],r=2/(l[n+2]-l[n]);for(let n=0;n<e;++n)t[n]*=r}return d}function qh(e,t,n){let r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n<e.length;++n)r[t+n]=e[n];for(let n=1;n<=t;++n)r[t-n]=e[Ys(n,i)];for(let a=1;a<=n;++a)r[i+t+a]=e[Ys(i-a,i)];return r}function Jh(e,t,n,r,i){if(n<=0)throw Error(`reference must be greater than zero`);if(r<=0)throw Error(`min_value must be greater than zero`);n=Math.max(r,n);let a=Math.log10(n);for(let n=0;n<e.length;++n)e[n]=t*Math.log10(Math.max(r,e[n])-a);if(i!==null){if(i<=0)throw Error(`db_range must be greater than zero`);let t=$f(e)[0]-i;for(let n=0;n<e.length;++n)e[n]=Math.max(e[n],t)}return e}function Yh(e,t=1,n=1e-5,r=null){return Jh(e,20,t,n,r)}function Xh(e,t=1,n=1e-10,r=null){return Jh(e,10,t,n,r)}async function Zh(e,t,n,r,{fft_length:i=null,power:a=1,center:o=!0,pad_mode:s=`reflect`,onesided:c=!0,preemphasis:l=null,preemphasis_htk_flavor:u=!0,mel_filters:d=null,mel_floor:f=1e-10,log_mel:p=null,max_log_mel:m=null,reference:h=1,min_value:g=1e-10,db_range:_=null,remove_dc_offset:v=null,min_num_frames:y=null,max_num_frames:b=null,do_pad:x=!0,transpose:S=!1,mel_offset:C=0,mel_floor_mode:ee=`clamp`}={}){let w=t.length;if(i===null&&(i=n),n>i)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(w!==n)throw Error(`Length of the window (${w}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error(\"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.\");if(!u)throw Error(\"`preemphasis_htk_flavor=false` is not currently supported.\");if(o){let t=Math.floor(n/2);switch(s){case`reflect`:e=qh(e,t,t);break;case`constant`:{let n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}case`semicausal`:{let n=new e.constructor(e.length+t);n.set(e,t),e=n;break}default:throw Error(`pad_mode=\"${s}\" not implemented yet.`)}}let te=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&te<y&&(te=y);let ne=c?Math.floor(i/2)+1:i,re=te,ie=te;b!==null&&(b>te?x&&(ie=b):ie=re=b);let ae=new rp(i),oe=new Float64Array(i),se=new Float64Array(ae.outputBufferSize),ce=new Float32Array(ne*ie);for(let i=0;i<re;++i){let a=i*r,o=Math.min(e.length-a,n);o!==n&&oe.fill(0,0,n);for(let t=0;t<o;++t)oe[t]=e[a+t];if(v){let e=0;for(let t=0;t<o;++t)e+=oe[t];let t=e/o;for(let e=0;e<o;++e)oe[e]-=t}if(l!==null){for(let e=o-1;e>=1;--e)oe[e]-=l*oe[e-1];oe[0]*=1-l}for(let e=0;e<t.length;++e)oe[e]*=t[e];ae.realTransform(se,oe);for(let e=0;e<ne;++e){let t=e<<1;ce[e*ie+i]=se[t]**2+se[t+1]**2}}if(a!==null&&a!==2){let e=a/2;for(let t=0;t<ce.length;++t)ce[t]**=e}let le=d.length,ue=await Jp(new H(`float32`,d.flat(),[le,ne]),new H(`float32`,ce,[ne,ie]));S&&(ue=ue.transpose(1,0));let T=ue.data;if(ee===`add`)for(let e=0;e<T.length;++e)T[e]=C+T[e]+f;else for(let e=0;e<T.length;++e)T[e]=C+Math.max(f,T[e]);if(a!==null&&p!==null){let e=Math.min(T.length,re*le);switch(p){case`log`:for(let t=0;t<e;++t)T[t]=Math.log(T[t]);break;case`log10`:for(let t=0;t<e;++t)T[t]=Math.log10(T[t]);break;case`log10_max_norm`:{for(let t=0;t<e;++t)T[t]=Math.log10(T[t]);let t=(m??$f(T)[0])-8;for(let n=0;n<e;++n)T[n]=(Math.max(T[n],t)+4)/4;break}case`dB`:if(a===1)Yh(T,h,g,_);else if(a===2)Xh(T,h,g,_);else throw Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return ue}function Qh(e,t,{periodic:n=!0,frame_length:r=null,center:i=!0}={}){let a=n?e+1:e,o;switch(t){case`boxcar`:o=new Float64Array(a).fill(1);break;case`hann`:case`hann_window`:o=Rh(a);break;case`hamming`:o=zh(a);break;case`povey`:o=Rh(a).map(e=>e**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null||e===r)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);let s=new Float64Array(r),c=i?Math.floor((r-e)/2):0;return s.set(o,c),s}function $h(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=/* @__PURE__ */ new ArrayBuffer(44),i=new DataView(r);return eg(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),eg(i,8,`WAVE`),eg(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),eg(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice())],{type:`audio/wav`})}function eg(e,t,n){for(let r=0;r<n.length;++r)e.setUint8(t+r,n.charCodeAt(r))}var tg=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return/* @__PURE__ */ new Float32Array;if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((e,t)=>e+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),$h(e,this.sampling_rate)}async save(e){return Ph(e,this.toBlob())}},ng=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){jh(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t<n.length;++t)n[t]=(n[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}},rg=class extends Ah{async _call(e){jh(e,`EncodecFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let n=[1,t,e.length/t];return{input_values:new H(`float32`,e,n)}}},ig=class extends Ah{async _call(e){jh(e,`ChatterboxFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new H(`float32`,e,t)}}},ag=class extends Ah{constructor(e){super(e),this.mel_filters=Kh(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=Kh(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=Qh(this.config.fft_window_size,`hann`)}async _get_input_mel(e,t,n,r){let i,a=e.length-t;if(a>0){if(n===`rand_trunc`){let n=Math.floor(uf.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy \"${n}\" not implemented`)}else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;r<t;r+=e.length)n.set(e.subarray(0,Math.min(e.length,t-r)),r);else if(r===`repeatpad`)for(let t=e.length;t<-a;t+=e.length)n.set(e,t);e=n}if(n===`fusion`)throw Error(`Truncation strategy \"${n}\" not implemented`);i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return i.unsqueeze_(0)}async _extract_fbank_features(e,t,n=null){return Zh(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:`dB`,max_num_frames:n,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return jh(e,`ClapFeatureExtractor`),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},og=1e-5,sg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(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=Qh(this.config.win_length,`hann`,{periodic:!1});this.window=new Float64Array(this.config.n_fft);let n=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,n)}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 Zh(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){jh(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e<n;++e){let t=e*a;for(let e=0;e<a;++e){let n=r[t+e];o[e]+=n,s[e]+=n*n}}let c=n>1?n-1:1;for(let e=0;e<a;++e){let t=o[e]/n,i=(s[e]-n*t*t)/c,l=1/(Math.sqrt(i)+og);for(let i=0;i<n;++i){let n=i*a+e;r[n]=(r[n]-t)*l}}let l=new BigInt64Array(i);return l.fill(1n,0,n),{input_features:t.unsqueeze_(0),attention_mask:new H(`int64`,l,[1,i])}}},cg=class extends sg{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let n=new sf(e.length);for(let r=0;r<e.length;++r)e[r]+=t*n.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,n=this.config.overlap_chunk_second??5,r=this.config.min_energy_window_samples??1600,i=this.config.sampling_rate,a=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(n*i));if(e.length<=a)return[e];let s=[],c=0,l=e.length;for(;c<l;){if(c+a>=l){s.push(e.slice(c,l));break}let t=Math.max(c,c+a-o),n=Math.min(c+a,l),i;i=n<=t?c+a:this._find_split_point_energy(e,t,n,r),i=Math.max(c+1,Math.min(i,l)),s.push(e.slice(c,i)),c=i}return s}_find_split_point_energy(e,t,n,r){let i=n-t;if(i<=r)return Math.floor((t+n)/2);let a=1/0,o=t,s=i-r;for(let n=0;n<=s;n+=r){let i=0;for(let a=0;a<r;++a){let r=e[t+n+a];i+=r*r}i=Math.sqrt(i/r),i<a&&(a=i,o=t+n)}return o}async _call(e){jh(e,`CohereAsrFeatureExtractor`);let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},lg=class extends rg{},ug=class extends Ah{constructor(e){super(e);let{fft_length:t,feature_size:n,min_frequency:r,max_frequency:i,sampling_rate:a,frame_length:o}=this.config,s=Kh(Math.floor(1+t/2),n,r,i,a,null,`htk`,!1);this.mel_filters=s,this.window=Qh(o,`hann`)}async _extract_fbank_features(e,t){return Zh(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:n=!0,padding:r=!0,pad_to_multiple_of:i=128}={}){if(jh(e,`Gemma3nAudioFeatureExtractor`),n&&e.length>t&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=cm([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},dg=class extends ug{async _extract_fbank_features(e,t){let{frame_length:n,hop_length:r,fft_length:i}=this.config,a=Math.floor(n/2),o=Math.floor((e.length+a-(n+1))/r)+1;return Zh(e,this.window,n,r,{fft_length:i,center:!0,pad_mode:`semicausal`,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:this.config.mel_floor,mel_floor_mode:`add`,remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){jh(e,`Gemma4AudioFeatureExtractor`);let n=e.length,r=await super._call(e,t),{input_features:i}=r,[,a,o]=i.dims,{frame_length:s,hop_length:c}=this.config,l=Math.floor(s/2),u=s+1,d=new Uint8Array(n+l+(t.pad_to_multiple_of??128));d.fill(1,l,l+n);let f=new Uint8Array(a);for(let e=0;e<a;++e)f[e]=+!!d[e*c+u-1];let p=i.data;for(let e=0;e<a;++e)f[e]||p.fill(0,e*o,(e+1)*o);return r.input_features_mask=new H(`bool`,f,[1,a]),r}},fg=class extends Ah{constructor(e){super(e);let{n_fft:t,win_length:n,n_mels:r,sample_rate:i}=e.melspec_kwargs;this.mel_filters=Kh(Math.floor(1+t/2),r,0,i/2,i,null,`htk`);let a=Qh(n,`hann`);this.window=new Float64Array(t);let o=Math.floor((t-n)/2);this.window.set(a,o)}async _call(e){jh(e,`GraniteSpeechFeatureExtractor`);let{n_fft:t,hop_length:n,n_mels:r}=this.config.melspec_kwargs,i=Math.floor(e.length/n)+1,a=i-i%2;return{input_features:(await Zh(e,this.window,t,n,{power:2,mel_filters:this.mel_filters,log_mel:`log10_max_norm`,transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},pg=class extends Ah{async _call(e){jh(e,`MoonshineFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new H(`float32`,e,t)}}},mg=class extends Ah{async _call(e){jh(e,`PyAnnoteFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new H(`float32`,e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let n=t/this.samples_to_frames(t)/this.config.sampling_rate,r=[];for(let t of e.tolist()){let e=[],i=-1;for(let n=0;n<t.length;++n){let[r,a]=$f(Xf(t[n])),[o,s]=[n,n+1];a===i?(e.at(-1).end=s,e.at(-1).score+=r):(i=a,e.push({id:a,start:o,end:s,score:r}))}r.push(e.map(({id:e,start:t,end:r,score:i})=>({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},hg=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){jh(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r<t;++r){let i=0;for(let a=0;a<e;++a)i+=n[a*t+r];let a=i/e,o=0;for(let i=0;i<e;++i)o+=(n[i*t+r]-a)**2;o/=e-1;let s=Math.sqrt(o+1e-7);for(let i=0;i<e;++i){let e=i*t+r;n[e]=(n[e]-a)/s}}}let o;if(t){let[e,t]=a.dims,r=a.data,s=e%n;if(s>0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new H(a.type,n,[c,t]),i&&(o=new H(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;n<s;n+=l,++r)t[r]=e[n]}else t.fill(1n);d.attention_mask=new H(`int64`,t,[1,e])}return d}},gg=class extends lg{},_g=class extends Ah{},vg=class extends Ah{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){jh(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 n=[1,t.length];return{input_values:new H(`float32`,t,n),attention_mask:new H(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},yg=class extends Ah{constructor(e){super(e);let t=this.config.sampling_rate,n=Kh(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0);this.mel_filters=n,this.window=Qh(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),Zh(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){jh(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t<r;++t){let r=t*i*a,o=t*a;for(let t=0;t<i;++t){let i=r+t*a;for(let t=0;t<a;++t)n[i+t]-=e[o+t]}}}return{input_features:t}}},bg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Qh(this.config.n_fft,`hann`)}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:n,hop_length:r,mel_filters:i,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/r:(e.length-n)/r);return await Zh(e,this.window,n,r,{power:2,mel_filters:i,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 jh(e,`VoxtralRealtimeFeatureExtractor`),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},xg=class extends Ah{constructor(e){super(e),this.config.mel_filters??=Kh(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,`slaney`,`slaney`),this.window=Qh(this.config.n_fft,`hann`)}async _extract_fbank_features(e){return await Zh(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}={}){jh(e,`WhisperFeatureExtractor`);let n,r=t??this.config.n_samples;return e.length>r?(e.length>this.config.n_samples&&N.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`.\"),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},Sg=class{static async from_pretrained(e,t={}){let n=await qf(e,Th,!0,t),r=n.feature_extractor_type,i=Mh[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${wh}.`);return new i(n)}},Cg=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},wg=/* @__PURE__ */ new Set([`ja`,`zh`]),Tg=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;get_decoder_prompt_ids(e=`en`){let t=[`▁`,`<|startofcontext|>`,`<|startoftranscript|>`,`<|emo:undefined|>`,`<|${e}|>`,`<|${e}|>`,`<|pnc|>`,`<|noitn|>`,`<|notimestamp|>`,`<|nodiarize|>`];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t=`en`){let n=e.filter(e=>e&&e.trim());if(n.length===0)return``;let r=wg.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},Eg={},Dg,Og,kg;if(j.IS_WEB_ENV)Dg=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},kg=self.createImageBitmap,Og=self.ImageData;else if(Eg)kg=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new Mg(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var Ag={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},jg=/* @__PURE__ */ new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),Mg=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)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 Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!j.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await Rf(e);if(t.status!==200)throw Error(`Unable to read image from \"${e}\" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(j.IS_WEB_ENV){let t=await kg(e),n=Dg(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=Eg(await e.arrayBuffer());return await kg(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.permute(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t<this.data.length;t+=this.channels){let r=this.data[t],i=this.data[t+1],a=this.data[t+2];e[n++]=Math.round(.2989*r+.587*i+.114*a)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t];break;case 4:for(let t=0,n=0;t<this.data.length;t+=4)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,n=0;t<this.data.length;++t)e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=this.data[t],e[n++]=255;break;case 3:for(let t=0,n=0;t<this.data.length;t+=3)e[n++]=this.data[t],e[n++]=this.data[t+1],e[n++]=this.data[t+2],e[n++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${e.channels}`);let t=this.data,n=e.data,r=this.width*this.height;if(this.channels===3){let e=new Uint8ClampedArray(r*4);for(let i=0,a=0,o=0;i<r;++i)e[o++]=t[a++],e[o++]=t[a++],e[o++]=t[a++],e[o++]=n[i];return this._update(e,this.width,this.height,4)}if(this.channels===4){for(let e=0;e<r;++e)t[4*e+3]=n[e];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,n,{resample:r=2}={}){if(this.width===t&&this.height===n)return this;let i=Ag[r]??r,a=Gs(t),o=Gs(n);if(a&&o)return this;if(a?t=n/this.height*this.width:o&&(n=t/this.width*this.height),j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),a=Dg(t,n).getContext(`2d`);return a.drawImage(i,0,0,t,n),new e(a.getImageData(0,0,t,n).data,t,n,4).convert(r)}{let e=this.toSharp();switch(i){case`box`:case`hamming`:(i===`box`||i===`hamming`)&&(N.warn(`Resampling method ${i} is not yet supported. Using bilinear instead.`),i=`bilinear`);case`nearest`:case`bilinear`:case`bicubic`:e=e.affine([t/this.width,0,0,n/this.height],{interpolator:i});break;case`lanczos`:e=e.resize({width:t,height:n,fit:`fill`,kernel:`lanczos3`});break;default:throw Error(`Resampling method ${i} is not supported.`)}return await kg(e)}}async pad([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.max(r,0),i=Math.max(i,0),t===0&&n===0&&r===0&&i===0)return this;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=this.width+t+n,c=this.height+r+i,l=Dg(s,c).getContext(`2d`);return l.drawImage(o,0,0,this.width,this.height,t,r,this.width,this.height),new e(l.getImageData(0,0,s,c).data,s,c,4).convert(a)}{let e=this.toSharp().extend({left:t,right:n,top:r,bottom:i});return await kg(e)}}async crop([t,n,r,i]){if(t=Math.max(t,0),n=Math.max(n,0),r=Math.min(r,this.width-1),i=Math.min(i,this.height-1),t===0&&n===0&&r===this.width-1&&i===this.height-1)return this;let a=r-t+1,o=i-n+1;if(j.IS_WEB_ENV){let r=this.channels,i=this.toCanvas(),s=Dg(a,o).getContext(`2d`);return s.drawImage(i,t,n,a,o,0,0,a,o),new e(s.getImageData(0,0,a,o).data,a,o,4).convert(r)}{let e=this.toSharp().extract({left:t,top:n,width:a,height:o});return await kg(e)}}async center_crop(t,n){if(this.width===t&&this.height===n)return this;let r=(this.width-t)/2,i=(this.height-n)/2;if(j.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),s=Dg(t,n).getContext(`2d`),c=0,l=0,u=0,d=0;return r>=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await kg(e)}}async toBlob(e=`image/png`,t=1){if(!j.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new H(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`){if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`)}return t}toCanvas(){if(!j.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=Dg(e.width,e.height),n=new Og(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;e<o;++e){let n=i*e;for(let r=0;r<i;++r)s[r][e]=t[n+r]}return s.map(t=>new e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(j.IS_WEB_ENV){if(j.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=jg.get(t)??`image/png`;return Ph(e,await this.toBlob(n))}if(j.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(j.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return Eg(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Mg.read.bind(Mg);function Ng(e,t,n,r,i){let a=r*n**2,o=Math.sqrt(a/(e*t)),s=i*n,c=Math.floor(o*e/s)*s,l=Math.floor(o*t/s)*s;if(c===0&&l===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \\`pooling_kernel_size * patch_size\\`=${s}.`);let u=Math.floor(r/i**2)*s;return c===0?(c=s,l=Math.min(Math.floor(t/e)*s,u)):l===0&&(l=s,c=Math.min(Math.floor(e/t)*s,u)),[c,l]}function Pg(e,t,n,r,i,a,o){let s=Math.floor(t/i),c=Math.floor(n/i),l=s*c,u=i*i*r,d=new Float32Array(a*u),f=0;for(let t=0;t<s;++t)for(let a=0;a<c;++a)for(let o=0;o<i;++o){let s=(t*i+o)*n*r+a*i*r;for(let t=0;t<i;++t){let n=s+t*r;for(let t=0;t<r;++t)d[f++]=e[n+t]}}let p=new BigInt64Array(a*2).fill(-1n),m=0;for(let e=0;e<s;++e)for(let t=0;t<c;++t)p[m++]=BigInt(t),p[m++]=BigInt(e);return{patches:new H(`float32`,d,[a,u]),positions:new H(`int64`,p,[a,2]),num_soft_tokens:Math.floor(l/o**2)}}var Fg=class extends Vs{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:n}=this,r=this.max_soft_tokens*n**2,i=[],a=[],o=[];for(let s of e){if(this.do_convert_rgb&&(s=s.rgb()),this.do_resize){let[e,i]=Ng(s.height,s.width,t,r,n);(e!==s.height||i!==s.width)&&(s=await s.resize(i,e,{resample:this.resample}))}let e=Float32Array.from(s.data);if(this.do_rescale)for(let t=0;t<e.length;++t)e[t]*=this.rescale_factor;let{patches:c,positions:l,num_soft_tokens:u}=Pg(e,s.height,s.width,s.channels,t,r,n);i.push(c),a.push(l),o.push(u)}return{pixel_values:nm(i,0),image_position_ids:nm(a,0),num_soft_tokens_per_image:o}}},Ig=class extends K{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:r,boa_token:i,eoa_token:a,image_token:o,boi_token:s,eoi_token:c}=this.tokenizer.config;this.audio_token=r,this.boa_token=i,this.eoa_token=a,this.image_token=o,this.boi_token=s,this.eoi_token=c}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([qf(e,Dh,!0,t),G.from_pretrained(e,t),Kf(e,Oh,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new Fg(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new dg(n.feature_extractor)),new this(n,a,i)}_compute_audio_num_tokens(e,t){let n=Math.round(t*20/1e3),r=Math.round(t*10/1e3),i=Math.floor(n/2),a=Math.floor((e+i-n-1)/r)+1;if(a<=0)return 0;for(let e=0;e<2;++e)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;if(t){i=await this.image_processor(t,r);let n=i.num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>`\n\n${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token}\n\n`))}let a;if(n){let t=Array.isArray(n)?n:[n];a=await this.feature_extractor(t[0],r);let i=this.feature_extractor.config.sampling_rate??16e3,o=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>`\n\n${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token}\n\n`))}return{...this.tokenizer(e,r),...i,...a}}},Lg=class extends Vs{constructor(e){super(),this.config=e,this.frame_processor=new Fg(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??`uniform`}sample_frames(e){let t=e.length,{max_frames:n}=this;if(t<=n)return e;if(this.overflow_strategy===`truncate`)return e.slice(0,n);let r=n>1?(t-1)/(n-1):0;return Array.from({length:n},(i,a)=>e[a>0&&a===n-1?t-1:Math.floor(a*r)])}async _call(e){Array.isArray(e)||(e=[e]);let t=e.map(e=>this.sample_frames(e.frames.map(e=>e.image))),{pixel_values:n,image_position_ids:r,num_soft_tokens_per_image:i}=await this.frame_processor(t.flat()),a=0;return{pixel_values_videos:n,video_position_ids:r,num_frames_per_video:t.map(e=>e.length),num_soft_tokens_per_video:t.map(e=>i[(a+=e.length)-1])}}};function Rg(e,t){return Array.isArray(e)?e.every(e=>Array.isArray(e))?e:t?[e]:e.map(e=>[e]):[[e]]}function zg(e,t,n){let r=0;if(e=e.map(e=>e.replaceAll(t,()=>n[r++]??``)),r!==n.length)throw Error(`Found ${r} ${t} tokens in the text, but ${n.length} inputs were passed.`);return e}var Bg=class extends Ig{constructor(e,t,n){super(e,t,n),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new Lg(e.video_processor)}async _call(e,t=null,n=null,r=null,i={}){let a=[[this.image_token,t&&Rg(t,!0)],[this.video_token,r&&Rg(r,!1)],[this.audio_token,n&&Rg(n,!1)]];if(e==null){let t=a.filter(([,e])=>e),n=t[0]?.[1].length;if(t.some(([,e])=>e.length!==n))throw Error(`Received a different number of samples per modality.`);e=Array.from({length:n},(e,n)=>t.flatMap(([e,t])=>Array(t[n].length).fill(e)).join(` `))}else typeof e==`string`&&(e=[e]);let[o,s,c]=a.map(([,e])=>e?.flat()),l=o&&await this.image_processor(o),u=s&&await this.video_processor(s),d=c&&await this._process_audio(c),{image_token:f,video_token:p,audio_token:m,boi_token:h,eoi_token:g,boa_token:_,eoa_token:v}=this,y={[f]:l?.num_soft_tokens_per_image.map(e=>h+f.repeat(e)+g),[p]:u?.num_soft_tokens_per_video.map((e,t)=>(h+p.repeat(e)+g).repeat(u.num_frames_per_video[t])),[m]:d?.num_soft_tokens_per_audio.map(e=>_+m.repeat(e)+v)};for(let[t,n]of Object.entries(y))e=zg(e,t,n??[]);return{...this.tokenizer(e,{padding:!0,...i}),...l,...u,...d}}async _process_audio(e){let t=[];for(let n of e)t.push(await this.feature_extractor(n));let n=Math.max(...t.map(e=>e.input_features.dims[1])),r=t[0].input_features.dims[2],i=new Float32Array(e.length*n*r),a=new Uint8Array(e.length*n);return t.forEach((e,t)=>{i.set(e.input_features.data,t*n*r),a.set(e.input_features_mask.data,t*n)}),{input_features:new H(`float32`,i,[e.length,n,r]),input_features_mask:new H(`bool`,a,[e.length,n]),num_soft_tokens_per_audio:t.map(({input_features_mask:{data:e}})=>{let t=0;for(let n=0;n<e.length;n+=4)t+=Number(e[n]);return t})}}};function Vg(e,t,n=0,r=null){let i=e/t,a=op(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),a<n&&(a=Math.ceil(i)*t),a}function Hg([e,t],n){return[Math.max(Math.floor(e/n),1)*n,Math.max(Math.floor(t/n),1)*n]}function Ug([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function Wg(e,t=.5,n=null,r=!1){let i=e.logits,a=e.pred_boxes,[o,s,c]=i.dims;if(n!==null&&n.length!==o)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let l=[];for(let e=0;e<o;++e){let o=n===null?null:n[e],u={boxes:[],classes:[],scores:[]},d=i[e],f=a[e];for(let e=0;e<s;++e){let n=d[e],i=[],a;if(r){a=n.sigmoid().data;for(let e=0;e<a.length;++e)a[e]>t&&i.push(e)}else{let e=$f(n.data)[1];if(e===c-1||(a=Xf(n.data),a[e]<t))continue;i.push(e)}for(let t of i){let n=f[e].data;n=Ug(n),o!==null&&(n=n.map((e,t)=>e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function Gg(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;e<r;++e){let r=t===null?null:t[e],a=n[e];r!==null&&(a=Kp(a,r,`bilinear`,!1));let[o,s]=r??a.dims.slice(-2),c=new H(`int32`,new Int32Array(o*s),[o,s]),l=a[0].data,u=c.data;for(let e=1;e<a.dims[0];++e){let t=a[e].data;for(let n=0;n<t.length;++n)t[n]>l[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;e<u.length;++e){let t=u[e];d[t]=t}let f=d.filter(e=>e!==void 0);i.push({segmentation:c,labels:f})}return i}function Kg(e,t,n,r){let i=[],a=[],o=[];for(let s=0;s<e.dims[0];++s){let c=e[s],l=t[s],u=$f(c.data)[1];if(u===r)continue;let d=Xf(c.data)[u];d>n&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function qg(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t<e.length;++t)e[t]===n&&(a.push(t),++o),c[t]>=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function Jg(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new H(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;t<e.length;++t)e[t]=Kp(e[t],o,`bilinear`,!1);let d=new Int32Array(e[0].data.length),f=new Float32Array(e[0].data.length);for(let n=0;n<e.length;++n){let r=t[n],i=e[n].data;for(let e=0;e<i.length;++e)i[e]*=r,i[e]>f[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a<n.length;++a){let o=n[a],[s,c]=qg(d,e,a,r,i);if(s){++p;for(let e of c)m[e]=p;u.push({id:p,label_id:o,score:t[a]})}}return[l,u]}function Yg(e,t,n=28,r=3136,i=0xf5000,a=1){if(e<n||t<n){let r=Math.max(n/e,n/t);e=Math.round(e*r),t=Math.round(t*r)}if(Math.max(e,t)/Math.min(e,t)>200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/n)*n,s=Math.round(t/n)*n;if(a*o*s>i){let r=Math.sqrt(a*e*t/i);o=Math.max(n,Math.floor(e/r/n)*n),s=Math.max(n,Math.floor(t/r/n)*n)}else if(a*o*s<r){let i=Math.sqrt(r/(a*e*t));o=Math.ceil(e*i/n)*n,s=Math.ceil(t*i/n)*n}return[s,o]}function Xg(e,t=.5,n=.5,r=.8,i=null,a=null){i===null&&(N.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\"),i=/* @__PURE__ */ new Set);let o=e.class_queries_logits??e.logits,s=(e.masks_queries_logits??e.pred_masks).sigmoid(),[c,l,u]=o.dims;if(--u,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 d=[];for(let e=0;e<c;++e){let c=a===null?null:a[e],l=o[e],f=s[e],[p,m,h]=Kg(l,f,t,u);if(h.length===0){let[e,t]=c??f.dims.slice(-2),n=new H(`int32`,new Int32Array(e*t).fill(-1),[e,t]);d.push({segmentation:n,segments_info:[]});continue}let[g,_]=Jg(p,m,h,n,r,i,c);d.push({segmentation:g,segments_info:_})}return d}function Zg(e,t=.5,n=null){throw Error(\"`post_process_instance_segmentation` is not yet implemented.\")}var q=class extends Vs{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,n=2){let r=e.height,i=e.width,a=t.height,o=t.width,s=Math.min(r,a),c=Math.min(i,o);return s===r&&c===i?e:(r>i?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=Qf(n.data)[0],i=$f(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;e<n.height;++e){let t=e*n.width;for(let d=0;d<n.width;++d)(u[t+d]-r)/i<a&&(o=Math.min(o,d),s=Math.min(s,e),c=Math.max(c,d),l=Math.max(l,e))}return e=await e.crop([o,s,c,l]),e}pad_image(e,t,n,{mode:r=`constant`,center:i=!1,constant_values:a=0}={}){let[o,s,c]=t,l,u;if(typeof n==`number`?(l=n,u=n):n===`square`?l=u=Math.max(o,s):(l=n.width,u=n.height),l!==s||u!==o){let n=new Float32Array(l*u*c);if(Array.isArray(a))for(let e=0;e<n.length;++e)n[e]=a[e%c];else a!==0&&n.fill(a);let[d,f]=i?[Math.floor((l-s)/2),Math.floor((u-o)/2)]:[0,0];for(let t=0;t<o;++t){let r=(t+f)*l,i=t*s;for(let t=0;t<s;++t){let a=(r+t+d)*c,o=(i+t)*c;for(let t=0;t<c;++t)n[a+t]=e[o+t]}}if(r===`symmetric`){if(i)throw Error(\"`center` padding is not supported when `mode` is set to `symmetric`.\");let t=o-1,r=s-1;for(let i=0;i<u;++i){let a=i*l,u=Ys(i,t)*s;for(let t=0;t<l;++t){if(i<o&&t<s)continue;let l=(a+t)*c,d=(u+Ys(t,r))*c;for(let t=0;t<c;++t)n[l+t]=e[d+t]}}}e=n,t=[u,l,c]}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[n,r]=e.size,i,a;if(this.do_thumbnail){let{height:e,width:n}=t;i=Math.min(e,n)}else Number.isInteger(t)?(i=t,a=this.config.max_size??i):t!==void 0&&(i=t.shortest_edge,a=t.longest_edge);if(i!==void 0||a!==void 0){let e=i===void 0?1:Math.max(i/n,i/r),t=n*e,o=r*e,s=a===void 0?1:Math.min(a/t,a/o),c=Math.floor(Number((t*s).toFixed(2))),l=Math.floor(Number((o*s).toFixed(2)));return this.size_divisibility!==void 0&&([c,l]=Hg([c,l],this.size_divisibility)),[c,l]}if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let e=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=i/r,a=e/n;Math.abs(1-a)<Math.abs(1-t)?t=a:a=t,i=Vg(t*r,this.config.ensure_multiple_of),e=Vg(a*n,this.config.ensure_multiple_of)}return[e,i]}if(this.size_divisibility!==void 0)return Hg([n,r],this.size_divisibility);throw Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(t)}`)}async resize(e){let[t,n]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,n,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:n=null,do_convert_rgb:r=null,do_convert_grayscale:i=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[o,s]=e.size;if(r??this.do_convert_rgb?e=e.rgb():i&&(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 t,n;Number.isInteger(this.crop_size)?(t=this.crop_size,n=this.crop_size):(t=this.crop_size.width,n=this.crop_size.height),e=await e.center_crop(t,n)}let c=[e.height,e.width],l=Float32Array.from(e.data),u=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(l),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=Array(e.channels).fill(t));let n=this.image_std;if(Array.isArray(this.image_std)||(n=Array(e.channels).fill(n)),t.length!==e.channels||n.length!==e.channels)throw Error(`When set to arrays, the length of \\`image_mean\\` (${t.length}) and \\`image_std\\` (${n.length}) must match the number of channels in the image (${e.channels}).`);for(let r=0;r<l.length;r+=e.channels)for(let i=0;i<e.channels;++i)l[r+i]=(l[r+i]-t[i])/n[i]}if(n??this.do_pad){if(this.pad_size){let t=this.pad_image(l,[e.height,e.width,e.channels],this.pad_size);[l,u]=t}else if(this.size_divisibility){let e=Math.ceil(u[1]/this.size_divisibility)*this.size_divisibility,t=Math.ceil(u[0]/this.size_divisibility)*this.size_divisibility;[l,u]=this.pad_image(l,u,{width:e,height:t})}}if(a??this.do_flip_channel_order){if(u[2]!==3)throw Error(`Flipping channel order is only supported for RGB images.`);for(let e=0;e<l.length;e+=3){let t=l[e];l[e]=l[e+2],l[e+2]=t}}let d=new H(`float32`,l,u).permute(2,0,1);return{original_size:[s,o],reshaped_input_size:c,pixel_values:d}}async _call(e,...t){Array.isArray(e)||(e=[e]);let n=await Promise.all(e.map(e=>this.preprocess(e)));return{pixel_values:nm(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t);return new this(n)}},Qg={};us(Qg,{BeitFeatureExtractor:()=>$g,BitImageProcessor:()=>e_,CHMv2ImageProcessor:()=>n_,CLIPFeatureExtractor:()=>i_,CLIPImageProcessor:()=>r_,ChineseCLIPFeatureExtractor:()=>t_,ConvNextFeatureExtractor:()=>o_,ConvNextImageProcessor:()=>a_,DINOv3ViTImageProcessor:()=>d_,DPTFeatureExtractor:()=>h_,DPTImageProcessor:()=>m_,DeiTFeatureExtractor:()=>c_,DeiTImageProcessor:()=>s_,DetrFeatureExtractor:()=>u_,DetrImageProcessor:()=>l_,DonutFeatureExtractor:()=>p_,DonutImageProcessor:()=>f_,EfficientNetImageProcessor:()=>g_,GLPNFeatureExtractor:()=>b_,Gemma3ImageProcessor:()=>__,Gemma4ImageProcessor:()=>Fg,Glm46VImageProcessor:()=>y_,GroundingDinoImageProcessor:()=>x_,Idefics3ImageProcessor:()=>S_,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>w_,Lfm2VlImageProcessor:()=>A_,Lfm3VlImageProcessor:()=>j_,LlavaOnevisionImageProcessor:()=>M_,Mask2FormerImageProcessor:()=>F_,MaskFormerFeatureExtractor:()=>P_,MaskFormerImageProcessor:()=>N_,MobileNetV1FeatureExtractor:()=>L_,MobileNetV1ImageProcessor:()=>I_,MobileNetV2FeatureExtractor:()=>z_,MobileNetV2ImageProcessor:()=>R_,MobileNetV3FeatureExtractor:()=>V_,MobileNetV3ImageProcessor:()=>B_,MobileNetV4FeatureExtractor:()=>U_,MobileNetV4ImageProcessor:()=>H_,MobileViTFeatureExtractor:()=>G_,MobileViTImageProcessor:()=>W_,NougatImageProcessor:()=>K_,OwlViTFeatureExtractor:()=>J_,OwlViTImageProcessor:()=>q_,Owlv2ImageProcessor:()=>Y_,Phi3VImageProcessor:()=>t1,PixtralImageProcessor:()=>n1,PvtImageProcessor:()=>r1,Qwen2VLImageProcessor:()=>v_,RTDetrImageProcessor:()=>i1,Sam2ImageProcessor:()=>a1,Sam3ImageProcessor:()=>a1,SamImageProcessor:()=>a1,SapiensFeatureExtractor:()=>s1,SapiensImageProcessor:()=>o1,SegformerFeatureExtractor:()=>l1,SegformerImageProcessor:()=>c1,SiglipImageProcessor:()=>u1,SmolVLMImageProcessor:()=>S_,Swin2SRImageProcessor:()=>d1,VLMImageProcessor:()=>C_,ViTFeatureExtractor:()=>p1,ViTImageProcessor:()=>f1,VitMatteImageProcessor:()=>m1,VitPoseImageProcessor:()=>h1,YolosFeatureExtractor:()=>_1,YolosImageProcessor:()=>g1});var $g=class extends q{},e_=class extends q{},t_=class extends q{},n_=class extends q{},r_=class extends q{},i_=class extends r_{},a_=class extends q{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},o_=class extends a_{},s_=class extends q{},c_=class extends s_{},l_=class extends q{async _call(e){let t=await super._call(e),n=cm([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Wg(...e)}post_process_panoptic_segmentation(...e){return Xg(...e)}post_process_instance_segmentation(...e){return Zg(...e)}},u_=class extends l_{},d_=class extends q{},f_=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},p_=class extends f_{},m_=class extends q{},h_=class extends m_{},g_=class extends q{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},__=class extends q{},v_=class extends q{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 n=this.patch_size*this.merge_size;return Yg(e.height,e.width,n,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:n,original_sizes:r,reshaped_input_sizes:i}=await super._call(e,...t),a=n,{temporal_patch_size:o,merge_size:s,patch_size:c}=this.config;a.dims[0]===1&&(a=U(Array.from({length:o},()=>a),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new H(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},y_=class extends v_{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return Yg(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},b_=class extends q{},x_=class extends q{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=um([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},S_=class extends q{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[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await qp(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,U(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>qp(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(U(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=cm([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=cm([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;r<l;++r){let a=i[r].dims[0];if(a<e){i[r]=U([i[r],cm([e-a,d,f,p],0)],0);let o=r*n+a*f*p,s=(r+1)*n;t.fill(!1,o,s)}}m=nm(i,0)}return{pixel_values:m,pixel_attention_mask:h,original_sizes:s,reshaped_input_sizes:c,...n?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){let n=t,r=t,i=[],[a,o]=e.dims.slice(-2),s=0,c=0;if(a>n||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;n<s;++n)for(let r=0;r<c;++r){let u,d,f,p;n===s-1?(d=a-t,p=a):(d=n*t,p=(n+1)*t),r===c-1?(u=o-l,f=o):(u=r*l,f=(r+1)*l);let m=await Zp(e,[d,u],[p,f],[2,3]);i.push(m)}let u=n,d=r;(a!==u||o!==d)&&(e=await qp(e,{size:[u,d]}))}return i.push(e),{frames:i,num_splits_h:s,num_splits_w:c}}},C_=class extends q{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(e=>e*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},w_=class extends q{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function T_(e,t){return Math.round(e/t)*t}function E_(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t<a?(a=t,o=n):t===a&&s>.5*i*i*n[0]*n[1]&&(o=n)}return o}function D_(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function O_(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;e<n;++e){let n=e*r*d,i=e*o*s*c;for(let e=0;e<o;++e)for(let o=0;o<s;++o){let f=i+(e*s+o)*c;for(let i=0;i<t;++i){let s=(e*t+i)*a+o*t;for(let e=0;e<t;++e){let t=s+e;for(let e=0;e<r;++e)u[f++]=l[n+e*d+t]}}}}return new H(`float32`,u,[n,o*s,c])}function k_(e,t){let[,n,r]=e.dims,i=new BigInt64Array(t);i.fill(1n,0,n);let a=e;if(n<t){let n=new Float32Array(t*r);n.set(e.data),a=new H(`float32`,n,[1,t,r])}return{padded:a,mask:new H(`int64`,i,[t])}}var A_=class extends q{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,n=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,n)}_is_image_too_large(e,t){let n=this.encoder_patch_size*this.downsample_factor;return Math.max(this.encoder_patch_size,T_(e,n))*Math.max(this.encoder_patch_size,T_(t,n))>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=D_(this.min_tiles,this.max_tiles),[r,i]=E_(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=Yg(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&(this.min_tiles!==1||this.max_tiles!==1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await qp(l,{size:[a,i]});m=[];for(let t=0;t<r;++t)for(let n=0;n<e;++n){let e=t*this.tile_size,r=n*this.tile_size;m.push(o.slice(null,null,[e,e+this.tile_size],[r,r+this.tile_size]))}this.use_thumbnail&&e*r!==1&&m.push(await qp(l,{size:[p,f]}))}else m=[await qp(l,{size:[p,f]})];for(let e of m){let[,,t,n]=e.dims,{padded:o,mask:s}=k_(O_(e,this.encoder_patch_size),this.max_num_patches);r.push(o),i.push(s),a.push([Math.floor(t/this.encoder_patch_size),Math.floor(n/this.encoder_patch_size)])}o.push(h),s.push(g),c.push([p,f])}}let l={pixel_values:U(r,0),pixel_attention_mask:nm(i,0),spatial_shapes:new H(`int64`,BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(l.image_rows=o,l.image_cols=s,l.image_sizes=c),l}},j_=class extends v_{async _call(e,...t){Array.isArray(e)||(e=[e]);let n=await Promise.all(e.map(e=>super._call(e,...t)));return{pixel_values:U(n.map(e=>e.pixel_values),0),image_grid_thw:U(n.map(e=>e.image_grid_thw),0),original_sizes:n.flatMap(e=>e.original_sizes),reshaped_input_sizes:n.flatMap(e=>e.reshaped_input_sizes)}}},M_=class extends q{},N_=class extends q{post_process_panoptic_segmentation(...e){return Xg(...e)}post_process_instance_segmentation(...e){return Zg(...e)}},P_=class extends N_{},F_=class extends N_{},I_=class extends q{},L_=class extends I_{},R_=class extends q{},z_=class extends R_{},B_=class extends q{},V_=class extends B_{},H_=class extends q{},U_=class extends H_{},W_=class extends q{},G_=class extends W_{},K_=class extends f_{},q_=class extends q{post_process_object_detection(...e){return Wg(...e)}},J_=class extends q_{},Y_=class extends q_{},X_=336,Z_=[2,3],{ceil:Q_,floor:$_,sqrt:e1}=Math,t1=class extends q{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:n}=this.config;return $_(($_(t/X_)*$_(e/X_)+1)*n+1+($_(t/X_)+1)*e1(n))}get_resize_output_image_size(e,t){let n=this._num_crops,[r,i]=e.size,a=r/i,o=1;for(;o*Math.ceil(o/a)<=n;)o+=1;--o;let s=Math.floor(o*336);return[s,Math.floor(s/a)]}pad_image(e,t,n,r={}){let[i,a]=t,o=X_*Q_(i/X_),s=X_*Q_(a/X_),c=[1,1,1].map((e,t)=>(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||e1(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await qp(e,{size:[X_,X_],mode:`bicubic`});if(t>0){let a=[],s=e1(t),c=$_(r/s),l=$_(n/s);for(let t=0;t<s;++t)for(let i=0;i<s;++i){let o,u,d,f;t===s-1?(u=n-l,f=n):(u=t*l,f=(t+1)*l),i===s-1?(o=r-c,d=r):(o=i*c,d=(i+1)*c);let p=await Zp(e,[u,o],[f,d],Z_);a.push(p)}let u=await qp(U(a,0),{size:[X_,X_],mode:`bicubic`});o.push(U([i,u],0))}else o.push(i)}let s=nm(o,0),c=a.map(e=>e.map(e=>X_*Q_(e/X_)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new H(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},n1=class extends q{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},r1=class extends q{},i1=class extends q{post_process_object_detection(...e){return Wg(...e)}},a1=class extends q{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=Ks(e);if(i.length===3)r||(i=[1,...i]),e=[e];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 r=0;r<e.length;++r){let[i,a]=t[r],[o,s]=n[r],c=[s/a,o/i];for(let t=0;t<e[r].length;++t)for(let n=0;n<e[r][t].length;++n)for(let i=0;i<e[r][t][n].length;++i)e[r][t][n][i]*=c[i%2]}return new H(`float32`,Float32Array.from(e.flat(1/0)),i)}add_input_labels(e,t){let n=Ks(e);if(n.length===2)n=[1,...n],e=[e];else if(n.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(n.some((e,n)=>e!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new H(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error(\"`input_points` must be provided if `input_labels` are provided.\");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;a<t.length;++a){let c=t[a],l=n[a],u=await qp(e[a],{mode:`bilinear`,size:s});if(u=u.slice(null,null,[0,l[0]],[0,l[1]]),u=await qp(u,{mode:`bilinear`,size:c}),i){let e=u.data,t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)e[n]>r&&(t[n]=1);u=new H(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},o1=class extends q{post_process_semantic_segmentation(...e){return Gg(...e)}},s1=class extends o1{},c1=class extends q{post_process_semantic_segmentation(...e){return Gg(...e)}},l1=class extends c1{},u1=class extends q{},d1=class extends q{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},f1=class extends q{},p1=class extends f1{},m1=class extends q{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:nm(n.map((e,t)=>U([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},h1=class extends q{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e<i;++e){let i=r[e],a=t[e],l=[];for(let e=0;e<a.length;++e){let t=a[e],r=[],c=[],u=[],d=t.at(-2)/s,f=t.at(-1)/o;for(let e=0;e<i.length;++e){let[t,a]=[0,0],o=0,s=-1/0,l=i[e];for(let e=0;e<l.length;++e){let n=l[e];for(let r=0;r<n.length;++r){let i=n[r];o+=i,s=Math.max(s,i),t+=(r+.5)*i,a+=e*i}}if(n!=null&&s<n)continue;let p=[d*t/o,f*a/o];r.push(p),u.push(e),c.push(s)}l.push({bbox:t,scores:c,labels:u,keypoints:r})}c.push(l)}return c}},g1=class extends q{post_process_object_detection(...e){return Wg(...e)}},_1=class extends g1{},v1=class{static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t),r=n.image_processor_type??n.feature_extractor_type,i=Qg[r?.replace(/Fast$/,``)];return i||=(r!==void 0&&N.warn(`Image processor type '${r}' not found, assuming base ImageProcessor. Please report this at ${wh}.`),q),new i(n)}},y1=class extends K{static tokenizer_class=G;static image_processor_class=v1;constructor(e,t,n){super(e,t,n);let{tasks_answer_post_processing_type:r,task_prompts_without_inputs:i,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(r??{})),this.task_prompts_without_inputs=new Map(Object.entries(i??{})),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 n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(`<s>`,``).replaceAll(`</s>`,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task \"${t}\" (of type \"${r}\") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},b1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.image_seq_length=this.config.image_seq_length;let{boi_token:r,image_token:i,eoi_token:a}=this.tokenizer.config;this.boi_token=r,this.image_token=i,this.eoi_token=a;let o=i.repeat(this.image_seq_length);this.full_image_sequence=`\n\n${r}${o}${a}\n\n`}async _call(e,t=null,n={}){typeof e==`string`&&(e=[e]);let r;return t&&(r=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,n),...r}}},x1=class extends K{static image_processor_class=v1;static feature_extractor_class=Sg;static tokenizer_class=G;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a;let d=a.repeat(this.audio_seq_length);this.full_audio_sequence=`\n\n${i}${d}${o}\n\n`,this.image_token_id=s,this.boi_token=c,this.image_token=l;let f=l.repeat(this.image_seq_length);this.full_image_sequence=`\n\n${c}${f}${u}\n\n`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},S1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static image_token=`<|image_pad|>`;async _call(e,t=null,...n){Array.isArray(e)||(e=[e]);let r,i;if(t&&(r=await this.image_processor(t),i=r.image_grid_thw),i){let t=this.image_processor.config.merge_size**2,n=0,r=this.constructor.image_token,a=i.tolist();e=e.map(e=>{for(;e.includes(r);){let i=Number(a[n++].reduce((e,t)=>e*t,1n));e=e.replace(r,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,r)})}return{...this.tokenizer(e),...r}}},C1=class extends S1{static image_token=`<|image|>`},w1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new H(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function T1(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var E1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>Ug(e))),f=[];for(let e=0;e<s;++e){let a=i===null?null:i[e];a!==null&&(d[e]=d[e].map(e=>e.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i<c;++i){let a=o[i];if(a<=n)continue;let c=d[e][i],u=l[e][i];s.push(a),m.push(c);let f=T1(u.gt(r),t[e]);p.push(f)}f.push({scores:s,boxes:m,labels:this.batch_decode(p)})}return f}};function D1(e,t,n,r,i,a){let o=``;for(let a=0;a<t;++a){for(let t=0;t<n;++t)o+=r+`<row_${a+1}_col_${t+1}>`+i.repeat(e);o+=`\n`}return o+=`\n${r}${a}`+i.repeat(e)+`${r}`,o}function O1(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function k1(e,t,n,r,i,a){return e===0&&t===0?O1(n,r,i,a):D1(n,e,t,r,i,a)}var A1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static uses_processor_config=!0;fake_image_token=`<fake_token_around_image>`;image_token=`<image>`;global_img_token=`<global-img>`;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;t<e.length;++t){let n=e[t],r=i[t],l=a[t];s.push(Zs(n,this.image_token));let u=r.map((e,t)=>k1(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;e<u.length;++e)f+=u[e]+d[e+1];c.push(f)}return{...this.tokenizer(c),...r}}},j1=class extends K{static image_processor_class=v1;static tokenizer_class=G;static uses_processor_config=!0;constructor(e,t,n){super(e,t,n),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:n=`default`}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(e=>e.images).flatMap(e=>e.images).map(e=>Mg.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of \"${this.image_tag}\" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e<o.length;++e){let t=Array(this.num_image_tokens).fill(c),n=a(o[e]);d=qs(d,[l],t,[u],n);let r=Array(this.num_image_tokens).fill(!0);f=qs(f,[!1],r,[!1],Array(n.length).fill(!1))}let p=[1,d.length],m={input_ids:new H(`int64`,d,p),attention_mask:new H(`int64`,Array(d.length).fill(1),p),images_seq_mask:new H(`bool`,f,p),images_emb_mask:new H(`bool`,Array(s*this.num_image_tokens).fill(!0),[1,s,this.num_image_tokens])};if(t&&t.length>0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},M1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},N1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??`<image>`,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e<h;++e)for(let n=0;n<g;++n)v+=`<|img_row_${e+1}_col_${n+1}|>`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},P1=class extends K{static tokenizer_class=G;static image_processor_class=v1;async _call(e,t=null,n={}){let r=e?await this.image_processor(e,n):{};if(t!==null){Array.isArray(t)||(t=[t]);let e=this.tokenizer.config.image_token??`<|image|>`,n=r.image_grid_thw?.tolist()??[],i=t.reduce((t,n)=>t+n.split(e).length-1,0);if(i!==n.length)throw Error(`Found ${i} ${e} tokens in the text but received ${n.length} images.`);let a=this.image_processor.config.merge_size,o=0;t=t.map(t=>t.replaceAll(e,()=>{let t=Number(n[o++].reduce((e,t)=>e*t,1n));return e.repeat(t/a**2)}))}return{...r,...t===null?{}:this.tokenizer(t,n)}}},F1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e<t.length;++e)t[e]=t[e].replace(i,i.repeat(s))}let i=t?this.tokenizer(t,n):{};return{...r,...i}}},I1={char:[`char_decode`,1],bpe:[`bpe_decode`,2],wp:[`wp_decode`,102]},L1=class extends K{static tokenizer_class=G;static image_processor_class=v1;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(!I1.hasOwnProperty(t))throw Error(`Format ${t} is not supported.`);let[n,r]=I1[t],i=this[n].bind(this),[a,o]=e.dims,s=[],c=[],l=e.tolist();for(let e=0;e<a;++e){let t=l[e],n=[],i=[];for(let e=1;e<o;++e){let[a,o]=$f(Xf(t[e]));if(i.push(a),o==r)break;n.push(o)}let a=i.length>0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e<r.length;++e){let[t,n]=$f([i[e],o[e],c[e]]);l.push([r[e],a[e],s[e]][n]),u.push(t)}return{generated_text:l,scores:u,char_preds:r,bpe_preds:a,wp_preds:s}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),n=await G.from_pretrained(`Xenova/gpt2`),r=await G.from_pretrained(`Xenova/bert-base-uncased`);return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:n,wp_tokenizer:r},t}async _call(e,t=null){let n=await this.image_processor(e);return t&&(n.labels=this.tokenizer(t).input_ids),n}},R1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},z1=class extends K{static tokenizer_class=G;static image_processor_class=v1},B1=`<image>`;function V1(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e}\n`}var H1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(N.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(B1))?a=t.map(e=>{let t=e.replaceAll(B1,B1.repeat(i)),n=t.lastIndexOf(B1),a=n===-1?0:n+B1.length;return t.slice(0,a)+r+t.slice(a)+`\n`}):(N.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(t=>V1(t,r,i,B1,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},U1=`<|image|>`,W1=/<\\|image_\\d+\\|>/g,G1=class extends K{static image_processor_class=v1;static tokenizer_class=G;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(W1).join(U1.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(U1);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},K1=class extends K{static tokenizer_class=G;static image_processor_class=v1;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e<t.length;++e){let n=i.repeat(d),r=n+a,s=n+o,c=r.repeat(u-1)+s;t[e]=t[e].replace(i,c)}}let i=t?this.tokenizer(t,n):{};return{...r,...i}}},q1=class extends K{static feature_extractor_class=mg;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}},J1=class extends S1{},Y1=class extends J1{},X1=class extends K{static image_processor_class=v1;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)}},Z1=class extends X1{},Q1=class extends Z1{},$1=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},e0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!0;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let i=t.length,{input_features:a}=await this.feature_extractor(t,{...n,max_length:i}),o=Math.round(i/this.config.encoder_ds_factor+1e-4),s=1+Math.ceil(o/this.config.stack_factor);r.audio_token_len=[s],r.audio_values=a;let c=this.config.audio_placeholder;if(!e.includes(c))throw Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(s))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},t0=`[AUDIO]`,n0=`[BEGIN_AUDIO]`,r0=375;function i0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.subarray(r,Math.min(r+t,e.length)));return n}var a0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!1;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){if(!e.includes(t0))throw Error(`The input text does not contain the audio token ${t0}.`);Array.isArray(t)||(t=[t]);let i=e.split(t0),a=i.length-1;if(a!==t.length)throw Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${a}).`);let o=this.feature_extractor.config.n_samples,s=t.map(e=>i0(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?U(u,0):u[0];let d=i[0];for(let e=0;e<c.length;++e){d+=n0;for(let t=0;t<c[e];++t)d+=t0.repeat(r0);d+=i[e+1]}e=d}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},o0=32,s0=6,c0=8,l0=10,u0=32,d0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(s0+1)*c0}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 c0*e+t}get num_right_pad_tokens(){return s0+1+l0}get audio_length_per_tok(){return c0}get raw_audio_length_per_tok(){return c0*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:n=!0}={}){if(jh(e,`VoxtralRealtimeProcessor`),!t&&!n)throw Error(\"In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.\");if(n){if(t){let t=o0*this.raw_audio_length_per_tok,n=new Float32Array(t+e.length);n.set(e,t);let r=await this.feature_extractor(n,{center:!0}),i=1+(o0+s0),a=new BigInt64Array(i).fill(BigInt(u0));return a[0]=1n,{input_ids:new H(`int64`,a,[1,i]),...r}}{let t=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+t);return n.set(e),await this.feature_extractor(n,{center:!0})}}return await this.feature_extractor(e,{center:!1})}},f0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},p0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},m0=class extends K{static tokenizer_class=G;static feature_extractor_class=Sg;async _call(e){return await this.feature_extractor(e)}},h0=class{static async from_pretrained(e,t={}){let n=await qf(e,Eh,!0,t),{image_processor_type:r,feature_extractor_type:i,processor_class:a}=n;if(a&&kh[a])return kh[a].from_pretrained(e,t);if(!r&&!i)throw Error(\"No `image_processor_type` or `feature_extractor_type` found in the config.\");let o={};if(r){let e=Qg[r.replace(/Fast$/,``)];if(!e)throw Error(`Unknown image_processor_type: '${r}'.`);o.image_processor=new e(n)}if(i){let e=Qg[i];if(e)o.image_processor=new e(n);else{let e=Mh[i];if(!e)throw Error(`Unknown feature_extractor_type: '${i}'.`);o.feature_extractor=new e(n)}}return new K({},o,null)}};async function g0(e,t){return await qf(e,`config.json`,!0,t)}function _0(e){let t={},n={};switch(e.model_type){case`llava`:case`paligemma`:case`gemma3`:case`florence2`:case`llava_onevision`:case`idefics3`:case`granite_speech`:case`ultravox`:case`voxtral`:case`voxtral_realtime`:case`smolvlm`:case`gemma3n`:case`gemma4`:case`lfm2_vl`:case`lfm3_vl`:case`chatterbox`:case`lighton_ocr`:case`glm_ocr`:case`mistral3`:case`qwen2_5_vl`:case`qwen3_vl`:case`qwen3_vl_moe`:n=_0(e.text_config);break;case`moondream1`:n=_0(e.phi_config);break;case`musicgen`:n=_0(e.decoder);break;case`multi_modality`:n=_0(e.language_config);break;case`gpt2`:case`gptj`:case`jais`:case`codegen`:case`gpt_bigcode`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`n_embd`;break;case`gpt_neox`:case`stablelm`:case`opt`:case`falcon`:case`modernbert-decoder`:t.num_heads=`num_attention_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`;break;case`gpt_oss`:case`llama`:case`llama4_text`:case`nanochat`:case`apertus`:case`arcee`:case`afmoe`:case`lfm2`:case`lfm2_moe`:case`lfm3`:case`smollm3`:case`olmo`:case`olmo2`:case`olmo3`:case`mobilellm`:case`granite`:case`granitemoehybrid`:case`cohere`:case`cohere2`:case`mistral`:case`voxtral_realtime_text`:case`voxtral_realtime_encoder`:case`starcoder2`:case`qwen2`:case`qwen2_moe`:case`qwen2_vl`:case`qwen2_vl_text`:case`qwen2_5_vl_text`:case`qwen3_moe`:case`qwen3_vl_text`:case`qwen3_vl_moe_text`:case`phi`:case`phi3`:case`phi3_v`:case`llava_qwen2`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`,t.num_attention_heads=`num_attention_heads`,t.dim_kv=`head_dim`;break;case`qwen3`:case`solar_open`:case`glm_ocr_text`:case`gemma`:case`gemma2`:case`vaultgemma`:case`gemma3_text`:case`gemma3n_text`:case`gemma4_text`:case`glm`:case`helium`:case`ernie4_5`:case`hunyuan_v1_dense`:case`falcon_h1`:case`nemotron_h`:case`ministral`:case`ministral3`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=`head_dim`;break;case`openelm`:t.num_heads=`num_kv_heads`,t.num_layers=`num_transformer_layers`,t.dim_kv=`head_dim`;break;case`gpt_neo`:case`donut-swin`:t.num_heads=`num_heads`,t.num_layers=`num_layers`,t.hidden_size=`hidden_size`;break;case`bloom`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`hidden_size`;break;case`mpt`:t.num_heads=`n_heads`,t.num_layers=`n_layers`,t.hidden_size=`d_model`;break;case`exaone`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_layers`,t.dim_kv=`head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`youtu`:case`deepseek_v3`:case`deepseek_v4`:case`glm_moe_dsa`:case`mistral4`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=e.model_type===`deepseek_v4`?`head_dim`:`qk_head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`zaya`:case`hrm_text`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`,t.dim_kv=`head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`t5`:case`mt5`:case`longt5`:t.num_decoder_layers=`num_decoder_layers`,t.num_decoder_heads=`num_heads`,t.decoder_dim_kv=`d_kv`,t.num_encoder_layers=`num_layers`,t.num_encoder_heads=`num_heads`,t.encoder_dim_kv=`d_kv`;break;case`bart`:case`mbart`:case`marian`:case`whisper`:case`lite-whisper`:case`m2m_100`:case`blenderbot`:case`blenderbot-small`:case`florence2_language`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`d_model`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`d_model`;break;case`speecht5`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`hidden_size`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`hidden_size`;break;case`trocr`:t.num_encoder_layers=t.num_decoder_layers=`decoder_layers`,t.num_encoder_heads=t.num_decoder_heads=`decoder_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`d_model`;break;case`musicgen_decoder`:t.num_encoder_layers=t.num_decoder_layers=`num_hidden_layers`,t.num_encoder_heads=t.num_decoder_heads=`num_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`moonshine`:t.num_decoder_layers=`decoder_num_hidden_layers`,t.num_decoder_heads=`decoder_num_key_value_heads`,t.num_encoder_layers=`encoder_num_hidden_layers`,t.num_encoder_heads=`encoder_num_key_value_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`cohere_asr`:t.num_decoder_layers=`num_hidden_layers`,t.num_decoder_heads=`num_key_value_heads`,t.decoder_hidden_size=`hidden_size`,t.decoder_dim_kv=`head_dim`;let{num_hidden_layers:r,num_attention_heads:i,hidden_size:a}=e.encoder_config;n={num_encoder_layers:r,num_encoder_heads:i,encoder_hidden_size:a,encoder_dim_kv:e.head_dim};break;case`vision-encoder-decoder`:let o=_0(e.decoder),s=`num_decoder_layers`in o,c=Xs(e,[`model_type`,`is_encoder_decoder`]);return s?(c.num_decoder_layers=o.num_decoder_layers,c.num_decoder_heads=o.num_decoder_heads,c.decoder_hidden_size=o.decoder_hidden_size,c.num_encoder_layers=o.num_encoder_layers,c.num_encoder_heads=o.num_encoder_heads,c.encoder_hidden_size=o.encoder_hidden_size):(c.num_layers=o.num_layers,c.num_heads=o.num_heads,c.hidden_size=o.hidden_size),c}let r={...n,...Xs(e,[`model_type`,`multi_query`,`is_encoder_decoder`])};for(let n in t)r[n]=e[t[n]];return r}function v0(e,t){e instanceof b0||(e=new b0(e));let n=t?.prefix??`past_key_values`,r=n===`present`?`present`:`past`,i=/* @__PURE__ */ new Set;if([`lfm2`,`lfm2_moe`,`lfm3`].includes(e.model_type)){let{layer_types:t}=e;for(let e=0;e<t.length;++e)if(t[e]===`full_attention`||t[e]===`sliding_attention`)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);else if(t[e]===`conv`)i.add(`${r}_conv.${e}`);else throw Error(`Unsupported layer type: ${t[e]}`);return i}if([`granitemoehybrid`,`falcon_h1`,`nemotron_h`].includes(e.model_type)){let t=e,a=t.layer_types??t.layers_block_type,o=t.num_hidden_layers??a?.length;for(let e=0;e<o;++e)a&&a[e]!==`mamba`||(i.add(`${r}_conv.${e}`),i.add(`${r}_ssm.${e}`)),a&&a[e]!==`attention`||(i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`));return i}if([`qwen3_next`,`qwen3_5_text`,`qwen3_5_moe_text`,`olmo_hybrid`].includes(e.model_type)){let{layer_types:t}=e;for(let a=0;a<t.length;++a)if(t[a]===`full_attention`)i.add(`${n}.${a}.key`),i.add(`${n}.${a}.value`);else if(t[a]===`linear_attention`)e.model_type===`olmo_hybrid`?(i.add(`${r}_conv.${a}.key`),i.add(`${r}_conv.${a}.value`),i.add(`${r}_conv.${a}.query`)):i.add(`${r}_conv.${a}`),i.add(`${r}_recurrent.${a}`);else throw Error(`Unsupported layer type: ${t[a]}`);return i}if([`gemma4`,`gemma4_text`].includes(e.model_type)){let t=e.model_type===`gemma4`?e.text_config:e,r=t.num_hidden_layers-(t.num_kv_shared_layers??0);for(let e=0;e<r;++e)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);return i}if(e.model_type===`deepseek_v4`){let{layer_types:t,num_hidden_layers:a}=e;for(let e=0;e<a;++e){i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);let a=t[e];if(a===`compressed_sparse_attention`)i.add(`${r}_compressor.${e}.kv`),i.add(`${r}_compressor.${e}.gate`),i.add(`${r}_indexer.${e}.kv`),i.add(`${r}_indexer.${e}.gate`);else if(a===`heavily_compressed_attention`)i.add(`${r}_compressor.${e}.kv`),i.add(`${r}_compressor.${e}.gate`);else if(a&&a!==`sliding_attention`)throw Error(`Unsupported layer type: ${a}`)}return i}if(e.model_type===`zaya`){let{num_hidden_layers:t,cca_time1:r}=e,a=r??1;for(let e=0;e<t;e+=a)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`),i.add(`${n}.${e}.conv_state`),i.add(`${n}.${e}.shift_state`);return i}if([`lfm2_vl`,`lfm3_vl`,`qwen3_5`,`qwen3_5_moe`,`voxtral_realtime`].includes(e.model_type)){let n;return n=e.model_type===`voxtral_realtime`&&t?.session_name===`audio_encoder`?e.audio_config:e.text_config,v0(n,t)}return y0(e,{prefix:n})}function y0(e,{prefix:t=`past_key_values`}={}){let n=/* @__PURE__ */ new Set,r=e.normalized_config;if(r.is_encoder_decoder&&`num_encoder_heads`in r&&`num_decoder_heads`in r)for(let e=0;e<r.num_decoder_layers;++e)n.add(`${t}.${e}.encoder.key`),n.add(`${t}.${e}.encoder.value`),n.add(`${t}.${e}.decoder.key`),n.add(`${t}.${e}.decoder.value`);else if(r.multi_query)for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key_value`);else for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key`),n.add(`${t}.${e}.value`);return n}var b0=class e{model_type=null;is_encoder_decoder=!1;max_position_embeddings;\"transformers.js_config\";constructor(e){Object.assign(this,e),this.normalized_config=_0(this)}static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:o=`main`}={}){r&&!(r instanceof e)&&(r=new e(r));let s=r??await g0(t,{progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:o});return new this(s)}},x0=class{static async from_pretrained(...e){return b0.from_pretrained(...e)}};function S0(e,t,n){return e?typeof e==`object`&&e?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(n)?+e[n]:0:+e:0}function C0(e,t){let n=[];for(let r=0;r<t;++r)n.push(`${e}_data${r===0?``:`_`+r}`);return n}async function w0(e,t,n,r){let i=`${t}${r}.onnx`;return await Gf(e,`${n.subfolder??``}/${i}`,!0,n,j.IS_NODE_ENV)}async function T0(e,t,n,r,i,a={}){let o=`${t}${n}.onnx`,s=j.IS_NODE_ENV,c=[],l=S0(i,o,t);if(l>0){if(l>hf)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${hf}).`);let t=C0(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(Gf(e,t,!0,r,s).then(e=>e instanceof Uint8Array?{path:n,data:e}:n))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await Gf(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function E0(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=Ip(n.device??a.device,t,{warn:e=>N.info(e)}),s=Sp(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=Hp(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>N.info(e)});if(!Vp.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(Rp).join(`, `)}`);if(o===`webgpu`&&!j.IS_NODE_ENV&&l===Rp.fp16&&!await Lp())throw Error(`The device (${o}) does not support fp16.`);let u=Vp[l],d={...n.session_options};d.executionProviders??=s;let f=a.free_dimension_overrides;f?d.freeDimensionOverrides??=f:o.startsWith(`webnn`)&&!d.freeDimensionOverrides&&N.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config[\"transformers.js_config\"][\"device_config\"][\"${o}\"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=w0(e,t,n,u),m=await T0(e,t,u,n,n.use_external_data_format??a.use_external_data_format,d);if(m.length>0&&(!j.IS_NODE_ENV||m.some(e=>typeof e!=`string`))&&(d.externalData=m),r&&o===`webgpu`){let e=v0(n.config,{prefix:`present`,session_name:i});if(e.size>0&&!jp()){let t={};for(let n of e)t[n]=`gpu-buffer`;d.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:d,session_config:{dtype:l,device:o}}}async function D0(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await E0(e,t[i],n,a,i);return[i,await Ep(o,s,c)]})))}function O0(e){for(let t in e)kp(e[t])?e[t]=new H(e[t]):typeof e[t]==`object`&&O0(e[t]);return e}async function J(e,t){let n=k0(e,t);try{return O0(await Op(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return j.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw N.error(`An error occurred during model execution: \"${e}\".`),N.error(`Inputs given to model:`,t),e}}function k0(e,t){let n=/* @__PURE__ */ Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];e instanceof H?n[i]=jp()?e.clone():e:r.push(i)}if(r.length>0)throw Error(`An error occurred during model execution: \"Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));N.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: \"${n.join(`, `)}\".`)}return n}var A0=class{},j0=class extends A0{constructor({last_hidden_state:e,hidden_states:t=null,attentions:n=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=n}},Y=class extends A0{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},M0=class extends A0{constructor({logits:e}){super(),this.logits=e}},N0=class extends A0{constructor({logits:e}){super(),this.logits=e}},P0=class extends A0{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},F0=class extends A0{constructor({logits:e}){super(),this.logits=e}},I0=class extends A0{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}},L0=class extends A0{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=i}},R0=class extends A0{constructor({alphas:e}){super(),this.alphas=e}},z0=class extends Vs{_call(e,t){throw Error(\"`_call` should be implemented in a subclass\")}},B0=class extends Vs{_call(e,t){throw Error(\"`_call` should be implemented in a subclass\")}},V0=class extends Vs{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},H0=class extends z0{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===1){let e=t[n].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}},U0=class extends z0{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.max_length-1){let e=t[n].data;e.fill(-1/0);for(let t of this.eos_token_id)e[t]=0}return t}},W0=class extends z0{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let n=0;n<e.length;++n){let e=t[n].data;for(let t of this.suppress_tokens)e[t]=-1/0}return t}},G0=class extends z0{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.begin_index){let e=t[n].data;for(let t of this.begin_suppress_tokens)e[t]=-1/0}return t}},K0=class extends z0{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,this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;if(r[this.no_timestamps_token_id]=-1/0,e[n].length===this.begin_index){r.subarray(0,this.timestamp_begin).fill(-1/0);continue}let i=e[n].slice(this.begin_index),a=i.length>=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=Zf(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>$f(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},q0=class extends z0{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){let t=[];for(let n=0;n<this.no_repeat_ngram_size;++n)t.push(e[r+n]);n.push(t.map(Number))}let r=/* @__PURE__ */ new Map;for(let e of n){let t=e.slice(0,e.length-1),n=JSON.stringify(t),i=r.get(n)??[];i.push(e[e.length-1]),r.set(n,i)}return r}getGeneratedNgrams(e,t){let n=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(n.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=this.calcBannedNgramTokens(e[n]);for(let e of i)r[e]=-1/0}return t}},J0=class extends z0{constructor(e){super(),this.penalty=e}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;for(let t of new Set(e[n])){let e=Number(t);r[e]<0?r[e]*=this.penalty:r[e]/=this.penalty}}return t}},Y0=class extends z0{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length<this.min_length){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},X0=class extends z0{constructor(e,t,n){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(n)?n:[n]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length-this.prompt_length_to_skip<this.min_new_tokens){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},Z0=class extends z0{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=e[n];for(let e of this.bad_words_ids){if(i.length<e.length-1)continue;let t=!0;for(let n=1;n<=e.length-1;++n)if(e.at(-n-1)!=i.at(-n)){t=!1;break}t&&(r[e.at(-1)]=-1/0)}}return t}},Q0=class extends z0{constructor(e){if(super(),e<=1)throw Error(`Require guidance scale >1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;e<i.data.length;++e)i.data[e]+=(r.data[e]-i.data[e])*this.guidance_scale;return i}},$0=class extends B0{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 n=t.data;for(let e=0;e<n.length;++e)n[e]/=this.temperature;return t}},ev=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Xs(e,Object.getOwnPropertyNames(this)))}},tv=class extends Vs{_call(e,t){throw Error(`StoppingCriteria needs to be subclassed`)}},nv=class e extends Vs{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(t){t instanceof e?t=t.criteria:t instanceof tv&&(t=[t]),this.criteria.push(...t)}_call(e,t){let n=Array(e.length).fill(!1);for(let r of this.criteria){let i=r(e,t);for(let e=0;e<n.length;++e)n[e]||=i[e]}return n}[Symbol.iterator](){return this.criteria.values()}},rv=class extends tv{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(e=>e.length>=this.max_length)}},iv=class extends tv{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},av=class extends Vs{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 n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return df(e)}static getSampler(e){if(e.do_sample)return new sv(e);if(e.num_beams>1)return new cv(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 ov(e)}},ov=class extends av{async sample(e){let t=$f(e.data)[1];return[[BigInt(t),0]]}},sv=class extends av{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[n,r]=await Yp(e,t),i=Xf(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},cv=class extends av{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[n,r]=await Yp(e,t),i=Xf(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},lv=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key \"${t}\" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof H))throw TypeError(`Expected a Tensor for key \"${t}\", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},X={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16,MultimodalEncoder:17},uv={[X.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[X.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[X.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[X.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[X.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[X.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[X.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[X.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...uv[X.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},[X.MultimodalEncoder]:{sessions:(e,t)=>({model:t.model_file_name??`model`,...e.vision_config&&{vision_encoder:`vision_encoder`},...e.audio_config&&{audio_encoder:`audio_encoder`}})},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function dv(e,t,n={}){let r=uv[e]??uv.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function fv(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=xv.get(e);if(t!==void 0)return t}if(e.model_type){let t=xv.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(hv))if(t.has(e.model_type)){let n=xv.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;N.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${wh}`)}return X.EncoderOnly}function pv(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?Pf(bf(e,{cache_dir:n,local_files_only:r,revision:i}),()=>x0.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):x0.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function mv(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await pv(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=fv(t),f=(e,t=null)=>{t??=e;let n=Ip(l,e),r=Vp[Hp(u,e,n)]??``,i=`${t}${r}.onnx`,o=`${c}/${i}`;a.push(o);let d=S0(s,i,e);for(let e of C0(i,d)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=dv(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var hv=null;function gv(e){hv=e}function _v(e){if(e instanceof H)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 H(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}return new H(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function vv(e){return new H(`bool`,[e],[1])}var yv={[X.DecoderOnly]:{can_generate:!0,forward:Mv,prepare_inputs:Rv},[X.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Mv,prepare_inputs:Rv},[X.Seq2Seq]:{can_generate:!0,forward:wv,prepare_inputs:zv},[X.Vision2Seq]:{can_generate:!0,forward:wv,prepare_inputs:zv},[X.Musicgen]:{can_generate:!0,forward:wv},[X.EncoderDecoder]:{can_generate:!1,forward:wv},[X.ImageTextToText]:{can_generate:!0,forward:Fv,prepare_inputs:Bv},[X.AudioTextToText]:{can_generate:!0,forward:Pv,prepare_inputs:Bv},[X.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Bv},[X.Phi3V]:{can_generate:!0,prepare_inputs:Bv},[X.MultiModality]:{can_generate:!0},[X.AutoEncoder]:{can_generate:!1,forward:Ev},[X.Chatterbox]:{can_generate:!0,forward:Tv},[X.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Rv},default:{can_generate:!1,forward:Tv}};function bv(e,t){let n=xv.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=xv.get(i);e!==void 0&&(n=e,r=!0)}let a=yv[n]??yv.default,o=uv[n]??uv.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var xv=/* @__PURE__ */ new Map,Sv=/* @__PURE__ */ new Map,Cv=/* @__PURE__ */ new Map,Z=class extends Vs{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=bv(Cv.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=Cv.get(this);n=f.config=await x0.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=bv(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&N.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${wh}.`)}if(t&&!(t instanceof Us)){let r={};try{let t=await mv(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>If(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){N.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new Us(t,r))}let _=[D0(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(Wv(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new V0;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new J0(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new q0(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new Z0(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new Y0(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new X0(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new H0(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new U0(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new W0(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new G0(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new Q0(e.guidance_scale)),e.temperature===0&&e.do_sample&&(N.warn(\"`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`.\"),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new $0(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=ev){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,Xs(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new nv;return e.max_length!==null&&n.push(new rv(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new iv(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[hv.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,hv.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,hv.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,hv.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Cv.get(this.constructor),n=/* @__PURE__ */ new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=Dv(t,n.past_key_values),n.input_ids=new H(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=U([n.decoder_attention_mask,um([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=U([n.attention_mask,um([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=Xs(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error(\"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...\")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...Xs(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Tv(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=U([i,lm(i,0)],0),`attention_mask`in t&&(t.attention_mask=U([t.attention_mask,pm(t.attention_mask)],0));else if(t.decoder_input_ids){let e=_v(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=U(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof H)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\\`decoder_start_token_id\\` expected to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=_v(o)}return s.decoder_attention_mask=dm(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=av.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate){if(t.output_attentions){let e=Ov(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,Xs(v,this._return_dict_in_generate_keys))}let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;t<e.dims.at(0);++t){let r=await h(e[t]);for(let[e,i]of r){let r=BigInt(e);g[t]+=i,_[t].push(r),n.push([r]);break}}if(i&&i.put(n),p(_).every(e=>e))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new H(`int64`,_.flat(),[_.length,_[0].length]),S=Dv(v,s.past_key_values),C=new Set(Object.values(S));for(let e of Object.values(v))e.location===`gpu-buffer`&&!C.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await S.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:S,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await J(r,Xs(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function wv(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Tv(e,Xs(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await Mv(e,o,!0)}async function Tv(e,t){let n=e.sessions.model,r=Xs(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error(\"Both `input_ids` and `inputs_embeds` are missing in the model inputs.\");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error(\"Both `input_ids` and `token_type_ids` are missing in the model inputs.\");r.token_type_ids=pm(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error(\"Both `pixel_values` and `pixel_mask` are missing in the model inputs.\");let e=r.pixel_values.dims;r.pixel_mask=um([e[0],e[2],e[3]])}return await J(n,r)}async function Ev(e,t){let n=await e.encode(t);return await e.decode(n)}function Dv(e,t){let n=/* @__PURE__ */ Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present_compressor`,`past_compressor`).replace(`present_indexer`,`past_indexer`).replace(`present`,`past_key_values`);n[i]=r.includes(`encoder`)&&t?t[i]:e[r]}return t?(t.update(n),t):new lv(n)}function Ov(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function kv(e,t){return e.map(e=>typeof e==`number`?e:t[e]??0)}function Av(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=v0(e.config),o=e.config?.normalized_config?.num_heads,s={batch_size:i};typeof o==`number`&&(s[`batch_size x num_heads`]=i*o);let c=/* @__PURE__ */ Object.create(null);for(let e of r.inputMetadata){if(!a.has(e.name))continue;let n=kv(e.shape,s),r=n.reduce((e,t)=>e*t,1),i=Up[e.type],o=new H(e.type,new i(r),n);t[e.name]=o,c[e.name]=o}return n?(n.update(c),n):new lv(c)}function jv(e,t,n){t.num_logits_to_keep||(e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes(`num_logits_to_keep`)&&(t.num_logits_to_keep=new H(`int64`,[n],[]))}async function Mv(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=vv(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=Lv(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),jv(e,a,0n),Av(e,a,i),await J(r,Xs(a,r.inputNames))}async function Nv(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,num_logits_to_keep:f=null,...p}){if(!c){c=await e.encode_text({input_ids:a,...p});let s=Xs(p,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...p});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=U([um([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`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:t,video_grid_thw:n}=p;[s]=e.get_rope_index(a,t,n,o)}return await Mv(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d,num_logits_to_keep:f},!0)}async function Pv(e,t){return await Nv(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 Fv(e,t){return await Nv(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 Iv(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;e<n;++e){let n=e*r,o=BigInt(t);for(let e=0;e<r;++e){let t=n+e;i[t]===0n?a[t]=BigInt(1):(a[t]=o,o+=i[t])}}return{data:a,dims:e.dims}}function Lv(e,t=null,n=0){let{input_ids:r,inputs_embeds:i,attention_mask:a}=e,{data:o,dims:s}=Iv(a,n),c=new H(`int64`,o,s);if(t){let e=-(r??i).dims.at(1);c=c.slice(null,[e,null])}return c}function Rv(e,t,n,r){let i=n.past_key_values?n.past_key_values.get_seq_length():0;if(jv(e,n,1n),!n.attention_mask){let e;for(let t of[`input_ids`,`inputs_embeds`,`position_ids`])if(n[t]){e=n[t].dims;break}if(!e)throw Error(`attention_mask is not provided, and unable to infer its shape from model inputs.`);n.attention_mask=um([e[0],i+e[1]])}if(n.past_key_values){let{input_ids:e,attention_mask:t}=n;t&&t.dims[1]>e.dims[1]||i<e.dims[1]&&(n.input_ids=e.slice(null,[i,null]))}return n}function zv(e,t,n,r){return n.past_key_values&&(t=t.map(e=>[e.at(-1)])),jv(e,n,1n),{...n,decoder_input_ids:_v(t)}}function Bv(e,...t){return e.config.is_encoder_decoder?zv(e,...t):Rv(e,...t)}function Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e<a.length;++e){let r=a[e],i=t[e];for(let e=0;e<r.length;++e)i[r[e]].data.set(n[c++].data)}return{inputs_embeds:t,attention_mask:i}}function Hv({image_token_id:e,inputs_embeds:t,image_features:n,input_ids:r,attention_mask:i}){return Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}function Uv({audio_token_id:e,inputs_embeds:t,audio_features:n,input_ids:r,attention_mask:i}){return Vv({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}async function Wv(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map(async r=>[r,await qf(e,t[r],!1,n)])))}var Gv={};us(Gv,{ASTForAudioClassification:()=>cy,ASTModel:()=>sy,ASTPreTrainedModel:()=>oy,AfmoeForCausalLM:()=>ny,AfmoeModel:()=>ty,AfmoePreTrainedModel:()=>ey,AlbertForMaskedLM:()=>Xv,AlbertForQuestionAnswering:()=>Yv,AlbertForSequenceClassification:()=>Jv,AlbertModel:()=>qv,AlbertPreTrainedModel:()=>Kv,ApertusForCausalLM:()=>$v,ApertusModel:()=>Qv,ApertusPreTrainedModel:()=>Zv,ArceeForCausalLM:()=>ay,ArceeModel:()=>iy,ArceePreTrainedModel:()=>ry,BartForConditionalGeneration:()=>dy,BartForSequenceClassification:()=>fy,BartModel:()=>uy,BartPretrainedModel:()=>ly,BaseModelOutput:()=>j0,BeitForImageClassification:()=>hy,BeitModel:()=>my,BeitPreTrainedModel:()=>py,BertForMaskedLM:()=>vy,BertForQuestionAnswering:()=>xy,BertForSequenceClassification:()=>yy,BertForTokenClassification:()=>by,BertModel:()=>_y,BertPreTrainedModel:()=>gy,BlenderbotForConditionalGeneration:()=>wy,BlenderbotModel:()=>Cy,BlenderbotPreTrainedModel:()=>Sy,BlenderbotSmallForConditionalGeneration:()=>Dy,BlenderbotSmallModel:()=>Ey,BlenderbotSmallPreTrainedModel:()=>Ty,BloomForCausalLM:()=>Ay,BloomModel:()=>ky,BloomPreTrainedModel:()=>Oy,CHMv2ForDepthEstimation:()=>Wy,CHMv2PreTrainedModel:()=>Uy,CLIPModel:()=>Xy,CLIPPreTrainedModel:()=>Yy,CLIPSegForImageSegmentation:()=>r2,CLIPSegModel:()=>n2,CLIPSegPreTrainedModel:()=>t2,CLIPTextModel:()=>Zy,CLIPTextModelWithProjection:()=>Qy,CLIPVisionModel:()=>$y,CLIPVisionModelWithProjection:()=>e2,CamembertForMaskedLM:()=>Ny,CamembertForQuestionAnswering:()=>Iy,CamembertForSequenceClassification:()=>Py,CamembertForTokenClassification:()=>Fy,CamembertModel:()=>My,CamembertPreTrainedModel:()=>jy,CausalLMOutput:()=>F0,CausalLMOutputWithPast:()=>I0,ChatterboxModel:()=>By,ChatterboxPreTrainedModel:()=>zy,ChineseCLIPModel:()=>Hy,ChineseCLIPPreTrainedModel:()=>Vy,ClapAudioModelWithProjection:()=>Jy,ClapModel:()=>Ky,ClapPreTrainedModel:()=>Gy,ClapTextModelWithProjection:()=>qy,CodeGenForCausalLM:()=>o2,CodeGenModel:()=>a2,CodeGenPreTrainedModel:()=>i2,Cohere2ForCausalLM:()=>f2,Cohere2Model:()=>d2,Cohere2PreTrainedModel:()=>u2,CohereAsrForConditionalGeneration:()=>h2,CohereAsrModel:()=>m2,CohereAsrPreTrainedModel:()=>p2,CohereForCausalLM:()=>l2,CohereModel:()=>c2,CoherePreTrainedModel:()=>s2,ConvBertForMaskedLM:()=>v2,ConvBertForQuestionAnswering:()=>x2,ConvBertForSequenceClassification:()=>y2,ConvBertForTokenClassification:()=>b2,ConvBertModel:()=>_2,ConvBertPreTrainedModel:()=>g2,ConvNextForImageClassification:()=>w2,ConvNextModel:()=>C2,ConvNextPreTrainedModel:()=>S2,ConvNextV2ForImageClassification:()=>D2,ConvNextV2Model:()=>E2,ConvNextV2PreTrainedModel:()=>T2,DFineForObjectDetection:()=>P2,DFineModel:()=>N2,DFinePreTrainedModel:()=>M2,DINOv3ConvNextModel:()=>D4,DINOv3ConvNextPreTrainedModel:()=>E4,DINOv3ViTModel:()=>k4,DINOv3ViTPreTrainedModel:()=>O4,DPTForDepthEstimation:()=>B4,DPTModel:()=>z4,DPTPreTrainedModel:()=>R4,DacDecoderModel:()=>B2,DacDecoderOutput:()=>I2,DacEncoderModel:()=>z2,DacEncoderOutput:()=>F2,DacModel:()=>R2,DacPreTrainedModel:()=>L2,DebertaForMaskedLM:()=>U2,DebertaForQuestionAnswering:()=>K2,DebertaForSequenceClassification:()=>W2,DebertaForTokenClassification:()=>G2,DebertaModel:()=>H2,DebertaPreTrainedModel:()=>V2,DebertaV2ForMaskedLM:()=>t4,DebertaV2ForQuestionAnswering:()=>i4,DebertaV2ForSequenceClassification:()=>n4,DebertaV2ForTokenClassification:()=>r4,DebertaV2Model:()=>e4,DebertaV2PreTrainedModel:()=>$2,DecisionTransformerModel:()=>o4,DecisionTransformerPreTrainedModel:()=>a4,DeepseekV3ForCausalLM:()=>Y2,DeepseekV3Model:()=>J2,DeepseekV3PreTrainedModel:()=>q2,DeepseekV4ForCausalLM:()=>Q2,DeepseekV4Model:()=>Z2,DeepseekV4PreTrainedModel:()=>X2,DeiTForImageClassification:()=>l4,DeiTModel:()=>c4,DeiTPreTrainedModel:()=>s4,DepthAnythingForDepthEstimation:()=>d4,DepthAnythingPreTrainedModel:()=>u4,DepthProForDepthEstimation:()=>p4,DepthProPreTrainedModel:()=>f4,DetrForObjectDetection:()=>g4,DetrForSegmentation:()=>_4,DetrModel:()=>h4,DetrObjectDetectionOutput:()=>v4,DetrPreTrainedModel:()=>m4,DetrSegmentationOutput:()=>y4,Dinov2ForImageClassification:()=>S4,Dinov2Model:()=>x4,Dinov2PreTrainedModel:()=>b4,Dinov2WithRegistersForImageClassification:()=>T4,Dinov2WithRegistersModel:()=>w4,Dinov2WithRegistersPreTrainedModel:()=>C4,DistilBertForMaskedLM:()=>F4,DistilBertForQuestionAnswering:()=>P4,DistilBertForSequenceClassification:()=>M4,DistilBertForTokenClassification:()=>N4,DistilBertModel:()=>j4,DistilBertPreTrainedModel:()=>A4,DonutSwinModel:()=>L4,DonutSwinPreTrainedModel:()=>I4,EdgeTamModel:()=>N7,EfficientNetForImageClassification:()=>U4,EfficientNetModel:()=>H4,EfficientNetPreTrainedModel:()=>V4,ElectraForMaskedLM:()=>K4,ElectraForQuestionAnswering:()=>Y4,ElectraForSequenceClassification:()=>q4,ElectraForTokenClassification:()=>J4,ElectraModel:()=>G4,ElectraPreTrainedModel:()=>W4,EmbeddingGemma2Model:()=>Z4,EmbeddingGemma2PreTrainedModel:()=>X4,Ernie4_5ForCausalLM:()=>e3,Ernie4_5Model:()=>$4,Ernie4_5PretrainedModel:()=>Q4,EsmForMaskedLM:()=>r3,EsmForSequenceClassification:()=>i3,EsmForTokenClassification:()=>a3,EsmModel:()=>n3,EsmPreTrainedModel:()=>t3,EuroBertForMaskedLM:()=>c3,EuroBertForSequenceClassification:()=>l3,EuroBertForTokenClassification:()=>u3,EuroBertModel:()=>s3,EuroBertPreTrainedModel:()=>o3,ExaoneForCausalLM:()=>p3,ExaoneModel:()=>f3,ExaonePreTrainedModel:()=>d3,FalconForCausalLM:()=>g3,FalconH1ForCausalLM:()=>y3,FalconH1Model:()=>v3,FalconH1PreTrainedModel:()=>_3,FalconModel:()=>h3,FalconPreTrainedModel:()=>m3,FastViTForImageClassification:()=>S3,FastViTModel:()=>x3,FastViTPreTrainedModel:()=>b3,Florence2ForConditionalGeneration:()=>w3,Florence2PreTrainedModel:()=>C3,GLPNForDepthEstimation:()=>i6,GLPNModel:()=>r6,GLPNPreTrainedModel:()=>n6,GPT2LMHeadModel:()=>y6,GPT2Model:()=>v6,GPT2PreTrainedModel:()=>_6,GPTBigCodeForCausalLM:()=>s6,GPTBigCodeModel:()=>o6,GPTBigCodePreTrainedModel:()=>a6,GPTJForCausalLM:()=>S6,GPTJModel:()=>x6,GPTJPreTrainedModel:()=>b6,GPTNeoForCausalLM:()=>u6,GPTNeoModel:()=>l6,GPTNeoPreTrainedModel:()=>c6,GPTNeoXForCausalLM:()=>p6,GPTNeoXModel:()=>f6,GPTNeoXPreTrainedModel:()=>d6,Gemma2ForCausalLM:()=>A3,Gemma2Model:()=>k3,Gemma2PreTrainedModel:()=>O3,Gemma3ForCausalLM:()=>R3,Gemma3ForConditionalGeneration:()=>L3,Gemma3Model:()=>I3,Gemma3PreTrainedModel:()=>F3,Gemma3nForCausalLM:()=>V3,Gemma3nForConditionalGeneration:()=>B3,Gemma3nPreTrainedModel:()=>z3,Gemma4ForCausalLM:()=>U3,Gemma4ForConditionalGeneration:()=>H3,GemmaForCausalLM:()=>D3,GemmaModel:()=>E3,GemmaPreTrainedModel:()=>T3,GlmForCausalLM:()=>K3,GlmModel:()=>G3,GlmMoeDsaForCausalLM:()=>Y3,GlmMoeDsaModel:()=>J3,GlmMoeDsaPreTrainedModel:()=>q3,GlmOcrForConditionalGeneration:()=>t6,GlmPreTrainedModel:()=>W3,GptOssForCausalLM:()=>g6,GptOssModel:()=>h6,GptOssPreTrainedModel:()=>m6,GraniteForCausalLM:()=>T6,GraniteModel:()=>w6,GraniteMoeHybridForCausalLM:()=>O6,GraniteMoeHybridModel:()=>D6,GraniteMoeHybridPreTrainedModel:()=>E6,GranitePreTrainedModel:()=>C6,GraniteSpeechForConditionalGeneration:()=>j6,GroundingDinoForObjectDetection:()=>N6,GroundingDinoPreTrainedModel:()=>M6,GroupViTModel:()=>F6,GroupViTPreTrainedModel:()=>P6,HeliumForCausalLM:()=>R6,HeliumModel:()=>L6,HeliumPreTrainedModel:()=>I6,HieraForImageClassification:()=>V6,HieraModel:()=>B6,HieraPreTrainedModel:()=>z6,HrmTextForCausalLM:()=>W6,HrmTextModel:()=>U6,HrmTextPreTrainedModel:()=>H6,HubertForCTC:()=>Q6,HubertForSequenceClassification:()=>$6,HubertModel:()=>Z6,HubertPreTrainedModel:()=>X6,HunYuanDenseV1ForCausalLM:()=>nb,HunYuanDenseV1Model:()=>tb,HunYuanDenseV1PreTrainedModel:()=>eb,IJepaForImageClassification:()=>ob,IJepaModel:()=>ab,IJepaPreTrainedModel:()=>ib,Idefics3ForConditionalGeneration:()=>rb,ImageMattingOutput:()=>R0,JAISLMHeadModel:()=>lb,JAISModel:()=>cb,JAISPreTrainedModel:()=>sb,JinaCLIPModel:()=>db,JinaCLIPPreTrainedModel:()=>ub,JinaCLIPTextModel:()=>fb,JinaCLIPVisionModel:()=>pb,Lfm2ForCausalLM:()=>gb,Lfm2Model:()=>hb,Lfm2MoeForCausalLM:()=>bb,Lfm2MoeModel:()=>yb,Lfm2MoePreTrainedModel:()=>vb,Lfm2PreTrainedModel:()=>mb,Lfm2VlForConditionalGeneration:()=>xb,Lfm3ForCausalLM:()=>wb,Lfm3Model:()=>Cb,Lfm3PreTrainedModel:()=>Sb,Lfm3VlForConditionalGeneration:()=>Tb,LightOnOcrForConditionalGeneration:()=>_b,LiteWhisperForConditionalGeneration:()=>HS,Llama4ForCausalLM:()=>Ab,Llama4PreTrainedModel:()=>kb,LlamaForCausalLM:()=>Ob,LlamaModel:()=>Db,LlamaPreTrainedModel:()=>Eb,LlavaForConditionalGeneration:()=>M3,LlavaOnevisionForConditionalGeneration:()=>M3,LlavaPreTrainedModel:()=>j3,LlavaQwen2ForCausalLM:()=>P3,LongT5ForConditionalGeneration:()=>Nb,LongT5Model:()=>Mb,LongT5PreTrainedModel:()=>jb,M2M100ForConditionalGeneration:()=>Ib,M2M100Model:()=>Fb,M2M100PreTrainedModel:()=>Pb,MBartForCausalLM:()=>qb,MBartForConditionalGeneration:()=>Gb,MBartForSequenceClassification:()=>Kb,MBartModel:()=>Wb,MBartPreTrainedModel:()=>Ub,MPNetForMaskedLM:()=>lx,MPNetForQuestionAnswering:()=>fx,MPNetForSequenceClassification:()=>ux,MPNetForTokenClassification:()=>dx,MPNetModel:()=>cx,MPNetPreTrainedModel:()=>sx,MT5ForConditionalGeneration:()=>vx,MT5Model:()=>_x,MT5PreTrainedModel:()=>gx,MarianMTModel:()=>zb,MarianModel:()=>Rb,MarianPreTrainedModel:()=>Lb,MaskFormerForInstanceSegmentation:()=>Hb,MaskFormerModel:()=>Vb,MaskFormerPreTrainedModel:()=>Bb,MaskedLMOutput:()=>N0,Metric3DForDepthEstimation:()=>Yb,Metric3DPreTrainedModel:()=>Jb,Metric3Dv2ForDepthEstimation:()=>Zb,Metric3Dv2PreTrainedModel:()=>Xb,MgpstrForSceneTextRecognition:()=>e8,MgpstrModelOutput:()=>Qb,MgpstrPreTrainedModel:()=>$b,MimiDecoderModel:()=>o8,MimiDecoderOutput:()=>n8,MimiEncoderModel:()=>a8,MimiEncoderOutput:()=>t8,MimiModel:()=>i8,MimiPreTrainedModel:()=>r8,Ministral3ForCausalLM:()=>f8,Ministral3Model:()=>d8,Ministral3PreTrainedModel:()=>u8,MinistralForCausalLM:()=>l8,MinistralModel:()=>c8,MinistralPreTrainedModel:()=>s8,Mistral3ForConditionalGeneration:()=>g8,Mistral4ForCausalLM:()=>y8,Mistral4Model:()=>v8,Mistral4PreTrainedModel:()=>_8,MistralForCausalLM:()=>h8,MistralModel:()=>m8,MistralPreTrainedModel:()=>p8,MobileBertForMaskedLM:()=>S8,MobileBertForQuestionAnswering:()=>w8,MobileBertForSequenceClassification:()=>C8,MobileBertModel:()=>x8,MobileBertPreTrainedModel:()=>b8,MobileLLMForCausalLM:()=>D8,MobileLLMModel:()=>E8,MobileLLMPreTrainedModel:()=>T8,MobileNetV1ForImageClassification:()=>A8,MobileNetV1ForSemanticSegmentation:()=>j8,MobileNetV1Model:()=>k8,MobileNetV1PreTrainedModel:()=>O8,MobileNetV2ForImageClassification:()=>P8,MobileNetV2ForSemanticSegmentation:()=>F8,MobileNetV2Model:()=>N8,MobileNetV2PreTrainedModel:()=>M8,MobileNetV3ForImageClassification:()=>R8,MobileNetV3ForSemanticSegmentation:()=>z8,MobileNetV3Model:()=>L8,MobileNetV3PreTrainedModel:()=>I8,MobileNetV4ForImageClassification:()=>H8,MobileNetV4ForSemanticSegmentation:()=>U8,MobileNetV4Model:()=>V8,MobileNetV4PreTrainedModel:()=>B8,MobileViTForImageClassification:()=>K8,MobileViTModel:()=>G8,MobileViTPreTrainedModel:()=>W8,MobileViTV2ForImageClassification:()=>Y8,MobileViTV2Model:()=>J8,MobileViTV2PreTrainedModel:()=>q8,ModelOutput:()=>A0,ModernBertDecoderForCausalLM:()=>rx,ModernBertDecoderModel:()=>nx,ModernBertDecoderPreTrainedModel:()=>tx,ModernBertForMaskedLM:()=>Q8,ModernBertForSequenceClassification:()=>$8,ModernBertForTokenClassification:()=>ex,ModernBertModel:()=>Z8,ModernBertPreTrainedModel:()=>X8,Moondream1ForConditionalGeneration:()=>N3,MoonshineForConditionalGeneration:()=>ox,MoonshineModel:()=>ax,MoonshinePreTrainedModel:()=>ix,MptForCausalLM:()=>hx,MptModel:()=>mx,MptPreTrainedModel:()=>px,MultiModalityCausalLM:()=>bx,MultiModalityPreTrainedModel:()=>yx,MusicgenForCausalLM:()=>Cx,MusicgenForConditionalGeneration:()=>wx,MusicgenModel:()=>Sx,MusicgenPreTrainedModel:()=>xx,NanoChatForCausalLM:()=>Dx,NanoChatModel:()=>Ex,NanoChatPreTrainedModel:()=>Tx,NemotronHForCausalLM:()=>Ax,NemotronHModel:()=>kx,NemotronHPreTrainedModel:()=>Ox,NeoBertForMaskedLM:()=>Nx,NeoBertForQuestionAnswering:()=>Ix,NeoBertForSequenceClassification:()=>Px,NeoBertForTokenClassification:()=>Fx,NeoBertModel:()=>Mx,NeoBertPreTrainedModel:()=>jx,NomicBertModel:()=>Rx,NomicBertPreTrainedModel:()=>Lx,OPTForCausalLM:()=>a5,OPTModel:()=>i5,OPTPreTrainedModel:()=>r5,Olmo2ForCausalLM:()=>Wx,Olmo2Model:()=>Ux,Olmo2PreTrainedModel:()=>Hx,Olmo3ForCausalLM:()=>qx,Olmo3Model:()=>Kx,Olmo3PreTrainedModel:()=>Gx,OlmoForCausalLM:()=>Vx,OlmoHybridForCausalLM:()=>Xx,OlmoHybridModel:()=>Yx,OlmoHybridPreTrainedModel:()=>Jx,OlmoModel:()=>Bx,OlmoPreTrainedModel:()=>zx,OpenAIPrivacyFilterForTokenClassification:()=>$x,OpenAIPrivacyFilterModel:()=>Qx,OpenAIPrivacyFilterPreTrainedModel:()=>Zx,OpenELMForCausalLM:()=>n5,OpenELMModel:()=>t5,OpenELMPreTrainedModel:()=>e5,OwlViTForObjectDetection:()=>d5,OwlViTModel:()=>u5,OwlViTPreTrainedModel:()=>l5,Owlv2ForObjectDetection:()=>c5,Owlv2Model:()=>s5,Owlv2PreTrainedModel:()=>o5,PaliGemmaForConditionalGeneration:()=>f5,ParakeetForCTC:()=>m5,ParakeetPreTrainedModel:()=>p5,PatchTSMixerForPrediction:()=>_5,PatchTSMixerModel:()=>g5,PatchTSMixerPreTrainedModel:()=>h5,PatchTSTForPrediction:()=>b5,PatchTSTModel:()=>y5,PatchTSTPreTrainedModel:()=>v5,Phi3ForCausalLM:()=>E5,Phi3Model:()=>T5,Phi3PreTrainedModel:()=>w5,Phi3VForCausalLM:()=>O5,Phi3VPreTrainedModel:()=>D5,PhiForCausalLM:()=>C5,PhiModel:()=>S5,PhiPreTrainedModel:()=>x5,PreTrainedModel:()=>Z,PvtForImageClassification:()=>j5,PvtModel:()=>A5,PvtPreTrainedModel:()=>k5,PyAnnoteForAudioFrameClassification:()=>P5,PyAnnoteModel:()=>N5,PyAnnotePreTrainedModel:()=>M5,QuestionAnsweringModelOutput:()=>P0,Qwen2ForCausalLM:()=>L5,Qwen2Model:()=>I5,Qwen2MoeForCausalLM:()=>B5,Qwen2MoeModel:()=>z5,Qwen2MoePreTrainedModel:()=>R5,Qwen2PreTrainedModel:()=>F5,Qwen2VLForCausalLM:()=>Q3,Qwen2VLForConditionalGeneration:()=>Z3,Qwen2VLPreTrainedModel:()=>X3,Qwen2_5_VLForCausalLM:()=>e6,Qwen2_5_VLForConditionalGeneration:()=>$3,Qwen3ForCausalLM:()=>U5,Qwen3Model:()=>H5,Qwen3MoeForCausalLM:()=>K5,Qwen3MoeModel:()=>G5,Qwen3MoePreTrainedModel:()=>W5,Qwen3NextForCausalLM:()=>Y5,Qwen3NextModel:()=>J5,Qwen3NextPreTrainedModel:()=>q5,Qwen3PreTrainedModel:()=>V5,Qwen3VLForCausalLM:()=>Z5,Qwen3VLForConditionalGeneration:()=>X5,Qwen3VLMoeForCausalLM:()=>$5,Qwen3VLMoeForConditionalGeneration:()=>Q5,Qwen3_5ForCausalLM:()=>t7,Qwen3_5ForConditionalGeneration:()=>e7,Qwen3_5MoeForCausalLM:()=>r7,Qwen3_5MoeForConditionalGeneration:()=>n7,RFDetrForObjectDetection:()=>l7,RFDetrModel:()=>c7,RFDetrObjectDetectionOutput:()=>u7,RFDetrPreTrainedModel:()=>s7,RTDetrForObjectDetection:()=>A2,RTDetrModel:()=>k2,RTDetrObjectDetectionOutput:()=>j2,RTDetrPreTrainedModel:()=>O2,RTDetrV2ForObjectDetection:()=>T7,RTDetrV2Model:()=>w7,RTDetrV2ObjectDetectionOutput:()=>E7,RTDetrV2PreTrainedModel:()=>C7,ResNetForImageClassification:()=>o7,ResNetModel:()=>a7,ResNetPreTrainedModel:()=>i7,RoFormerForMaskedLM:()=>y7,RoFormerForQuestionAnswering:()=>S7,RoFormerForSequenceClassification:()=>b7,RoFormerForTokenClassification:()=>x7,RoFormerModel:()=>v7,RoFormerPreTrainedModel:()=>_7,RobertaForMaskedLM:()=>p7,RobertaForQuestionAnswering:()=>g7,RobertaForSequenceClassification:()=>m7,RobertaForTokenClassification:()=>h7,RobertaModel:()=>f7,RobertaPreTrainedModel:()=>d7,Sam2ImageSegmentationOutput:()=>A7,Sam2Model:()=>M7,Sam2PreTrainedModel:()=>j7,Sam3TrackerModel:()=>P7,SamImageSegmentationOutput:()=>D7,SamModel:()=>k7,SamPreTrainedModel:()=>O7,SapiensForDepthEstimation:()=>L7,SapiensForNormalEstimation:()=>R7,SapiensForSemanticSegmentation:()=>I7,SapiensPreTrainedModel:()=>F7,SegformerForImageClassification:()=>V7,SegformerForSemanticSegmentation:()=>H7,SegformerModel:()=>B7,SegformerPreTrainedModel:()=>z7,Seq2SeqLMOutput:()=>L0,SequenceClassifierOutput:()=>Y,SiglipModel:()=>W7,SiglipPreTrainedModel:()=>U7,SiglipTextModel:()=>G7,SiglipVisionModel:()=>K7,SmolLM3ForCausalLM:()=>Y7,SmolLM3Model:()=>J7,SmolLM3PreTrainedModel:()=>q7,SmolVLMForConditionalGeneration:()=>X7,SnacDecoderModel:()=>e9,SnacEncoderModel:()=>$7,SnacModel:()=>Q7,SnacPreTrainedModel:()=>Z7,SolarOpenForCausalLM:()=>r9,SolarOpenModel:()=>n9,SolarOpenPreTrainedModel:()=>t9,SpeechT5ForSpeechToText:()=>o9,SpeechT5ForTextToSpeech:()=>s9,SpeechT5HifiGan:()=>c9,SpeechT5Model:()=>a9,SpeechT5PreTrainedModel:()=>i9,SqueezeBertForMaskedLM:()=>d9,SqueezeBertForQuestionAnswering:()=>p9,SqueezeBertForSequenceClassification:()=>f9,SqueezeBertModel:()=>u9,SqueezeBertPreTrainedModel:()=>l9,StableLmForCausalLM:()=>g9,StableLmModel:()=>h9,StableLmPreTrainedModel:()=>m9,Starcoder2ForCausalLM:()=>y9,Starcoder2Model:()=>v9,Starcoder2PreTrainedModel:()=>_9,StyleTextToSpeech2Model:()=>x9,StyleTextToSpeech2PreTrainedModel:()=>b9,SupertonicForConditionalGeneration:()=>C9,SupertonicPreTrainedModel:()=>S9,Swin2SRForImageSuperResolution:()=>A9,Swin2SRModel:()=>k9,Swin2SRPreTrainedModel:()=>O9,SwinForImageClassification:()=>E9,SwinForSemanticSegmentation:()=>D9,SwinModel:()=>T9,SwinPreTrainedModel:()=>w9,T5ForConditionalGeneration:()=>N9,T5Model:()=>M9,T5PreTrainedModel:()=>j9,TableTransformerForObjectDetection:()=>I9,TableTransformerModel:()=>F9,TableTransformerObjectDetectionOutput:()=>L9,TableTransformerPreTrainedModel:()=>P9,TokenClassifierOutput:()=>M0,TrOCRForCausalLM:()=>z9,TrOCRPreTrainedModel:()=>R9,UltravoxModel:()=>A6,UltravoxPreTrainedModel:()=>k6,UniSpeechForCTC:()=>H9,UniSpeechForSequenceClassification:()=>U9,UniSpeechModel:()=>V9,UniSpeechPreTrainedModel:()=>B9,UniSpeechSatForAudioFrameClassification:()=>J9,UniSpeechSatForCTC:()=>K9,UniSpeechSatForSequenceClassification:()=>q9,UniSpeechSatModel:()=>G9,UniSpeechSatPreTrainedModel:()=>W9,VaultGemmaForCausalLM:()=>Z9,VaultGemmaModel:()=>X9,VaultGemmaPreTrainedModel:()=>Y9,ViTForImageClassification:()=>tS,ViTMAEModel:()=>rS,ViTMAEPreTrainedModel:()=>nS,ViTMSNForImageClassification:()=>oS,ViTMSNModel:()=>aS,ViTMSNPreTrainedModel:()=>iS,ViTModel:()=>eS,ViTPreTrainedModel:()=>$9,VisionEncoderDecoderModel:()=>Q9,VitMatteForImageMatting:()=>cS,VitMattePreTrainedModel:()=>sS,VitPoseForPoseEstimation:()=>uS,VitPosePreTrainedModel:()=>lS,VitsModel:()=>pS,VitsModelOutput:()=>dS,VitsPreTrainedModel:()=>fS,VoxtralForConditionalGeneration:()=>mS,VoxtralRealtimeForConditionalGeneration:()=>wS,VoxtralRealtimePreTrainedModel:()=>CS,Wav2Vec2BertForCTC:()=>DS,Wav2Vec2BertForSequenceClassification:()=>OS,Wav2Vec2BertModel:()=>ES,Wav2Vec2BertPreTrainedModel:()=>TS,Wav2Vec2ForAudioFrameClassification:()=>Y6,Wav2Vec2ForCTC:()=>q6,Wav2Vec2ForSequenceClassification:()=>J6,Wav2Vec2Model:()=>K6,Wav2Vec2PreTrainedModel:()=>G6,WavLMForAudioFrameClassification:()=>FS,WavLMForCTC:()=>MS,WavLMForSequenceClassification:()=>NS,WavLMForXVector:()=>PS,WavLMModel:()=>jS,WavLMPreTrainedModel:()=>AS,WeSpeakerResNetModel:()=>LS,WeSpeakerResNetPreTrainedModel:()=>IS,WhisperForConditionalGeneration:()=>VS,WhisperModel:()=>BS,WhisperPreTrainedModel:()=>zS,XLMForQuestionAnswering:()=>JS,XLMForSequenceClassification:()=>KS,XLMForTokenClassification:()=>qS,XLMModel:()=>WS,XLMPreTrainedModel:()=>US,XLMRobertaForMaskedLM:()=>ZS,XLMRobertaForQuestionAnswering:()=>eC,XLMRobertaForSequenceClassification:()=>QS,XLMRobertaForTokenClassification:()=>$S,XLMRobertaModel:()=>XS,XLMRobertaPreTrainedModel:()=>YS,XLMWithLMHeadModel:()=>GS,XVectorOutput:()=>kS,YolosForObjectDetection:()=>rC,YolosModel:()=>nC,YolosObjectDetectionOutput:()=>iC,YolosPreTrainedModel:()=>tC,YoutuForCausalLM:()=>sC,YoutuModel:()=>oC,YoutuPreTrainedModel:()=>aC,ZayaForCausalLM:()=>uC,ZayaModel:()=>lC,ZayaPreTrainedModel:()=>cC});var Kv=class extends Z{},qv=class extends Kv{},Jv=class extends Kv{async _call(e){return new Y(await super._call(e))}},Yv=class extends Kv{async _call(e){return new P0(await super._call(e))}},Xv=class extends Kv{async _call(e){return new N0(await super._call(e))}},Zv=class extends Z{},Qv=class extends Zv{},$v=class extends Zv{},ey=class extends Z{},ty=class extends ey{},ny=class extends ey{},ry=class extends Z{},iy=class extends ry{},ay=class extends ry{},oy=class extends Z{},sy=class extends oy{},cy=class extends oy{},ly=class extends Z{},uy=class extends ly{},dy=class extends ly{},fy=class extends ly{async _call(e){return new Y(await super._call(e))}},py=class extends Z{},my=class extends py{},hy=class extends py{async _call(e){return new Y(await super._call(e))}},gy=class extends Z{},_y=class extends gy{},vy=class extends gy{async _call(e){return new N0(await super._call(e))}},yy=class extends gy{async _call(e){return new Y(await super._call(e))}},by=class extends gy{async _call(e){return new M0(await super._call(e))}},xy=class extends gy{async _call(e){return new P0(await super._call(e))}},Sy=class extends Z{},Cy=class extends Sy{},wy=class extends Sy{},Ty=class extends Z{},Ey=class extends Ty{},Dy=class extends Ty{},Oy=class extends Z{},ky=class extends Oy{},Ay=class extends Oy{},jy=class extends Z{},My=class extends jy{},Ny=class extends jy{async _call(e){return new N0(await super._call(e))}},Py=class extends jy{async _call(e){return new Y(await super._call(e))}},Fy=class extends jy{async _call(e){return new M0(await super._call(e))}},Iy=class extends jy{async _call(e){return new P0(await super._call(e))}},Ly=4299n,Ry=6561n,zy=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},By=class extends zy{async encode_speech(e){return J(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,audio_features:u=null,audio_tokens:d=null,speaker_embeddings:f=null,speaker_features:p=null,...m}){let h;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof H)){let t=e.dims[0];if(r==null)r=cm([t],.5);else if(typeof r==`number`)r=cm([t],r);else if(Array.isArray(r))r=new H(`float32`,r,[t]);else throw Error(\"Unsupported type for `exaggeration` input\")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await J(this.sessions.embed_tokens,c),u&&d&&f&&p&&(h={audio_features:u,audio_tokens:d,speaker_embeddings:f,speaker_features:p}),h||n)h??=await this.encode_speech(n),a=U([h.audio_features,a],1),t=um([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=um([a.dims[0],n+e])}}return{...await Mv(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1),...h}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.position_ids=t.input_ids.dims[1]===1?new H(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==Ry)-1),[e.length,1]):new H(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=Ry?0:t++)}).flat(),t.input_ids.dims)),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),Rv(this,e,t,n)}async generate(e){let t=e.past_key_values,{sequences:n,audio_tokens:r,speaker_embeddings:i,speaker_features:a,past_key_values:o}=await super.generate({...e,return_dict_in_generate:!0});try{let t=n.slice(null,[e.input_ids.dims[1],-1]),o=U([r,t,cm([t.dims[0],3],Ly)],1),{waveform:s}=await J(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:a,speaker_embeddings:i});return s}finally{o!==t&&await o?.dispose()}}},Vy=class extends Z{},Hy=class extends Vy{},Uy=class extends Z{},Wy=class extends Uy{},Gy=class extends Z{},Ky=class extends Gy{},qy=class extends Gy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Jy=class extends Gy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},Yy=class extends Z{},Xy=class extends Yy{},Zy=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Qy=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},$y=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},e2=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},t2=class extends Z{},n2=class extends t2{},r2=class extends t2{},i2=class extends Z{},a2=class extends i2{},o2=class extends i2{},s2=class extends Z{},c2=class extends s2{},l2=class extends s2{},u2=class extends Z{},d2=class extends u2{},f2=class extends u2{},p2=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},m2=class extends p2{},h2=class extends p2{},g2=class extends Z{},_2=class extends g2{},v2=class extends g2{async _call(e){return new N0(await super._call(e))}},y2=class extends g2{async _call(e){return new Y(await super._call(e))}},b2=class extends g2{async _call(e){return new M0(await super._call(e))}},x2=class extends g2{async _call(e){return new P0(await super._call(e))}},S2=class extends Z{},C2=class extends S2{},w2=class extends S2{async _call(e){return new Y(await super._call(e))}},T2=class extends Z{},E2=class extends T2{},D2=class extends T2{async _call(e){return new Y(await super._call(e))}},O2=class extends Z{},k2=class extends O2{},A2=class extends O2{async _call(e){return new j2(await super._call(e))}},j2=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},M2=class extends Z{},N2=class extends M2{},P2=class extends M2{async _call(e){return new j2(await super._call(e))}},F2=class extends A0{constructor({audio_codes:e}){super(),this.audio_codes=e}},I2=class extends A0{constructor({audio_values:e}){super(),this.audio_values=e}},L2=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},R2=class extends L2{async encode(e){return new F2(await J(this.sessions.encoder_model,e))}async decode(e){return new I2(await J(this.sessions.decoder_model,e))}},z2=class extends L2{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},B2=class extends L2{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},V2=class extends Z{},H2=class extends V2{},U2=class extends V2{async _call(e){return new N0(await super._call(e))}},W2=class extends V2{async _call(e){return new Y(await super._call(e))}},G2=class extends V2{async _call(e){return new M0(await super._call(e))}},K2=class extends V2{async _call(e){return new P0(await super._call(e))}},q2=class extends Z{},J2=class extends q2{},Y2=class extends q2{},X2=class extends Z{},Z2=class extends X2{},Q2=class extends X2{},$2=class extends Z{},e4=class extends $2{},t4=class extends $2{async _call(e){return new N0(await super._call(e))}},n4=class extends $2{async _call(e){return new Y(await super._call(e))}},r4=class extends $2{async _call(e){return new M0(await super._call(e))}},i4=class extends $2{async _call(e){return new P0(await super._call(e))}},a4=class extends Z{},o4=class extends a4{},s4=class extends Z{},c4=class extends s4{},l4=class extends s4{async _call(e){return new Y(await super._call(e))}},u4=class extends Z{},d4=class extends u4{},f4=class extends Z{},p4=class extends f4{},m4=class extends Z{},h4=class extends m4{},g4=class extends m4{async _call(e){return new v4(await super._call(e))}},_4=class extends m4{async _call(e){return new y4(await super._call(e))}},v4=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},y4=class extends A0{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},b4=class extends Z{},x4=class extends b4{},S4=class extends b4{async _call(e){return new Y(await super._call(e))}},C4=class extends Z{},w4=class extends C4{},T4=class extends C4{async _call(e){return new Y(await super._call(e))}},E4=class extends Z{},D4=class extends E4{},O4=class extends Z{},k4=class extends O4{},A4=class extends Z{},j4=class extends A4{},M4=class extends A4{async _call(e){return new Y(await super._call(e))}},N4=class extends A4{async _call(e){return new M0(await super._call(e))}},P4=class extends A4{async _call(e){return new P0(await super._call(e))}},F4=class extends A4{async _call(e){return new N0(await super._call(e))}},I4=class extends Z{},L4=class extends I4{},R4=class extends Z{},z4=class extends R4{},B4=class extends R4{},V4=class extends Z{},H4=class extends V4{},U4=class extends V4{async _call(e){return new Y(await super._call(e))}},W4=class extends Z{},G4=class extends W4{},K4=class extends W4{async _call(e){return new N0(await super._call(e))}},q4=class extends W4{async _call(e){return new Y(await super._call(e))}},J4=class extends W4{async _call(e){return new M0(await super._call(e))}},Y4=class extends W4{async _call(e){return new P0(await super._call(e))}},X4=class extends Z{},Z4=class extends X4{async forward({input_ids:e,attention_mask:t,pixel_values:n=null,image_position_ids:r=null,pixel_values_videos:i=null,video_position_ids:a=null,input_features:o=null,input_features_mask:s=null}){let c={image_features:n&&await this.encode_image({pixel_values:n,pixel_position_ids:r}),video_features:i&&await this.encode_image({pixel_values:i,pixel_position_ids:a}),audio_features:o&&await this.encode_audio({input_features:o,input_features_mask:s})},{image_token_id:l,video_token_id:u,audio_token_id:d,text_config:f}=this.config,p={image:l,video:u,audio:d};for(let[t,n]of Object.entries(p)){let r=`${t}_features`;c[r]??=new H(`float32`,/* @__PURE__ */ new Float32Array,[0,f.hidden_size]);let i=0;for(let t of e.data)Number(t)===n&&++i;if(i!==c[r].dims[0])throw Error(`The number of ${t} tokens (${i}) and ${t} features (${c[r].dims[0]}) do not match.`)}return await J(this.sessions.model,{input_ids:e,attention_mask:t,...c})}},Q4=class extends Z{},$4=class extends Q4{},e3=class extends Q4{},t3=class extends Z{},n3=class extends t3{},r3=class extends t3{async _call(e){return new N0(await super._call(e))}},i3=class extends t3{async _call(e){return new Y(await super._call(e))}},a3=class extends t3{async _call(e){return new M0(await super._call(e))}},o3=class extends Z{},s3=class extends o3{},c3=class extends o3{async _call(e){return new N0(await super._call(e))}},l3=class extends o3{async _call(e){return new Y(await super._call(e))}},u3=class extends o3{async _call(e){return new M0(await super._call(e))}},d3=class extends Z{},f3=class extends d3{},p3=class extends d3{},m3=class extends Z{},h3=class extends m3{},g3=class extends m3{},_3=class extends Z{},v3=class extends _3{},y3=class extends _3{},b3=class extends Z{},x3=class extends b3{},S3=class extends b3{async _call(e){return new Y(await super._call(e))}},C3=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},w3=class extends C3{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:U([t,e],1),attention_mask:U([um(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error(\"Either `input_ids` or `pixel_values` should be provided.\");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c,num_logits_to_keep:l=null}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await Tv(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error(\"Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.\");c=await this.encode_text({input_ids:r})}let u={inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o,num_logits_to_keep:l};return await Mv(this,u,!0)}},T3=class extends Z{},E3=class extends T3{},D3=class extends T3{},O3=class extends Z{},k3=class extends O3{},A3=class extends O3{},j3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},M3=class extends j3{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Hv({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},N3=class extends M3{},P3=class extends M3{},F3=class extends Z{},I3=class extends F3{},L3=class extends M3{},R3=class extends L3{},z3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},B3=class extends z3{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,num_logits_to_keep:d=null,...f}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await J(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...f});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await J(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Mv(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u,num_logits_to_keep:d},!0)}_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return Hv({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Uv({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},V3=class extends B3{},H3=class extends B3{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return J(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},U3=class extends H3{},W3=class extends Z{},G3=class extends W3{},K3=class extends W3{},q3=class extends Z{},J3=class extends q3{},Y3=class extends q3{},X3=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},Z3=class extends X3{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=Iv(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>$f(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new H(`int64`,r,[3,...n]),new H(`int64`,i,[i.length,1])]}{let[t,n]=e.dims;return[new H(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),fm([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e<t.length;++e)if(t[e]==1){for(let t=0;t<3;++t)n[t][r][e]=a[t*i/3+s];++s}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a,video_token_id:o,vision_start_token_id:s}=this.config,c=e,l=c.reduce((e,t,n)=>(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;e<l.length;++e){let e=c.findIndex((e,t)=>t>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l<u?([g,_,v]=t[i.image_index],++i.image_index,--m,d=l):([g,_,v]=n[i.video_index],++i.video_index,--h,d=u);let[y,b,x]=[Number(g),Math.floor(Number(_)/r),Math.floor(Number(v)/r)],S=d-p,C=f.length>0?$f(f.at(-1))[0]+1:0;f.push(Array.from({length:3*S},(e,t)=>C+t%S));let ee=S+C,w=y*b*x,te=Array.from({length:w},(e,t)=>ee+Math.floor(t/(b*x))),ne=Array.from({length:w},(e,t)=>ee+Math.floor(t/x)%b),re=Array.from({length:w},(e,t)=>ee+t%x);f.push([te,ne,re].flat()),p=d+w}if(p<c.length){let e=f.length>0?$f(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=dm(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;e<i.length;++e){let t=i[e].filter((t,n)=>o[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push($f(r)[0]+1-i[e].length)}return[new H(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new H(`int64`,d,[d.length,1])]}return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await J(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return Hv({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(jv(this,t,1n),!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(e<t.input_ids.dims[1]){let[n,r]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=r,t.position_ids=n.slice(null,null,[e,null]),t.input_ids=t.input_ids.slice(null,[e,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));let n=BigInt(e),r=t.rope_deltas.map(e=>n+e);t.position_ids=nm([r,r,r],0)}}return t}},Q3=class extends Z3{},$3=class extends Z3{image_grid_thw_name=`image_grid_thw`},e6=class extends Q3{image_grid_thw_name=`image_grid_thw`},t6=class extends $3{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=t<e.length?+(e[t]==a):-1;n!==c&&(o.push([c,s,t]),s=t,c=n)}let l=0,u=[];for(let[e,n,a]of o)if(e===0){let e=a-n;u.push(Array.from({length:3*e},(t,n)=>l+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},n6=class extends Z{},r6=class extends n6{},i6=class extends n6{},a6=class extends Z{},o6=class extends a6{},s6=class extends a6{},c6=class extends Z{},l6=class extends c6{},u6=class extends c6{},d6=class extends Z{},f6=class extends d6{},p6=class extends d6{},m6=class extends Z{},h6=class extends m6{},g6=class extends m6{},_6=class extends Z{},v6=class extends _6{},y6=class extends _6{},b6=class extends Z{},x6=class extends b6{},S6=class extends b6{},C6=class extends Z{},w6=class extends C6{},T6=class extends C6{},E6=class extends Z{},D6=class extends E6{},O6=class extends E6{},k6=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},A6=class extends k6{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Uv({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},j6=class extends A6{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},M6=class extends Z{},N6=class extends M6{},P6=class extends Z{},F6=class extends P6{},I6=class extends Z{},L6=class extends I6{},R6=class extends I6{},z6=class extends Z{},B6=class extends z6{},V6=class extends z6{async _call(e){return new Y(await super._call(e))}},H6=class extends Z{},U6=class extends H6{},W6=class extends H6{forward_params=[`input_ids`,`attention_mask`,`token_type_ids`,`past_key_values`];prepare_inputs_for_generation(e,t,n){let r=Rv(this,e,t,n);return r.token_type_ids=(r.past_key_values?pm:dm)(r.input_ids),r}},G6=class extends Z{},K6=class extends G6{},q6=class extends G6{async _call(e){return new F0(await super._call(e))}},J6=class extends G6{async _call(e){return new Y(await super._call(e))}},Y6=class extends G6{async _call(e){return new M0(await super._call(e))}},X6=class extends Z{},Z6=class extends G6{},Q6=class extends G6{async _call(e){return new F0(await super._call(e))}},$6=class extends G6{async _call(e){return new Y(await super._call(e))}},eb=class extends Z{},tb=class extends eb{},nb=class extends eb{},rb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},ib=class extends Z{},ab=class extends ib{},ob=class extends ib{async _call(e){return new Y(await super._call(e))}},sb=class extends Z{},cb=class extends sb{},lb=class extends sb{},ub=class extends Z{},db=class extends ub{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error(\"Either `input_ids` or `pixel_values` should be provided.\");if(t&&(e.input_ids=um([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=cm([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},fb=class extends ub{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},pb=class extends ub{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},mb=class extends Z{},hb=class extends mb{},gb=class extends mb{},_b=class extends M3{},vb=class extends Z{},yb=class extends vb{},bb=class extends vb{},xb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},Sb=class extends Z{},Cb=class extends Sb{},wb=class extends Sb{},Tb=class extends M3{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`image_grid_thw`,`position_ids`,`past_key_values`]},Eb=class extends Z{},Db=class extends Eb{},Ob=class extends Eb{},kb=class extends Z{},Ab=class extends kb{},jb=class extends Z{},Mb=class extends jb{},Nb=class extends jb{},Pb=class extends Z{},Fb=class extends Pb{},Ib=class extends Pb{},Lb=class extends Z{},Rb=class extends Lb{},zb=class extends Lb{},Bb=class extends Z{},Vb=class extends Bb{},Hb=class extends Bb{},Ub=class extends Z{},Wb=class extends Ub{},Gb=class extends Ub{},Kb=class extends Ub{async _call(e){return new Y(await super._call(e))}},qb=class extends Ub{},Jb=class extends Z{},Yb=class extends Jb{},Xb=class extends Z{},Zb=class extends Xb{},Qb=class extends A0{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},$b=class extends Z{},e8=class extends $b{async _call(e){return new Qb(await super._call(e))}},t8=class extends A0{constructor({audio_codes:e}){super(),this.audio_codes=e}},n8=class extends A0{constructor({audio_values:e}){super(),this.audio_values=e}},r8=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},i8=class extends r8{async encode(e){return new t8(await J(this.sessions.encoder_model,e))}async decode(e){return new n8(await J(this.sessions.decoder_model,e))}},a8=class extends r8{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},o8=class extends r8{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},s8=class extends Z{},c8=class extends s8{},l8=class extends s8{},u8=class extends Z{},d8=class extends u8{},f8=class extends u8{},p8=class extends Z{},m8=class extends p8{},h8=class extends p8{},g8=class extends M3{},_8=class extends Z{},v8=class extends _8{},y8=class extends _8{},b8=class extends Z{},x8=class extends b8{},S8=class extends b8{async _call(e){return new N0(await super._call(e))}},C8=class extends b8{async _call(e){return new Y(await super._call(e))}},w8=class extends b8{async _call(e){return new P0(await super._call(e))}},T8=class extends Z{},E8=class extends T8{},D8=class extends T8{},O8=class extends Z{},k8=class extends O8{},A8=class extends O8{async _call(e){return new Y(await super._call(e))}},j8=class extends O8{},M8=class extends Z{},N8=class extends M8{},P8=class extends M8{async _call(e){return new Y(await super._call(e))}},F8=class extends M8{},I8=class extends Z{},L8=class extends I8{},R8=class extends I8{async _call(e){return new Y(await super._call(e))}},z8=class extends I8{},B8=class extends Z{},V8=class extends B8{},H8=class extends B8{async _call(e){return new Y(await super._call(e))}},U8=class extends B8{},W8=class extends Z{},G8=class extends W8{},K8=class extends W8{async _call(e){return new Y(await super._call(e))}},q8=class extends Z{},J8=class extends q8{},Y8=class extends q8{async _call(e){return new Y(await super._call(e))}},X8=class extends Z{},Z8=class extends X8{},Q8=class extends X8{async _call(e){return new N0(await super._call(e))}},$8=class extends X8{async _call(e){return new Y(await super._call(e))}},ex=class extends X8{async _call(e){return new M0(await super._call(e))}},tx=class extends Z{},nx=class extends tx{},rx=class extends tx{},ix=class extends Z{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},ax=class extends ix{},ox=class extends ix{},sx=class extends Z{},cx=class extends sx{},lx=class extends sx{async _call(e){return new N0(await super._call(e))}},ux=class extends sx{async _call(e){return new Y(await super._call(e))}},dx=class extends sx{async _call(e){return new M0(await super._call(e))}},fx=class extends sx{async _call(e){return new P0(await super._call(e))}},px=class extends Z{},mx=class extends px{},hx=class extends px{},gx=class extends Z{},_x=class extends gx{},vx=class extends gx{},yx=class extends Z{},bx=class extends yx{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await J(t,Xs(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await J(t,Xs({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await Mv(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find \"${a}\" generation head`);let o=await J(a,Xs(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return jv(this,t,1n),n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=U([t.input_ids,t.input_ids],0):(t.input_ids=U([t.input_ids,lm(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=U([t.attention_mask,lm(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=cm([0,0,3,384,384],1)),r&&(t.images_seq_mask=new H(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new H(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),{decoded_image:r}=await J(this.sessions.image_decode,{generated_tokens:n}),i=r.add_(1).mul_(127.5).clamp_(0,255).to(`uint8`),a=[];for(let e of i){let t=Mg.fromTensor(e);a.push(t)}return a}},xx=class extends Z{},Sx=class extends xx{},Cx=class extends xx{},wx=class extends Z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t<e.size;++t){if(e.data[t]==this.config.decoder.pad_token_id)continue;let o=t%n-Math.floor(t/n)%r;o>0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new H(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e<i.length;++e)for(let t=0;t<i[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),zv(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await J(this.sessions.encodec_decode,{audio_codes:n});return r}},Tx=class extends Z{},Ex=class extends Tx{},Dx=class extends Tx{},Ox=class extends Z{},kx=class extends Ox{},Ax=class extends Ox{},jx=class extends Z{},Mx=class extends jx{},Nx=class extends jx{async _call(e){return new N0(await super._call(e))}},Px=class extends jx{async _call(e){return new Y(await super._call(e))}},Fx=class extends jx{async _call(e){return new M0(await super._call(e))}},Ix=class extends jx{async _call(e){return new P0(await super._call(e))}},Lx=class extends Z{},Rx=class extends Lx{},zx=class extends Z{},Bx=class extends zx{},Vx=class extends zx{},Hx=class extends Z{},Ux=class extends Hx{},Wx=class extends Hx{},Gx=class extends Z{},Kx=class extends Gx{},qx=class extends Gx{},Jx=class extends Z{},Yx=class extends Jx{},Xx=class extends Jx{},Zx=class extends Z{},Qx=class extends Zx{},$x=class extends Zx{async _call(e){return new Y(await super._call(e))}},e5=class extends Z{},t5=class extends e5{},n5=class extends e5{},r5=class extends Z{},i5=class extends r5{},a5=class extends r5{},o5=class extends Z{},s5=class extends o5{},c5=class extends o5{},l5=class extends Z{},u5=class extends l5{},d5=class extends l5{},f5=class extends M3{},p5=class extends Z{},m5=class extends p5{async _call(e){return new F0(await super._call(e))}},h5=class extends Z{},g5=class extends h5{},_5=class extends h5{},v5=class extends Z{},y5=class extends v5{},b5=class extends v5{},x5=class extends Z{},S5=class extends x5{},C5=class extends x5{},w5=class extends Z{},T5=class extends w5{},E5=class extends w5{},D5=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},O5=class extends D5{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,num_logits_to_keep:l=null,...u}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error(\"`image_sizes` must be provided when `pixel_values` is provided.\");({image_features:t}=await J(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else t=new H(`float32`,[],[0,this.config.normalized_config.hidden_size]);({inputs_embeds:a}=await J(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await Mv(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c,num_logits_to_keep:l},!1)}},k5=class extends Z{},A5=class extends k5{},j5=class extends k5{async _call(e){return new Y(await super._call(e))}},M5=class extends Z{},N5=class extends M5{},P5=class extends M5{async _call(e){return new M0(await super._call(e))}},F5=class extends Z{},I5=class extends F5{},L5=class extends F5{},R5=class extends Z{},z5=class extends R5{},B5=class extends R5{},V5=class extends Z{},H5=class extends V5{},U5=class extends V5{},W5=class extends Z{},G5=class extends W5{},K5=class extends W5{},q5=class extends Z{},J5=class extends q5{},Y5=class extends q5{},X5=class extends $3{},Z5=class extends e6{},Q5=class extends X5{},$5=class extends Z5{},e7=class extends X5{},t7=class extends e7{},n7=class extends e7{},r7=class extends t7{},i7=class extends Z{},a7=class extends i7{},o7=class extends i7{async _call(e){return new Y(await super._call(e))}},s7=class extends Z{},c7=class extends s7{},l7=class extends s7{async _call(e){return new u7(await super._call(e))}},u7=class extends j2{},d7=class extends Z{},f7=class extends d7{},p7=class extends d7{async _call(e){return new N0(await super._call(e))}},m7=class extends d7{async _call(e){return new Y(await super._call(e))}},h7=class extends d7{async _call(e){return new M0(await super._call(e))}},g7=class extends d7{async _call(e){return new P0(await super._call(e))}},_7=class extends Z{},v7=class extends _7{},y7=class extends _7{async _call(e){return new N0(await super._call(e))}},b7=class extends _7{async _call(e){return new Y(await super._call(e))}},x7=class extends _7{async _call(e){return new M0(await super._call(e))}},S7=class extends _7{async _call(e){return new P0(await super._call(e))}},C7=class extends Z{},w7=class extends C7{},T7=class extends C7{async _call(e){return new E7(await super._call(e))}},E7=class extends j2{},D7=class extends A0{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},O7=class extends Z{},k7=class extends O7{async get_image_embeddings({pixel_values:e}){return await Tv(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=um(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 J(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new D7(await super._call(e))}},A7=class extends A0{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},j7=class extends Z{},M7=class extends j7{async get_image_embeddings({pixel_values:e}){return await Tv(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error(\"When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.\");let t=e.input_points.dims;e.input_labels??=um(t.slice(0,-1)),e.input_boxes??=cm([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=cm([t[0],t[1],0],-1n),e.input_points=cm([t[0],1,0,2],0)}else throw Error(\"At least one of `input_points` or `input_boxes` must be provided.\");let n=this.sessions.prompt_encoder_mask_decoder;return await J(n,Xs(e,n.inputNames))}async _call(e){return new A7(await super._call(e))}},N7=class extends M7{},P7=class extends M7{},F7=class extends Z{},I7=class extends F7{},L7=class extends F7{},R7=class extends F7{},z7=class extends Z{},B7=class extends z7{},V7=class extends z7{},H7=class extends z7{},U7=class extends Z{},W7=class extends U7{},G7=class extends U7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},K7=class extends Yy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},q7=class extends Z{},J7=class extends q7{},Y7=class extends q7{},X7=class extends rb{},Z7=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},Q7=class extends Z7{async encode(e){return await J(this.sessions.encoder_model,e)}async decode(e){return await J(this.sessions.decoder_model,e)}},$7=class extends Z7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},e9=class extends Z7{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},t9=class extends Z{},n9=class extends t9{},r9=class extends t9{},i9=class extends Z{},a9=class extends i9{},o9=class extends i9{},s9=class extends i9{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:s,encoder_attention_mask:c}=await Tv(this,o),l=s.dims[1]/this.config.reduction_factor,u=Math.floor(l*i),d=Math.floor(l*r),f=this.config.num_mel_bins,p=[],m=null,h=null,g=0;for(;;){++g;let e=vv(!!h),r;r=h?h.output_sequence_out:new H(`float32`,new Float32Array(f),[1,1,f]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:s};Av(this,i,m),h=await J(this.sessions.decoder_model_merged,i),m=Dv(h,m);let{prob:a,spectrum:o}=h;if(p.push(o),g>=d&&(Array.from(a.data).filter(e=>e>=n).length>0||g>=u))break}let _=U(p),{waveform:v}=await J(a.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}},c9=class extends Z{main_input_name=`spectrogram`},l9=class extends Z{},u9=class extends l9{},d9=class extends l9{async _call(e){return new N0(await super._call(e))}},f9=class extends l9{async _call(e){return new Y(await super._call(e))}},p9=class extends l9{async _call(e){return new P0(await super._call(e))}},m9=class extends Z{},h9=class extends m9{},g9=class extends m9{},_9=class extends Z{},v9=class extends _9{},y9=class extends _9{},b9=class extends Z{},x9=class extends b9{},S9=class extends Z{},C9=class extends S9{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await J(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;e<g;++e)_.fill(1n,e*h,e*h+m[e]);let v=new H(`int64`,_,[g,h]),y=c*o,b=y*h,x=mm([g,y,h]),S=x.data;for(let e=0;e<g;++e)if(m[e]!==h)for(let t=0;t<y;++t)S.fill(0,e*b+t*h+m[e],e*b+(t+1)*h);let C=cm([g],r);for(let e=0;e<r;++e){let r=cm([g],e);({denoised_latents:x}=await J(this.sessions.latent_denoiser,{style:n,noisy_latents:x,latent_mask:v,encoder_outputs:l,attention_mask:t,timestep:r,num_inference_steps:C}))}let{waveform:ee}=await J(this.sessions.voice_decoder,{latents:x});return{waveform:ee,durations:d}}},w9=class extends Z{},T9=class extends w9{},E9=class extends w9{async _call(e){return new Y(await super._call(e))}},D9=class extends w9{},O9=class extends Z{},k9=class extends O9{},A9=class extends O9{},j9=class extends Z{forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},M9=class extends j9{},N9=class extends j9{},P9=class extends Z{},F9=class extends P9{},I9=class extends P9{async _call(e){return new L9(await super._call(e))}},L9=class extends v4{},R9=class extends Z{},z9=class extends R9{},B9=class extends Z{},V9=class extends B9{},H9=class extends B9{async _call(e){return new F0(await super._call(e))}},U9=class extends B9{async _call(e){return new Y(await super._call(e))}},W9=class extends Z{},G9=class extends W9{},K9=class extends W9{async _call(e){return new F0(await super._call(e))}},q9=class extends W9{async _call(e){return new Y(await super._call(e))}},J9=class extends W9{async _call(e){return new M0(await super._call(e))}},Y9=class extends Z{},X9=class extends Y9{},Z9=class extends Y9{},Q9=class extends Z{main_input_name=`pixel_values`;forward_params=[`pixel_values`,`decoder_input_ids`,`encoder_hidden_states`,`past_key_values`]},$9=class extends Z{},eS=class extends $9{},tS=class extends $9{async _call(e){return new Y(await super._call(e))}},nS=class extends Z{},rS=class extends nS{},iS=class extends Z{},aS=class extends iS{},oS=class extends iS{async _call(e){return new Y(await super._call(e))}},sS=class extends Z{},cS=class extends sS{async _call(e){return new R0(await super._call(e))}},lS=class extends Z{},uS=class extends lS{},dS=class extends A0{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},fS=class extends Z{},pS=class extends fS{async _call(e){return new dS(await super._call(e))}},mS=class extends A6{},hS=2,gS=1,_S=/* @__PURE__ */ new WeakMap;function vS(e,t){let{text_config:n,audio_config:r}=e.config,i=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=r,s=a+o,c=new lv,l=v0(r),u={batch_size:1},d=`float32`;for(let e of i.inputMetadata){if(e.name===`past_padding_cache`){d=e.type;continue}if(!l.has(e.name))continue;let t=kv(e.shape,u),n=t.reduce((e,t)=>e*t,1),r=Up[e.type];c[e.name]=new H(e.type,new r(n),t)}let f=Up[d],p=new H(d,new f(s*hS),[1,s,hS]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:m,text_hidden_size:n.hidden_size}}async function yS(e,t){let n=t.dims[2],r=Math.floor((gS+n-3)/2)+1,i=new H(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=um([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await J(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,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=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function bS(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let t=await e.chunks_iter.next();if(t.done){e.stream_exhausted=!0;break}let n=await yS(e,t.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function xS(e,t,n){if(e.audio_embed_queue.length===0)return;let r=t.data,i=0,a=n;for(;a>0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n<o*e.text_hidden_size;++n)r[i*e.text_hidden_size+n]+=t.data[s+n];i+=o,a-=o,e.audio_queue_offset+=o,e.audio_queue_offset>=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var SS=class extends tv{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)}},CS=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},wS=class extends CS{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=_S.get(this);i&&await bS(i,i.audio_consumed+r);let{inputs_embeds:a}=await J(this.sessions.embed_tokens,{input_ids:e});i&&xS(i,a,r);let o={inputs_embeds:a,...n};Av(this,o,t);let s=this.sessions.decoder_model_merged;return await J(s,Xs(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=vS(this,e);_S.set(this,r);let i=new nv;i.push(new SS(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),_S.delete(this)}}},TS=class extends Z{},ES=class extends TS{},DS=class extends TS{async _call(e){return new F0(await super._call(e))}},OS=class extends TS{async _call(e){return new Y(await super._call(e))}},kS=class extends A0{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},AS=class extends Z{},jS=class extends AS{},MS=class extends AS{async _call(e){return new F0(await super._call(e))}},NS=class extends AS{async _call(e){return new Y(await super._call(e))}},PS=class extends AS{async _call(e){return new kS(await super._call(e))}},FS=class extends AS{async _call(e){return new M0(await super._call(e))}},IS=class extends Z{},LS=class extends IS{},RS=class extends ev{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},zS=class extends Z{requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},BS=class extends zS{},VS=class extends zS{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,RS)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(N.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${vh(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error(\"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\");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&&(N.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\"),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof H?vm(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new V0,n.push(new K0(t,a))),t.begin_suppress_tokens&&(n??=new V0,n.push(new G0(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error(\"Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\");t.task===`translate`&&N.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;d<l;){let e=Math.min(d+u,l),m=c.slice(null,null,[d,e]),h,g=m.dims[2];if(g<u){let e=c.dims[1],t=new Float32Array(e*u),n=m.data;for(let r=0;r<e;++r)t.set(n.subarray(r*g,(r+1)*g),r*u);h=new H(`float32`,t,[1,e,u])}else h=m;if(n)for(let e of n)`begin_index`in e&&(e.begin_index=r.length);let _=await super.generate({inputs:h,generation_config:t,logits_processor:n,decoder_input_ids:r,...i}),v=(s?_.sequences:_)[0].tolist().map(Number).slice(r.length),y;if(s){_.token_timestamps=this._extract_token_timestamps(_,t.alignment_heads,Math.floor((e-d)/2),.02,r.length);let n=d/2*.02;y=_.token_timestamps[0].tolist().slice(r.length).map(e=>e+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],S=[];for(let e=0;e<v.length-1;++e)b[e]&&b[e+1]&&S.push(e+1);let C,ee=v.length;if(S.length>0){if(x)C=e-d;else{let e=S.at(-1);C=(v[e-1]-a)*2,ee=e}}else C=e-d;let w=Math.floor(d/2),te=a+1500;for(let e=0;e<ee;++e)v[e]>=a&&(v[e]=Math.min(v[e]+w,te));f.push(...v.slice(0,ee)),y&&p.push(...y.slice(0,ee)),d+=C}f.push(o);let m=[...r,...f];if(s){let e=new H(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new H(`float32`,new Float32Array(t),[1,t.length])}}return new H(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error(\"Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.\");n??N.warn(\"`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\");let a=this.config.median_filter_width;a===void 0&&(N.warn(\"Model config has no `median_filter_width`, using default value of 7.\"),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>U(o.map(e=>e[t]),2)),c=nm(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).permute(1,0,2,3),[l,u]=im(c,-2,0,!0),d=c.clone();for(let e=0;e<d.dims[0];++e){let t=d[e];for(let n=0;n<t.dims[0];++n){let r=t[n],i=l[e][n][0].data,o=u[e][n][0].data;for(let e=0;e<r.dims[0];++e){let t=r[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-o[e])/i[e];t.set(ip(t,a))}}}let f=[am(i>0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new H(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;e<p[0];++e){let[t,n]=sp(f[e].neg().squeeze_(0).tolist()),a=qs([1],Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e<a.length;++e)a[e]&&o.push(n[e]*r);let s=Array(i).fill(0);s.push(...o),o.length>0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},HS=class extends VS{},US=class extends Z{},WS=class extends US{},GS=class extends US{async _call(e){return new N0(await super._call(e))}},KS=class extends US{async _call(e){return new Y(await super._call(e))}},qS=class extends US{async _call(e){return new M0(await super._call(e))}},JS=class extends US{async _call(e){return new P0(await super._call(e))}},YS=class extends Z{},XS=class extends YS{},ZS=class extends YS{async _call(e){return new N0(await super._call(e))}},QS=class extends YS{async _call(e){return new Y(await super._call(e))}},$S=class extends YS{async _call(e){return new M0(await super._call(e))}},eC=class extends YS{async _call(e){return new P0(await super._call(e))}},tC=class extends Z{},nC=class extends tC{},rC=class extends tC{async _call(e){return new iC(await super._call(e))}},iC=class extends A0{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},aC=class extends Z{},oC=class extends aC{},sC=class extends aC{},cC=class extends Z{},lC=class extends cC{},uC=class extends cC{},dC=/* @__PURE__ */ new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`],[`openai_privacy_filter`,`OpenAIPrivacyFilterModel`],[`embedding_gemma2`,`EmbeddingGemma2Model`]]),fC=/* @__PURE__ */ new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),pC=/* @__PURE__ */ new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),mC=/* @__PURE__ */ new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`lfm3`,`Lfm3Model`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`deepseek_v4`,`DeepseekV4Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`],[`zaya`,`ZayaModel`],[`hrm_text`,`HrmTextModel`]]),hC=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),gC=/* @__PURE__ */ new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),_C=/* @__PURE__ */ new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),vC=/* @__PURE__ */ 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`]]),yC=/* @__PURE__ */ new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`],[`openai_privacy_filter`,`OpenAIPrivacyFilterForTokenClassification`]]),bC=/* @__PURE__ */ new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),xC=/* @__PURE__ */ new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`lfm3`,`Lfm3ForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`deepseek_v4`,`DeepseekV4ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`zaya`,`ZayaForCausalLM`],[`hrm_text`,`HrmTextForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),SC=/* @__PURE__ */ new Map([[`multi_modality`,`MultiModalityCausalLM`]]),CC=/* @__PURE__ */ 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`]]),wC=/* @__PURE__ */ 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`]]),TC=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),EC=/* @__PURE__ */ new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`lfm3_vl`,`Lfm3VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),DC=/* @__PURE__ */ new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),OC=/* @__PURE__ */ new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),kC=/* @__PURE__ */ 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`]]),AC=/* @__PURE__ */ new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),jC=/* @__PURE__ */ new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),MC=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),NC=/* @__PURE__ */ new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),PC=/* @__PURE__ */ new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),FC=/* @__PURE__ */ new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),IC=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),LC=/* @__PURE__ */ new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),RC=/* @__PURE__ */ new Map([[`wavlm`,`WavLMForXVector`]]),zC=/* @__PURE__ */ new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),BC=/* @__PURE__ */ new Map([[`vitmatte`,`VitMatteForImageMatting`]]),VC=/* @__PURE__ */ new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),HC=/* @__PURE__ */ new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),UC=/* @__PURE__ */ new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),WC=/* @__PURE__ */ new Map([[`sapiens`,`SapiensForNormalEstimation`]]),GC=/* @__PURE__ */ new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),KC=/* @__PURE__ */ new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),qC=[[dC,X.EncoderOnly],[fC,X.EncoderDecoder],[mC,X.DecoderOnlyWithoutHead],[pC,X.AutoEncoder],[vC,X.EncoderOnly],[yC,X.EncoderOnly],[bC,X.Seq2Seq],[hC,X.Seq2Seq],[xC,X.DecoderOnly],[SC,X.MultiModality],[CC,X.EncoderOnly],[wC,X.EncoderOnly],[TC,X.Vision2Seq],[EC,X.ImageTextToText],[DC,X.AudioTextToText],[kC,X.EncoderOnly],[MC,X.EncoderOnly],[PC,X.EncoderOnly],[NC,X.EncoderOnly],[BC,X.EncoderOnly],[VC,X.EncoderOnly],[HC,X.EncoderOnly],[UC,X.EncoderOnly],[WC,X.EncoderOnly],[GC,X.EncoderOnly],[AC,X.EncoderOnly],[jC,X.EncoderOnly],[FC,X.MaskGeneration],[IC,X.EncoderOnly],[LC,X.EncoderOnly],[gC,X.Seq2Seq],[_C,X.EncoderOnly],[RC,X.EncoderOnly],[zC,X.EncoderOnly],[KC,X.EncoderOnly]];for(let[e,t]of qC)for(let n of e.values()){xv.set(n,t);let e=Gv[n];Cv.set(e,n),Sv.set(n,e)}var JC=[[`MusicgenForConditionalGeneration`,wx,X.Musicgen],[`Phi3VForCausalLM`,O5,X.Phi3V],[`CLIPTextModelWithProjection`,Qy,X.EncoderOnly],[`SiglipTextModel`,G7,X.EncoderOnly],[`JinaCLIPTextModel`,fb,X.EncoderOnly],[`ClapTextModelWithProjection`,qy,X.EncoderOnly],[`ClapAudioModelWithProjection`,Jy,X.EncoderOnly],[`DacEncoderModel`,z2,X.EncoderOnly],[`DacDecoderModel`,B2,X.EncoderOnly],[`MimiEncoderModel`,a8,X.EncoderOnly],[`MimiDecoderModel`,o8,X.EncoderOnly],[`SnacEncoderModel`,$7,X.EncoderOnly],[`SnacDecoderModel`,e9,X.EncoderOnly],[`Gemma3nForConditionalGeneration`,B3,X.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,H3,X.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,C9,X.Supertonic],[`ChatterboxModel`,By,X.Chatterbox],[`EmbeddingGemma2Model`,Z4,X.MultimodalEncoder],[`VoxtralRealtimeForConditionalGeneration`,wS,X.VoxtralRealtime]];for(let[e,t,n]of JC)xv.set(e,n),Cv.set(t,e),Sv.set(e,t);var YC=/* @__PURE__ */ new Map([[`modnet`,MC],[`birefnet`,MC],[`isnet`,MC],[`ben`,MC]]);for(let[e,t]of YC.entries())t.set(e,`PreTrainedModel`),xv.set(e,X.EncoderOnly),Sv.set(e,Z);var XC=new Set(YC.keys());xv.set(`PreTrainedModel`,X.EncoderOnly),Cv.set(Z,`PreTrainedModel`);var Q={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:vC,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:yC,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:gC,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:_C,MODEL_FOR_MASKED_LM_MAPPING_NAMES:CC,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:wC,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:kC,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:MC,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:NC,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:PC,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:AC,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:jC,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:FC,MODEL_FOR_CTC_MAPPING_NAMES:IC,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:LC,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:RC,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:zC,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:OC,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:BC,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:HC,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:UC,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:WC,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:GC,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:KC,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:EC,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:DC,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:bC,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:hC,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:xC,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:TC};gv(Q);var $=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await x0.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \"+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await Gv[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return XC.has(p)||N.warn(`Unknown model class \"${p}\", attempting to construct from base class.`),await Z.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},ZC=class extends ${static MODEL_CLASS_MAPPINGS=qC.map(e=>e[0]);static BASE_IF_FAIL=!0},QC=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},$C=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},ew=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},tw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},nw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},rw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},iw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},aw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},ow=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},sw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},cw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},lw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},uw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},dw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},fw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},pw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var mw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CTC_MAPPING_NAMES]},hw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var gw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var _w=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},vw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var yw=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function bw(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>Mg.read(e)))}async function xw(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?Ih(e,t):e instanceof Float64Array?new Float32Array(e):e))}function Sw(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var Cw=class extends Vs{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},ww=class extends Cw{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new H(`float32`,Xf(e.data),e.dims),s=[];for(let e of r.logits){let n=await Yp(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},Tw=class extends Cw{async _call(e,{ignore_labels:t=[`O`],aggregation_strategy:n=`none`}={}){if(n!==`none`&&n!==`simple`)throw Error(`Invalid aggregation_strategy: \"${n}\". Must be one of \"none\" or \"simple\".`);let r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(i)).logits,o=this.model.config.id2label,s=[];for(let e=0;e<a.dims[0];++e){let r=i.input_ids[e].tolist(),c=a[e],l=[];for(let e=0;e<c.dims[0];++e){let n=c[e],i=$f(n.data)[1],a=o?o[i]:`LABEL_${i}`;if(t.includes(a))continue;let s=this.tokenizer.decode([r[e]],{skip_special_tokens:!0});if(s===``)continue;let u=Xf(n.data);l.push({entity:a,score:u[i],index:e,word:s})}s.push(n===`simple`?Dw(l,r,this.tokenizer):l)}return r?s:s[0]}};function Ew(e){let t=e[0];return e[1]===`-`&&(t===`B`||t===`I`||t===`E`||t===`S`)?[t,e.slice(2)]:[`I`,e]}function Dw(e,t,n){let r=[],i=null;for(let t=0;t<e.length;++t){let[n,a]=Ew(e[t].entity);i===a&&n!==`B`&&n!==`S`?(r[r.length-1].end=t+1,n===`E`&&(i=null)):(r.push({tag:a,start:t,end:t+1}),i=n===`S`?null:a)}return r.map(({tag:r,start:i,end:a})=>{let o=0,s=[];for(let n=i;n<a;++n)o+=e[n].score,s.push(t[e[n].index]);return{entity_group:r,score:o/(a-i),word:n.decode(s,{skip_special_tokens:!0})}})}var Ow=class extends Cw{async _call(e,t,{top_k:n=1}={}){let r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),i=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(r),s=r.input_ids.tolist(),c=r.attention_mask.tolist(),{all_special_ids:l,sep_token_id:u}=this.tokenizer,d=[];for(let e=0;e<a.dims[0];++e){let t=s[e],r=t.findIndex(e=>e==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;n<i.length;++n)(c[e]==0||n<=r||l.findIndex(e=>e==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=Xf(i).map((e,t)=>[e,t]),m=Xf(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=Js(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;e<Math.min(h.length,n);++e){let[n,r,i]=h[e],a=t.slice(n,r+1),o=this.tokenizer.decode(a,{skip_special_tokens:!0});g.push({answer:o,score:i})}n===1?d.push(...g):d.push(g)}return i?d:d[0]}},kw=class extends Cw{async _call(e,{top_k:t=5}={}){let{mask_token_id:n,mask_token:r}=this.tokenizer,i=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(i),o=[],s=i.input_ids.tolist();for(let e=0;e<s.length;++e){let i=s[e],c=i.findIndex(e=>e==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await Yp(new H(`float32`,Xf(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Aw=class extends Cw{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},jw=class extends Aw{_key=`summary_text`},Mw=class extends Aw{_key=`translation_text`};function Nw(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var Pw=class extends Cw{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:n,return_full_text:r,tools:i,documents:a,chat_template:o,tokenizer_encode_kwargs:s,...c}=t,l=!1,u=!1,d=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,f=s,p;if(typeof e==`string`)p=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))l=!0,p=e;else{if(Nw(e))e=[e];else if(Array.isArray(e)&&e.every(Nw))l=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);u=!0;let t={tokenize:!1,add_generation_prompt:!0,...Xs({tools:i,documents:a,chat_template:o},[`tools`,`documents`,`chat_template`]),...f};p=e.map(e=>this.tokenizer.apply_chat_template(e,t)),d=!1,f=void 0}let m=u?!1:r??!0;this.tokenizer.padding_side=`left`;let h=this.tokenizer(p,{add_special_tokens:d,padding:!0,truncation:!0,...f}),g=await this.model.generate({...h,...this._default_generation_config,...c}),_=this.tokenizer.batch_decode(g,{skip_special_tokens:!0}),v;!m&&h.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let y=Array.from({length:e.length},e=>[]);for(let t=0;t<_.length;++t){let n=Math.floor(t/g.dims[0]*e.length);v&&(_[t]=_[t].slice(v[n])),y[n].push({generated_text:u?[...e[n],{role:`assistant`,content:_[t]}]:_[t]})}return!l&&y.length===1?y[0]:y}},Fw=class extends Cw{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(N.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&&(N.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>Xf(e)[1]):Xf(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},Iw=class extends Cw{async _call(e,{top_k:t=5}={}){let n=await xw(e,this.processor.feature_extractor.config.sampling_rate),r=this.model.config.id2label,i=[];for(let e of n){let n=await this.processor(e),a=(await this.model(n)).logits[0],o=await Yp(new H(`float32`,Xf(a.data),a.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:r?r[e]:`LABEL_${e}`,score:s[t]}));i.push(c)}return Array.isArray(e)?i:i[0]}},Lw=class extends Cw{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await xw(e,o),c=[];for(let e of s){let n=await this.processor(e),r=Xf((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},Rw=class extends Cw{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&N.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".'),t.task&&N.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');let n=!Array.isArray(e),r=await xw(n?[e]:e,this.processor.feature_extractor.config.sampling_rate),i=[];for(let e of r){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push($f(e.data)[1]);let a=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();i.push({text:a})}return n?i[0]:i}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await xw(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>ap(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await xw(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.tokenizer.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=await xw(r,i.config.sampling_rate),o=t.language??`en`,s=this.processor.get_decoder_prompt_ids(o),c=[];for(let e of a){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:s,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,o);c.push({text:a})}return n?c[0]:c}},zw=class extends Cw{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await M.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new H(`float32`,e,[e.length]);else if(!(e instanceof H))throw Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e<a;++e){let t=s?Math.min(Math.ceil(s[e]),o):o,r=e*o;c.push(new tg(i.slice(r,r+t),n))}return Array.isArray(e)?c:c[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type===`supertonic`?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:n,speed:r}){if(!t)throw Error(`Speaker embeddings must be provided for Supertonic models.`);let{sampling_rate:i,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),s=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,s),t=t.view(s,-1,a);let{waveform:c,durations:l}=await this.model.generate_speech({...o,style:t,num_inference_steps:n,speed:r});return this._postprocess_waveform(e,c,i,l)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return this._postprocess_waveform(e,n,r)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||=(N.info(`No vocoder specified, using default HifiGan vocoder.`),await ZC.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:`fp32`}));let{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),r=n.dims[0];t=await this._prepare_speaker_embeddings(t,r),t=t.view(r,-1);let{waveform:i}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,i,a)}},Bw=class extends Cw{async _call(e,t={}){let n=Array.isArray(e),r=await bw(e),{pixel_values:i}=await this.processor(r),a=[];for(let e of i){e.dims=[1,...e.dims];let n=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},Vw=class extends Cw{async _call(e,{top_k:t=5}={}){let n=await bw(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await Yp(new H(`float32`,Xf(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},Hw={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},Uw=class extends Cw{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=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 s=await bw(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=Hw[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(Hw))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=f[d[0]];for(let t=0;t<c.length;++t){let n=c[t],r=e[t];r.data.some(e=>e<-1e-5||e>1.00001)&&r.sigmoid_();let i=await Mg.fromTensor(r.mul_(255).to(`uint8`)).resize(n[1],n[0]);h.push({label:null,score:null,mask:i})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n<o.data.length;++n)o.data[n]===t.id&&(e[n]=255);let n=new Mg(e,o.dims[1],o.dims[0],1);h.push({score:t.score,label:m[t.label_id],mask:n})}}else if(o===`semantic`){let{segmentation:e,labels:t}=p(f,a??c)[0];for(let n of t){let t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r)e.data[r]===n&&(t[r]=255);let r=new Mg(t,e.dims[1],e.dims[0],1);h.push({score:null,label:m[n],mask:r})}}else throw Error(`Subtask ${o} not supported.`);return h}};Object.freeze({\"text-classification\":{pipeline:ww,model:QC,default:{model:`Xenova/distilbert-base-uncased-finetuned-sst-2-english`},type:`text`},\"token-classification\":{pipeline:Tw,model:$C,default:{model:`Xenova/bert-base-multilingual-cased-ner-hrl`},type:`text`},\"question-answering\":{pipeline:Ow,model:ow,default:{model:`Xenova/distilbert-base-cased-distilled-squad`},type:`text`},\"fill-mask\":{pipeline:kw,model:aw,default:{model:`onnx-community/ettin-encoder-32m-ONNX`,dtype:`fp32`},type:`text`},summarization:{pipeline:jw,model:ew,default:{model:`Xenova/distilbart-cnn-6-6`},type:`text`},translation:{pipeline:Mw,model:ew,default:{model:`Xenova/t5-small`},type:`text`},\"text2text-generation\":{pipeline:Aw,model:ew,default:{model:`Xenova/flan-t5-small`},type:`text`},\"text-generation\":{pipeline:Pw,model:iw,default:{model:`onnx-community/Qwen3-0.6B-ONNX`,dtype:`q4`},type:`text`},\"zero-shot-classification\":{pipeline:Fw,model:QC,default:{model:`Xenova/distilbert-base-uncased-mnli`},type:`text`},\"audio-classification\":{pipeline:Iw,model:hw,default:{model:`Xenova/wav2vec2-base-superb-ks`},type:`audio`},\"zero-shot-audio-classification\":{pipeline:Lw,model:ZC,default:{model:`Xenova/clap-htsat-unfused`},type:`multimodal`},\"automatic-speech-recognition\":{pipeline:Rw,model:[tw,mw],default:{model:`Xenova/whisper-tiny.en`},type:`multimodal`},\"text-to-audio\":{pipeline:zw,model:[rw,nw],default:{model:`onnx-community/Supertonic-TTS-ONNX`,dtype:`fp32`},type:`text`},\"image-to-text\":{pipeline:Bw,model:sw,default:{model:`Xenova/vit-gpt2-image-captioning`},type:`multimodal`},\"image-classification\":{pipeline:Vw,model:cw,default:{model:`Xenova/vit-base-patch16-224`},type:`multimodal`},\"image-segmentation\":{pipeline:Uw,model:[lw,uw,dw],default:{model:`Xenova/detr-resnet-50-panoptic`},type:`multimodal`},\"background-removal\":{pipeline:class extends Uw{async _call(e,t={}){let n=await bw(e),r=await super._call(e,t),i=n.map((e,t)=>{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[lw,uw,dw],default:{model:`Xenova/modnet`},type:`image`},\"zero-shot-image-classification\":{pipeline:class extends Cw{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await bw(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type!==`siglip`||`max_length`,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>Xf(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:ZC,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},\"object-detection\":{pipeline:class extends Cw{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await bw(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:Sw(t,!n)})));return r?d:d[0]}},model:fw,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},\"zero-shot-object-detection\":{pipeline:class extends Cw{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await bw(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e<o.length;++e){let a=o[e],u=i?null:[[a.height,a.width]],d=c.pixel_values[e].unsqueeze_(0),f=await this.model({...s,pixel_values:d}),p;if(`post_process_grounded_object_detection`in this.processor){let e=this.processor.post_process_grounded_object_detection(f,s.input_ids,{box_threshold:n,text_threshold:n,target_sizes:u})[0];p=e.boxes.map((t,n)=>({score:e.scores[n],label:e.labels[n],box:Sw(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:Sw(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:pw,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},\"document-question-answering\":{pipeline:class extends Cw{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){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 r=(await bw(e))[0],{pixel_values:i}=await this.processor(r),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/<s_answer>(.*?)<\\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:gw,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},\"image-to-image\":{pipeline:class extends Cw{async _call(e){let t=await bw(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push(Mg.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:_w,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},\"depth-estimation\":{pipeline:class extends Cw{async _call(e){let t=await bw(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e<t.length;++e){let n=r[e],[a,o]=n.dims.slice(-2),[s,c]=t[e].size,l=(await qp(n.view(1,1,a,o),{size:[c,s],mode:`bilinear`})).view(c,s),u=l.min().item(),d=l.max().item(),f=l.sub(u).div_(d-u).mul_(255).to(`uint8`).unsqueeze(0),p=Mg.fromTensor(f);i.push({predicted_depth:l,depth:p})}return Array.isArray(e)?i:i[0]}},model:vw,default:{model:`onnx-community/depth-anything-v2-small`},type:`image`},\"feature-extraction\":{pipeline:class extends Cw{async _call(e,{pooling:t=`none`,normalize:n=!1,quantize:r=!1,precision:i=`binary`}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a),s=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case`none`:break;case`mean`:s=Qp(s,a.attention_mask);break;case`first_token`:case`cls`:s=s.slice(null,0);break;case`last_token`:case`eos`:s=s.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return n&&(s=s.normalize(2,-1)),r&&(s=hm(s,i)),s}},model:ZC,default:{model:`onnx-community/all-MiniLM-L6-v2-ONNX`,dtype:`fp32`},type:`text`},\"image-feature-extraction\":{pipeline:class extends Cw{async _call(e,{pool:t=null}={}){let n=await bw(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),a;if(t){if(!(`pooler_output`in i))throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}},model:[yw,ZC],default:{model:`onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX`,dtype:`fp32`},type:`image`}}),Object.freeze({\"sentiment-analysis\":`text-classification`,ner:`token-classification`,asr:`automatic-speech-recognition`,\"text-to-speech\":`text-to-audio`,embeddings:`feature-extraction`});var Ww=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}};j.IS_PROCESS_AVAILABLE,Object.keys(Vp);let Gw=/^[\\w.-]+\\/[\\w.-]+$/,Kw=/^[a-f0-9]{40}$/,qw=/^[a-f0-9]{64}$/,Jw=/^(?!.*(?:^|\\/)\\.{1,2}(?:\\/|$))[\\w.@-]+(?:\\/[\\w.@-]+)*$/,Yw={\"litert-chat\":{task:`chat`},\"onnx-chat\":{task:`chat`},\"laya-choice\":{task:`classification`},\"janus-image\":{task:`image`},\"sd-turbo\":{task:`image`}},Xw=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`onnx/model_fp16.onnx`,`onnx/model_fp16.onnx_data`],Zw=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`processor_config.json`,`preprocessor_config.json`,`onnx/prepare_inputs_embeds_q4.onnx`,`onnx/language_model_q4f16.onnx`,`onnx/lm_head_fp16.onnx`,`onnx/gen_head_fp16.onnx`,`onnx/gen_img_embeds_fp16.onnx`,`onnx/image_decode.onnx`],Qw=[`text_encoder/model.onnx`,`unet/model.onnx`,`vae_decoder/model.onnx`],$w=[`tokenizer/tokenizer.json`,`tokenizer/tokenizer_config.json`],eT=[`config.json`,`tokenizer.json`,`tokenizer_config.json`];function tT(e){let t=/^onnx\\/(model|decoder_model_merged)(?:_(q4f16|q4|quantized|fp16))?\\.onnx$/.exec(e);if(t)return{modelFile:t[1],dtype:t[2]===`quantized`?`q8`:t[2]??`fp32`}}function nT(e,t){let n=`${e}_data`,r=t.filter(e=>e===n||e.startsWith(`${n}_`)&&/^[1-9]\\d*$/.test(e.slice(n.length+1)));if(!r.length)return[];let i=r.map((e,t)=>t===0?n:`${n}_${t}`);return i.every(e=>r.includes(e))?i:void 0}function rT(e){return typeof e==`string`&&Gw.test(e)&&e.split(`/`).every(e=>Jw.test(e))}function iT(e){return typeof e==`string`&&Jw.test(e)}function aT(e,t,n){return`https://huggingface.co/${e}/resolve/${t}/${n.split(`/`).map(encodeURIComponent).join(`/`)}`}function oT(e){let t=e?.source===`local`;if(!e||e.version!==1||!Object.hasOwn(Yw,e.adapter)||(t?e.repo!==`local/model`||e.revision!==void 0:!rT(e.repo)||typeof e.revision!=`string`||!Kw.test(e.revision))||!Array.isArray(e.files)||e.files.length===0||e.files.length>24||!e.files.every(e=>e&&iT(e.path)&&Number.isSafeInteger(e.size)&&e.size>0&&(e.sha256===void 0||typeof e.sha256==`string`&&qw.test(e.sha256))))return!1;let n=new Set(e.files.map(({path:e})=>e));if(n.size!==e.files.length)return!1;switch(e.adapter){case`litert-chat`:return e.files.length===1&&/\\.litertlm$/i.test(e.files[0].path)&&(t||qw.test(e.files[0].sha256));case`onnx-chat`:{let t=e.files[0].path;return!!(tT(t)&&eT.every(e=>n.has(e))&&nT(t,[...n]))}case`laya-choice`:return Xw.every(e=>n.has(e));case`janus-image`:return Zw.every(e=>n.has(e));case`sd-turbo`:return Qw.every(e=>n.has(e))&&(t?$w.every(e=>n.has(e)):e.repo.toLowerCase()===`schmuell/sd-turbo-ort-web`)}}let sT=`browser-model-sdk-weights-v1`,cT=`transformers-cache`,lT={repo:`Xenova/clip-vit-base-patch32`,revision:`6b7c523703ae26e39be4b03774966f8571c7f523`,files:[{path:`tokenizer.json`,size:2224119},{path:`tokenizer_config.json`,size:775}]};function uT(e){if(e.source===`local`)return e.files;let t=e.files.map(t=>{let n=e.adapter===`litert-chat`?`opfs`:e.adapter===`sd-turbo`||e.adapter===`laya-choice`&&t.path.startsWith(`onnx/`)?sT:cT;return{...t,store:n,url:aT(e.repo,e.revision,t.path)}});if(e.adapter===`sd-turbo`)for(let e of lT.files)t.push({...e,path:`tokenizer/${e.path}`,store:cT,url:aT(lT.repo,lT.revision,e.path)});return t}function dT(e,t,n,{file:r,cause:i,retryable:a=!1,httpStatus:o}={}){let s=Error(n,{cause:i});return s.details={kind:e,stage:t,file:r,retryable:a,...o===void 0?{}:{httpStatus:o}},s}function fT(e,t=!1){let n=e?.message??String(e),r=e?.cause??e;return{message:n,details:e?.details??(t?{kind:e?.name===`GPUOutOfMemoryError`?`gpu-allocation`:`initialize`,stage:`initialize`,retryable:!1}:void 0),cause:{name:r?.name??`Error`,message:r?.message??String(r)}}}function pT(e,t=!1){let n=0,r=0,i=0,a,o=/* @__PURE__ */ new Map;function s(t,n,r){let i=r?.name===`QuotaExceededError`,o=dT(i?`quota`:`cache`,t,`${i?`Browser model storage is full.`:`Browser model storage is unavailable.`} Try loading from a local folder or reopening with cache: 'memory-only'.`,{file:n,cause:r});if(a??=o,e===`require`)throw o}function c(e){return o.has(e)||o.set(e,Promise.resolve().then(()=>globalThis.caches.open(e))),o.get(e)}function l(){if(e===`require`&&a)throw a}return{policy:e,unavailable:s,hit(){n++},stored(){r++},skip(){i++},assertAvailable:l,async match(t,n,r){if(e!==`memory-only`)try{return await(await c(t)).match(n)}catch(e){s(`cache-read`,r,e)}},async put(t,n,a,o){if(e===`memory-only`)i++;else try{await(await c(t)).put(n,a),r++}catch(e){s(`cache-write`,o,e),i++}},snapshot(){return l(),{policy:e,hits:n,writes:r,bypassed:i,status:t?`local`:n+r?i?`mixed`:`cached`:`memory`,...a?{warning:{...a.details,message:a.message}}:{}}}}}\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nfunction mT(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function hT(e,t,n=``){let r=mT(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`\"${n}\" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function gT(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function _T(e,t){hT(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`\"digestInto() output\" expected to be of length >=`+n)}function vT(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function yT(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bT(e,t){return e<<32-t|e>>>t}let xT=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,ST=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function CT(e){if(hT(e),xT)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=ST[e[n]];return t}function wT(e,t={}){let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}let TT=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ET(e,t,n){return e&t^~e&n}function DT(e,t,n){return e&t^e&n^t&n}var OT=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=yT(this.buffer)}update(e){gT(this),hT(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=yT(e);for(;r<=i-a;a+=r)this.process(t,a)}else n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){gT(this),_T(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,vT(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(this.length*8),i),this.process(n,0);let o=yT(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen must be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};let kT=/* @__PURE__ */ Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,528734635,0x5be0cd19]),AT=/* @__PURE__ */ Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,961987163,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,310598401,607225278,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,604807628,770255983,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,338241895,666307205,773529912,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,275423344,430227734,506948616,659060556,883997877,958139571,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),jT=/* @__PURE__ */ new Uint32Array(64);var MT=class extends OT{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)jT[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=jT[e-15],n=jT[e-2],r=bT(t,7)^bT(t,18)^t>>>3,i=bT(n,17)^bT(n,19)^n>>>10;jT[e]=i+jT[e-7]+r+jT[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=bT(o,6)^bT(o,11)^bT(o,25),u=l+t+ET(o,s,c)+AT[e]+jT[e]|0,d=(bT(n,2)^bT(n,13)^bT(n,22))+DT(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){vT(jT)}destroy(){this.set(0,0,0,0,0,0,0,0),vT(this.buffer)}},NT=class extends MT{A=kT[0]|0;B=kT[1]|0;C=kT[2]|0;D=kT[3]|0;E=kT[4]|0;F=kT[5]|0;G=kT[6]|0;H=kT[7]|0;constructor(){super(32)}};let PT=/* @__PURE__ */ wT(()=>new NT,/* @__PURE__ */ TT(1));function FT(e,t,n,r=``){let i=`/__webinference_local__/`,a=`${i}${t}/`;e.allowLocalModels=!0,e.allowRemoteModels=!1,e.useBrowserCache=!1,e.localModelPath=i,e.fetch=async(t,i)=>{let o=String(t),s=e.backends.onnx.wasm.wasmPaths;if(o===s?.wasm||o===s?.mjs)return fetch(t,i);let c=o.startsWith(a)&&n.get(`${r}${o.slice(a.length)}`);return c?new Response(c,{headers:{\"Content-Length\":String(c.size)}}):new Response(null,{status:404})}}let IT=/^https:\\/\\/huggingface\\.co\\/[^/]+\\/[^/]+\\/resolve\\/[a-f0-9]{40}\\/(.+)$/;function LT(e,t,n){let r=uT(t),i=new Map(r.map(e=>[e.url,e])),a=e=>i.get(e)?.path??IT.exec(e)?.[1],o=e.fetch;e.useBrowserCache=!1,n.policy!==`memory-only`&&(e.useCustomCache=!0,e.customCache={async match(e){let t=a(e);if(!t)return;let r=await n.match(cT,e,t),o=r?.headers.get(`Content-Length`);if(r&&(!o||!i.has(e)||Number(o)===i.get(e).size))return n.hit(),r},async put(e,t){let r=a(e);r&&await n.put(cT,e,t,r)}}),e.fetch=async(e,t)=>{let r=String(e),s=i.get(r);if(a(r)&&n.assertAvailable(),s&&!new Headers(t?.headers).has(`Range`))return n.policy===`memory-only`&&n.skip(),zT(s,void 0,t);if(a(r)){let r=await fetch(e,{...t,credentials:`omit`,cache:`no-store`});return r.ok&&n.policy===`memory-only`&&!new Headers(t?.headers).has(`Range`)&&n.skip(),r}return o(e,t)}}function RT(e,t){let n=e?.get(t.path);if(!n||n.size!==t.size)throw dT(`local-file`,`read`,`The selected file ${t.path} is missing or has changed. Select the folder again.`,{file:t.path});return n}async function zT({url:e,path:t,size:n,sha256:r},i,a){let o;try{o=await fetch(e,{...a,credentials:`omit`,cache:`no-store`})}catch(e){throw dT(`download-interrupted`,`download`,`Could not download ${t}. Try again.`,{file:t,cause:e,retryable:!0})}if(!o.ok||!o.body){let e=o.status;throw dT(`download-http`,`download`,`Could not download ${t} (HTTP ${e}).`,{file:t,httpStatus:e,retryable:e===408||e===429||e>=500})}let s=o.body.getReader(),c=r&&PT.create(),l=0,u=-1/0,d=new ReadableStream({async pull(e){try{let{done:a,value:o}=await s.read();if(a){if(l!==n)throw dT(`download-interrupted`,`download`,`The download for ${t} was incomplete. Try again.`,{file:t,retryable:!0});if(c&&CT(c.digest())!==r)throw dT(`integrity`,`verify`,`The checksum for ${t} does not match the pinned model.`,{file:t});i?.(n),e.close();return}if(l+=o.byteLength,l>n)throw dT(`integrity`,`verify`,`The download for ${t} exceeded its expected size.`,{file:t});c?.update(o);let d=performance.now();d-u>=150&&(i?.(l),u=d),e.enqueue(o)}catch(n){let r=n?.details?n:dT(`download-interrupted`,`download`,`The transfer of ${t} was interrupted. Try again.`,{file:t,cause:n,retryable:!0});e.error(r),await s.cancel(r).catch(()=>{})}},cancel(e){return s.cancel(e)}});return new Response(d,{headers:{\"Content-Length\":String(n)}})}async function BT({asset:e,url:t,onProgress:n,localFiles:r,cache:i}){let{path:a,size:o}=e,s;if(r)s=RT(r,e);else{i.assertAvailable();let r=await i.match(sT,t,a);if(r){try{s=await r.blob()}catch(e){i.unavailable(`cache-read`,a,e)}s?.size===o?i.hit():s=void 0}s||(s=await(await zT({...e,url:t},n)).blob(),await i.put(sT,t,new Response(s,{headers:{\"Content-Length\":String(o)}}),a))}try{let e=new Uint8Array(await s.arrayBuffer());return n(o),e}catch(e){throw dT(r?`local-file`:`initialize`,`read`,`Could not read ${a}. Choose a smaller model or select the file again.`,{file:a,cause:e})}}let VT=[{key:`encoder`,path:`text_encoder/model.onnx`,dimensions:{batch_size:1}},{key:`unet`,path:`unet/model.onnx`,dimensions:{batch_size:1,num_channels:4,height:64,width:64,sequence_length:77}},{key:`decoder`,path:`vae_decoder/model.onnx`,dimensions:{batch_size:1,num_channels_latent:4,height_latent:64,width_latent:64}}],HT,UT=!1;function WT(e,t={}){self.postMessage({type:e,...t})}M.allowLocalModels=!1,M.backends.onnx.wasm.numThreads=1,w.wasm.numThreads=1,w.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/`,w.webgpu.powerPreference=`high-performance`;async function GT(e,t,n){let r;t?(FT(M,e.repo,t,`tokenizer/`),r=await G.from_pretrained(e.repo)):r=await G.from_pretrained(lT.repo,{revision:lT.revision}),r.pad_token_id=0;let i={},a=0;for(let r of VT){let o=await BT({url:t?void 0:aT(e.repo,e.revision,r.path),localFiles:t,cache:n,asset:e.files.find(({path:e})=>e===r.path),onProgress:e=>WT(`load-progress`,{loaded:a+e})});a+=o.byteLength,WT(`load-progress`,{loaded:a,label:`Preparing ${r.key}`}),i[r.key]=await Pe.create(o,{executionProviders:[`webgpu`],freeDimensionOverrides:r.dimensions,enableMemPattern:!1,enableCpuMemArena:!1,extra:{session:{disable_prepacking:`1`,use_device_allocator_for_initializers:`1`,use_ort_model_bytes_directly:`1`,use_ort_model_bytes_for_initializers:`1`}}})}return{tokenizer:r,sessions:i}}function KT(e){let t=e>>>0;function n(){t=t+0x6d2b79f5>>>0;let e=Math.imul(t^t>>>15,t|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/2**32}let r=/* @__PURE__ */ new Float32Array(16384);for(let e=0;e<r.length;e++)r[e]=Math.sqrt(-2*Math.log(1-n()))*Math.cos(2*Math.PI*n());return r}async function qT(e,t){let{tokenizer:n,sessions:r}=HT,i=[1,4,64,64],a=n(e,{padding:`max_length`,truncation:!0,max_length:77,return_tensor:!1}),o=[];function s(e){return o.push(e),e}try{WT(`generate-progress`,{label:`Encoding prompt`,fraction:.15});let e=s(new Ae(`int32`,Int32Array.from(a.input_ids,Number),[1,77])),n=await r.encoder.run({input_ids:e});for(let e of Object.values(n))s(e);WT(`generate-progress`,{label:`Denoising image`,fraction:.35});let o=14.6146,c=KT(t),l=c.map(e=>e*o/Math.hypot(o,1)),u=s((await r.unet.run({sample:s(new Ae(`float32`,l,i)),timestep:s(new Ae(`int64`,BigInt64Array.of(999n),[1])),encoder_hidden_states:n.last_hidden_state})).out_sample).data,d=c.map((e,t)=>(e-u[t])*o/.18215);WT(`generate-progress`,{label:`Decoding pixels`,fraction:.8});let f=s((await r.decoder.run({latent_sample:s(new Ae(`float32`,d,i))})).sample),p=f.data,[,,m,h]=f.dims,g=m*h,_=new Uint8ClampedArray(g*4);for(let e=0;e<g;e++){for(let t=0;t<3;t++)_[e*4+t]=(p[t*g+e]+1)*127.5;_[e*4+3]=255}let v=new OffscreenCanvas(h,m);return v.getContext(`2d`).putImageData(new ImageData(_,h,m),0,0),{blob:await v.convertToBlob({type:`image/png`}),width:h,height:m}}finally{for(let e of o)e.dispose()}}async function JT(e,t){t&&FT(M,e.repo,t);let n=/* @__PURE__ */ new Map,r=t?-1/0:0,i={revision:e.revision,progress_callback(e){if(e.status!==`progress`)return;n.set(e.file,e.loaded);let t=performance.now();t-r<150||(r=t,WT(`load-progress`,{loaded:[...n.values()].reduce((e,t)=>e+t,0)}))}},{repo:a}=e;return{processor:await h0.from_pretrained(a,i),janus:await bx.from_pretrained(a,{...i,device:{prepare_inputs_embeds:`wasm`,language_model:`webgpu`,lm_head:`webgpu`,gen_head:`webgpu`,gen_img_embeds:`webgpu`,image_decode:`webgpu`},dtype:{prepare_inputs_embeds:`q4`,language_model:`q4f16`,lm_head:`fp16`,gen_head:`fp16`,gen_img_embeds:`fp16`,image_decode:`fp32`}})}}async function YT(e){let{processor:t,janus:n}=HT,r=await t([{role:`<|User|>`,content:e}],{chat_template:`text_to_image`}),i=t.num_image_tokens,a=-1;class o extends Ww{put(){a++,a>0&&(a%32==0||a===i)&&WT(`generate-progress`,{label:`Rendering image tokens · ${a} / ${i}`,fraction:a/i})}end(){WT(`generate-progress`,{label:`Decoding pixels`,fraction:.99})}}let[s]=await n.generate_images({...r,do_sample:!0,min_new_tokens:i,max_new_tokens:i,streamer:new o});return{blob:await s.toBlob(),width:s.width,height:s.height}}self.addEventListener(`message`,async({data:e})=>{if(!UT){UT=!0;try{if(e.type===`load`){let{registration:t,localFiles:n,cache:r}=e;if(!oT(t)||![`sd-turbo`,`janus-image`].includes(t.adapter))throw Error(`Choose a compatible image generation export.`);let i=t.adapter,a=pT(r,!!n);n||LT(M,t,a),HT={engine:i,...i===`sd-turbo`?await GT(t,n,a):await JT(t,n)},WT(`ready`,{cache:a.snapshot()})}else e.type===`generate`&&HT&&WT(`result`,HT.engine===`sd-turbo`?await qT(e.prompt,e.seed):await YT(e.prompt))}catch(t){WT(`error`,fT(t,e.type===`load`))}finally{UT=!1}}})})();", t = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", e], { type: "text/javascript;charset=utf-8" });
3
3
  function n(n) {
4
4
  let r;
5
5
  try {