diff --git "a/assets/worker-Bv61e-dB.js" "b/assets/worker-Bv61e-dB.js" new file mode 100644--- /dev/null +++ "b/assets/worker-Bv61e-dB.js" @@ -0,0 +1,39 @@ +(function(){var e=Object.defineProperty,t=((t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r})({InferenceSession:()=>De,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>Se,TRACE_EVENT_END:()=>Ce,TRACE_FUNC_BEGIN:()=>O,TRACE_FUNC_END:()=>xe,Tensor:()=>_e,default:()=>rr,env:()=>S,registerBackend:()=>p}),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){if(typeof require<`u`)return require.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),s=(e,t)=>()=>(e&&(t=e(e=0)),t),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=s(()=>{"use strict";d=new Map,f=[],p=(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{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{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}}},h=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=new Set;for(let e of r){let t=await m(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)})]}}),_=s(()=>{"use strict";g()}),v,y=s(()=>{"use strict";v=`1.24.0-dev.20251116-b39e144322`}),b,x,ee=s(()=>{"use strict";y(),b=`warning`,x={wasm:{},webgl:{},webgpu:{},versions:{common:v},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}`);b=e}},get logLevel(){return b}},Object.defineProperty(x,`logLevel`,{enumerable:!0})}),S,te=s(()=>{"use strict";ee(),S=x}),C,w,ne=s(()=>{"use strict";C=(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{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{"use strict";ge(),re=(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{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,re(o,s)}else 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(re(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return re(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},E=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new he({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ie=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new he({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},ae=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new he({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},oe=(e,t,n)=>new he({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),ce,D,le,ue,de=s(()=>{"use strict";ce=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),D=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),le=!1,ue=()=>{if(!le){le=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(ce.set(`int64`,BigInt64Array),D.set(BigInt64Array,`int64`)),t&&(ce.set(`uint64`,BigUint64Array),D.set(BigUint64Array,`uint64`)),r?(ce.set(`float16`,n),D.set(n,`float16`)):ce.set(`float16`,Uint16Array)}}}),fe,pe,me=s(()=>{"use strict";ge(),fe=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new he(e.type,e.data,t);case`cpu-pinned`:return new he({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new he({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new he({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new he({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),he,ge=s(()=>{"use strict";ne(),se(),de(),me(),he=class{constructor(e,t,n){ue();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=ce.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=ce.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=D.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=fe(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 T(e,t)}static fromTexture(e,t){return E(e,t)}static fromGpuBuffer(e,t){return ie(e,t)}static fromMLTensor(e,t){return ae(e,t)}static fromPinnedBuffer(e,t,n){return oe(e,t,n)}toDataURL(e){return C(this,e)}toImageData(e){return w(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 pe(this,e)}}}),_e,ve=s(()=>{"use strict";ge(),_e=he}),ye,be,O,xe,Se,Ce,we=s(()=>{"use strict";ee(),ye=(e,t)=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeStamp(`${e}::ORT::${t}`)},be=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||be(`BEGIN`,e)},xe=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||be(`END`,e)},Se=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.time(`ORT::${e}`)},Ce=e=>{(typeof x.trace>`u`?!x.wasm.trace:!x.trace)||console.timeEnd(`ORT::${e}`)}}),Te,Ee=s(()=>{"use strict";g(),ve(),we(),Te=class e{constructor(e){this.handler=e}async run(e,t,n){O(),Se(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof _e||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 _e)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 _e)&&(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];t instanceof _e?s[e]=t:s[e]=new _e(t.type,t.data,t.dims)}return Ce(`InferenceSession.run`),xe(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){O(),Se(`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 h(o),l=await s.createInferenceSessionHandler(a,c);return Ce(`InferenceSession.create`),xe(),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}}}),De,Oe=s(()=>{"use strict";Ee(),De=Te}),ke=s(()=>{"use strict";}),Ae=s(()=>{"use strict";}),je=s(()=>{"use strict";}),Me=s(()=>{"use strict";}),Ne={};c(Ne,{InferenceSession:()=>De,TRACE:()=>ye,TRACE_EVENT_BEGIN:()=>Se,TRACE_EVENT_END:()=>Ce,TRACE_FUNC_BEGIN:()=>O,TRACE_FUNC_END:()=>xe,Tensor:()=>_e,env:()=>S,registerBackend:()=>p});var Pe=s(()=>{"use strict";_(),te(),Oe(),ve(),ke(),Ae(),we(),je(),Me()}),Fe=s(()=>{"use strict";}),Ie={};c(Ie,{default:()=>ze});var Le,Re,ze,Be=s(()=>{"use strict";Dn(),ht(),ot(),Le=`ort-wasm-proxy-worker`,Re=globalThis.self?.name===Le,Re&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:mt(n.wasm).then(()=>{hn(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;gn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=bn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;xn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:Sn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;wn(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},En([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:Tn(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),ze=Re?null:e=>new Worker(e??Ye,{type:`module`,name:Le})}),Ve={};c(Ve,{default:()=>Ue});async function He(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.Uc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=ln;return t=e(...t),ln==n?t:new Promise((e,t)=>{gn={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=self.location.href,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(ee(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,ee=e=>e.startsWith(`file://`);function S(){Me.buffer!=C.buffer&&le()}if(i){let e=function(n){try{var r=n.data,i=r.Oc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({Oc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.de)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Oc:`callHandler`,ce:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));Me=r.je,le(),f=r.ke,pe(),Lo()}else if(i===`run`){(function(e){var t=(S(),E)[e+52>>>2>>>0];e=(S(),E)[e+56>>>2>>>0],ia(t,t-e),I(t)})(r.Nc),Yi(r.Nc,0,0,1,0,0),ke(),Zt(r.Nc),te||=(Ei(),!0);try{Ne(r.he,r.Wc)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?te&&Qt():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw Xi(),e}};var te=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var C,w,ne,re,T,E,ie,ae,oe,se,ce,D=!1;function le(){var e=Me.buffer;t.HEAP8=C=new Int8Array(e),ne=new Int16Array(e),t.HEAPU8=w=new Uint8Array(e),re=new Uint16Array(e),t.HEAP32=T=new Int32Array(e),t.HEAPU32=E=new Uint32Array(e),ie=new Float32Array(e),ae=new Float64Array(e),oe=new BigInt64Array(e),se=new BigUint64Array(e)}function ue(){D=!0,i?g():Xa._b()}function de(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function fe(){return{a:{f:Le,J:ze,k:We,p:Ge,l:Ke,ta:qe,b:Je,ca:Ye,Ka:Ze,q:Qe,da:rt,_a:it,Ga:at,Ia:ot,$a:st,Ya:ct,Ra:lt,Xa:ut,pa:dt,Ha:ft,Yb:pt,Za:mt,Fa:k,eb:ht,Da:St,Tb:Ct,Rb:jt,Ca:Nt,M:Pt,I:Ft,Sb:Rt,ka:Kt,Ub:qt,Ua:Jt,Wb:$t,La:tn,Pb:nn,la:rn,Ta:Zt,bb:an,U:yn,n:En,c:Et,sb:Dn,w:On,L:kn,z:An,j:jn,o:Mn,tb:Nn,G:Pn,T:Fn,h:In,u:Ln,m:Rn,i:zn,Oa:Bn,Pa:Wn,Qa:Gn,Ma:Kn,Na:qn,Qb:Xn,fb:Zn,db:er,Y:rr,rb:ir,ma:ar,cb:Qn,gb:or,ab:sr,Xb:cr,N:Yn,hb:lr,X:ur,Vb:dr,ob:Mr,C:Nr,sa:Pr,ra:Fr,qb:Ir,W:Lr,v:Rr,nb:zr,mb:Br,lb:Vr,pb:Hr,kb:Ur,jb:M,ib:Wr,Va:Jr,Wa:Yr,Ja:Ce,ea:Xr,oa:Zr,Sa:N,na:$r,Db:Fo,xa:Do,Eb:Po,ya:Eo,F:go,e:no,s:eo,x:$a,D:po,Ib:Co,ba:xo,B:ao,za:wo,$:Oo,ha:So,Fb:Mo,Gb:jo,Ba:_o,Aa:bo,Jb:vo,wa:No,aa:To,d:to,A:io,r:ro,Cb:Io,t:so,y:mo,H:oo,E:co,K:ho,S:ko,ja:fo,_:Ao,Kb:uo,Lb:lo,P:yo,g:ei,a:Me,Ob:xe,Hb:ti,ia:ni,O:ri,qa:ii,Mb:ai,Q:oi,zb:si,Ab:ci,ua:li,fa:P,R:ui,Ea:di,va:fi,Z:pi,xb:mi,Zb:hi,V:gi,Bb:_i,ub:vi,vb:bi,wb:xi,ga:Si,yb:Ci,Nb:wi}}}async function pe(){function e(e,n){var r=Xa=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=sn(n),e[t]=r):e[t]=n;return Xa=e,Xa=function(){var e=Xa,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).$b=t(e.$b),e.Cc=n(e.Cc),e.Ec=t(e.Ec),e.rd=(e=>(t,n)=>e(t,n)>>>0)(e.rd),e.wd=t(e.wd),e.xd=n(e.xd),e.Bd=t(e.Bd),e}(),Ee.push(Xa.id),Ti=(e=Xa).$b,Ei=e.ac,t._OrtInit=e.bc,t._OrtGetLastError=e.cc,t._OrtCreateSessionOptions=e.dc,t._OrtAppendExecutionProvider=e.ec,t._OrtAddFreeDimensionOverride=e.fc,t._OrtAddSessionConfigEntry=e.gc,t._OrtReleaseSessionOptions=e.hc,t._OrtCreateSession=e.ic,t._OrtReleaseSession=e.jc,t._OrtGetInputOutputCount=e.kc,t._OrtGetInputOutputMetadata=e.lc,t._OrtFree=e.mc,t._OrtCreateTensor=e.nc,t._OrtGetTensorData=e.oc,t._OrtReleaseTensor=e.pc,t._OrtCreateRunOptions=e.qc,t._OrtAddRunConfigEntry=e.rc,t._OrtReleaseRunOptions=e.sc,t._OrtCreateBinding=e.tc,t._OrtBindInput=e.uc,t._OrtBindOutput=e.vc,t._OrtClearBoundOutputs=e.wc,t._OrtReleaseBinding=e.xc,t._OrtRunWithBinding=e.yc,t._OrtRun=e.zc,t._OrtEndProfiling=e.Ac,Di=t._OrtGetWebGpuDevice=e.Bc,Oi=e.Cc,ki=t._free=e.Dc,Ai=t._malloc=e.Ec,ji=t._wgpuBufferRelease=e.Fc,Mi=t._wgpuCreateInstance=e.Gc,Ni=e.Hc,Pi=e.Ic,Fi=e.Jc,Ii=e.Kc,Li=e.Lc,Ri=e.Pc,zi=e.Zc,Bi=e._c,Vi=e.$c,Hi=e.bd,Ui=e.cd,Wi=e.dd,Gi=e.ed,Ki=e.fd,qi=e.gd,Ji=e.hd,Yi=e.kd,Xi=e.ld,Zi=e.md,Qi=e.nd,$i=e.od,ea=e.pd,ta=e.qd,na=e.rd,F=e.sd,ra=e.td,ia=e.ud,I=e.vd,aa=e.wd,L=e.xd,oa=e.yd,sa=e.zd,ca=e.Ad,la=e.Bd,ua=e.Cd,da=e.Dd,fa=e.Ed,pa=e.Fd,ma=e.Gd,ha=e.Hd,ga=e.Id,_a=e.Jd,va=e.Kd,ya=e.Ld,ba=e.Md,xa=e.Nd,Sa=e.Od,Ca=e.Pd,wa=e.Qd,Ta=e.Rd,Ea=e.Td,Da=e.Ud,Oa=e.Vd,ka=e.Wd,Aa=e.Yd,ja=e.Zd,Ma=e._d,Na=e.$d,Pa=e.ae,Fa=e.be,Ia=e.pe,La=e.qe,Ra=e.re,za=e.se,Ba=e.te,R=e.ue,Va=e.ve,Ha=e.we,Ua=e.xe,Wa=e.ye,Ga=e.ze,Ka=e.Xe,qa=e.Ye,Ja=e.Ze,Ya=e._e,f=n,Xa}var n,r=fe();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,fe()),f):(ce??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`/assets/ort-wasm-simd-threaded.asyncify-BrebZMa_.wasm`,``+self.location.href).href,n=await async function(e){var t=ce;if(!d&&!ee(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return async function(e,t){try{var n=await async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==ce&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e}(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),de(e)}}(t,e)}(r),e(n.instance,n.module))}class me{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var he=e=>{e.terminate(),e.onmessage=()=>{}},ge=[],_e=0,ve=null,ye=e=>{we.length==0&&(je(),Ae(we[0]));var t=we.pop();if(!t)return 6;Te.push(t),De[e.Nc]=t,t.Nc=e.Nc;var n={Oc:`run`,he:e.ge,Wc:e.Wc,Nc:e.Nc};return t.postMessage(n,e.Yc),0},be=0,O=(e,t,...n)=>{var r,i=16*n.length,a=L(),o=aa(i),s=o>>>3;for(r of n)typeof r==`bigint`?((S(),oe)[s++>>>0]=1n,(S(),oe)[s++>>>0]=r):((S(),oe)[s++>>>0]=0n,(S(),ae)[s++>>>0]=r);return e=Zi(e,0,i,o,t),I(a),e};function xe(e){if(i)return O(0,1,e);if(p=e,!(0{if(p=e,i)throw Se(e),`unwind`;xe(e)},we=[],Te=[],Ee=[],De={},Oe=e=>{var t=e.Nc;delete De[t],we.push(e),Te.splice(Te.indexOf(e),1),e.Nc=0,Qi(t)};function ke(){Ee.forEach(e=>e())}var Ae=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Oc,i.Vc&&i.Vc!=Oi()){var a=De[i.Vc];a?a.postMessage(i,i.Yc):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.Vc}, but that thread no longer exists!`)}else r===`checkMailbox`?Qt():r===`spawnThread`?ye(i):r===`cleanupThread`?Yt(()=>{Oe(De[i.ie])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.ce](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({Oc:`load`,de:i,je:Me,ke:f})});function je(){var e=new Worker((()=>{let e=URL;return self.location.href>`file:`&&self.location.href<`file;`?new e(`ort.webgpu.bundle.min.mjs`,self.location.href):new URL(self.location.href)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});we.push(e)}var Me,Ne=(e,t)=>{be=0,e=da(e,t),0-9007199254740992>e||9007199254740992>>=0);return(S(),C)[t.Qc+12>>>0]==0&&(Be(t,!0),Fe--),Ve(t,!1),Pe.push(t),la(e)}var Re=0,ze=()=>{F(0,0);var e=Pe.pop();oa(e.Xc),Re=0};function Be(e,t){t=t?1:0,(S(),C)[e.Qc+12>>>0]=t}function Ve(e,t){t=t?1:0,(S(),C)[e.Qc+13>>>0]=t}class He{constructor(e){this.Xc=e,this.Qc=e-24}}var Ue=e=>{var t=Re;if(!t)return ra(0),0;var n=new He(t);(S(),E)[n.Qc+16>>>2>>>0]=t;var r=(S(),E)[n.Qc+4>>>2>>>0];if(!r)return ra(0),t;for(var i of e){if(i===0||i===r)break;if(ca(i,r,n.Qc+16))return ra(i),t}return ra(r),t};function We(){return Ue([])}function Ge(e){return Ue([e>>>0])}function Ke(e,t,n,r){return Ue([e>>>0,t>>>0,n>>>0,r>>>0])}var qe=()=>{var e=Pe.pop();e||de(`no exception to throw`);var t=e.Xc;throw(S(),C)[e.Qc+13>>>0]==0&&(Pe.push(e),Ve(e,!0),Be(e,!1),Fe++),sa(t),Re=t};function Je(e,t,n){var r=new He(e>>>=0);throw t>>>=0,n>>>=0,(S(),E)[r.Qc+16>>>2>>>0]=0,(S(),E)[r.Qc+4>>>2>>>0]=t,(S(),E)[r.Qc+8>>>2>>>0]=n,sa(e),Fe++,Re=e}var Ye=()=>Fe;function Xe(e,t,n,r){return i?O(2,1,e,t,n,r):Ze(e,t,n,r)}function Ze(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?Xe(e,t,n,r):(e={ge:n,Nc:e,Wc:r,Yc:a},i?(e.Oc=`spawnThread`,postMessage(e,a),0):ye(e))}function Qe(e){throw Re||=e>>>0,Re}var $e=globalThis.TextDecoder&&new TextDecoder,et=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},tt=(e,t=0,n,r)=>{if(16<(n=et(e,t>>>=0,n,r))-t&&e.buffer&&$e)return $e.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},nt=(e,t,n)=>(e>>>=0)?tt((S(),w),e,t,n):``;function rt(e,t,n){return i?O(3,1,e,t,n):0}function it(e,t){if(i)return O(4,1,e,t)}function at(e,t){if(i)return O(5,1,e,t)}function ot(e,t,n){if(i)return O(6,1,e,t,n)}function st(e,t,n){return i?O(7,1,e,t,n):0}function ct(e,t){if(i)return O(8,1,e,t)}function lt(e,t,n){if(i)return O(9,1,e,t,n)}function ut(e,t,n,r){if(i)return O(10,1,e,t,n,r)}function dt(e,t,n,r){if(i)return O(11,1,e,t,n,r)}function ft(e,t,n,r){if(i)return O(12,1,e,t,n,r)}function pt(e){if(i)return O(13,1,e)}function mt(e,t){if(i)return O(14,1,e,t)}function k(e,t,n){if(i)return O(15,1,e,t,n)}var ht=()=>de(``),gt=e=>{e>>>=0;for(var t=``;;){var n=(S(),w)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},_t={},A={},vt={},yt=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function bt(e,t,n={}){return function(e,t,n={}){var r=t.name;if(!e)throw new yt(`type "${r}" must have a positive integer typeid pointer`);if(A.hasOwnProperty(e)){if(n.ee)return;throw new yt(`Cannot register type '${r}' twice`)}A[e]=t,delete vt[e],_t.hasOwnProperty(e)&&(t=_t[e],delete _t[e],t.forEach(e=>e()))}(e,t,n)}var xt=(e,t,n)=>{switch(t){case 1:return n?e=>(S(),C)[e>>>0]:e=>(S(),w)[e>>>0];case 2:return n?e=>(S(),ne)[e>>>1>>>0]:e=>(S(),re)[e>>>1>>>0];case 4:return n?e=>(S(),T)[e>>>2>>>0]:e=>(S(),E)[e>>>2>>>0];case 8:return n?e=>(S(),oe)[e>>>3>>>0]:e=>(S(),se)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function St(e,t,n,r,i){e>>>=0,n>>>=0,t=gt(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}bt(e,{name:t,Mc:a,Sc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Rc:xt(t,n,!r),Tc:null})}function Ct(e,t,n,r){bt(e>>>=0,{name:t=gt(t>>>0),Mc:function(e){return!!e},Sc:function(e,t){return t?n:r},Rc:function(e){return this.Mc((S(),w)[e>>>0])},Tc:null})}var wt=[],Tt=[0,1,,1,null,1,!0,1,!1,1];function Et(e){9<(e>>>=0)&&--Tt[e+1]==0&&(Tt[e]=void 0,wt.push(e))}var Dt=e=>{if(!e)throw new yt(`Cannot use deleted val. handle = ${e}`);return Tt[e]},Ot=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=wt.pop()||Tt.length;return Tt[t]=e,Tt[t+1]=1,t}};function kt(e){return this.Mc((S(),E)[e>>>2>>>0])}var At={name:`emscripten::val`,Mc:e=>{var t=Dt(e);return Et(e),t},Sc:(e,t)=>Ot(t),Rc:kt,Tc:null};function jt(e){return bt(e>>>0,At)}var Mt=(e,t)=>{switch(t){case 4:return function(e){return this.Mc((S(),ie)[e>>>2>>>0])};case 8:return function(e){return this.Mc((S(),ae)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function Nt(e,t,n){n>>>=0,bt(e>>>=0,{name:t=gt(t>>>0),Mc:e=>e,Sc:(e,t)=>t,Rc:Mt(t,n),Tc:null})}function Pt(e,t,n,r,i){e>>>=0,n>>>=0,t=gt(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}bt(e,{name:t,Mc:a,Sc:(e,t)=>t,Rc:xt(t,n,r!==0),Tc:null})}function Ft(e,t,n){function r(e){var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],new i((S(),C).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];bt(e>>>=0,{name:n=gt(n>>>0),Mc:r,Rc:r},{ee:!0})}var It=(e,t,n)=>{var r=(S(),w);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Lt=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function Rt(e,t){bt(e>>>=0,{name:t=gt(t>>>0),Mc(e){var t=(S(),E)[e>>>2>>>0];return t=nt(e+4,t,!0),ki(e),t},Sc(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new yt(`Cannot pass non-string to std::string`);var r=n?Lt(t):t.length,i=Ai(4+r+1),a=i+4;return(S(),E)[i>>>2>>>0]=r,n?It(t,a,r+1):(S(),w).set(t,a>>>0),e!==null&&e.push(ki,i),i},Rc:kt,Tc(e){ki(e)}})}var zt=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,Bt=(e,t,n)=>{if(e>>>=1,16<(t=et((S(),re),e,t/2,n))-e&&zt)return zt.decode((S(),re).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},Vt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(S(),ne)[t>>>1>>>0]=0,t-r},Ht=e=>2*e.length,Ut=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(S(),E)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Wt=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(S(),T)[t>>>2>>>0]=0,t-r},Gt=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=gt(n>>>=0),t===2)var r=Bt,i=Vt,a=Ht;else r=Ut,i=Wt,a=Gt;bt(e,{name:n,Mc:e=>{var n=(S(),E)[e>>>2>>>0];return n=r(e+4,n*t,!0),ki(e),n},Sc:(e,r)=>{if(typeof r!=`string`)throw new yt(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=Ai(4+o+t);return(S(),E)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(ki,s),s},Rc:kt,Tc(e){ki(e)}})}function qt(e,t){bt(e>>>=0,{fe:!0,name:t=gt(t>>>0),Mc:()=>{},Sc:()=>{}})}function Jt(e){Yi(e>>>0,!r,1,!n,131072,!1),ke()}var Yt=e=>{if(!x)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Zt(e){e>>>=0,Xt||(Atomics.waitAsync((S(),T),e>>>2,e).value.then(Qt),e+=128,Atomics.store((S(),T),e>>>2,1))}var Qt=()=>Yt(()=>{var e=Oi();e&&(Zt(e),ta())});function $t(e,t){(e>>>=0)==t>>>0?setTimeout(Qt):i?postMessage({Vc:e,Oc:`checkMailbox`}):(e=De[e])&&e.postMessage({Oc:`checkMailbox`})}var en=[];function tn(e,t,n,r,i){for(t>>>=0,i>>>=0,en.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(S(),oe)[n++>>>0]:(S(),ae)[n++>>>0];en.push(a)}return(t?Qa[t]:Za[e])(...en)}var nn=()=>{be=0};function rn(e){e>>>=0,i?postMessage({Oc:`cleanupThread`,ie:e}):Oe(De[e])}function an(e){}var on=e=>{try{e()}catch(e){de(e)}};function sn(e){var t=(...t)=>{dn.push(e);try{return e(...t)}finally{x||(dn.pop(),ln&&cn===1&&dn.length===0&&(cn=0,be+=1,on(qa),typeof Fibers<`u`&&Fibers.De()))}};return mn.set(e,t),t}var cn=0,ln=null,un=0,dn=[],fn=new Map,pn=new Map,mn=new Map,hn=0,gn=null,_n=[],vn=e=>function(e){if(!x){if(cn===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(un=e,t=!0,n)){cn=2,on(()=>Ja(ln)),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.resume(),e=!1;try{var r=function(){var e=(S(),T)[ln+8>>>2>>>0];return e=pn.get(e),e=mn.get(e),--be,e()}()}catch(t){r=t,e=!0}var i=!1;if(!ln){var a=gn;a&&(gn=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(cn=1,ln=function(){var e=Ai(65548),t=e+12;if((S(),E)[e>>>2>>>0]=t,(S(),E)[e+4>>>2>>>0]=t+65536,t=dn[0],!fn.has(t)){var n=hn++;fn.set(t,n),pn.set(n,t)}return t=fn.get(t),(S(),T)[e+8>>>2>>>0]=t,e}(),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.pause(),on(()=>Ka(ln)))}else cn===2?(cn=0,on(Ya),ki(ln),ln=null,_n.forEach(Yt)):de(`invalid state: ${cn}`);return un}}(t=>{e().then(t)});function yn(e){return e>>>=0,vn(async()=>Ot(await Dt(e)))}var bn=[],xn=e=>{var t=bn.length;return bn.push(e),t},Sn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=A[a];if(o===void 0)throw e=`parameter ${r}`,a=Ti(a),t=gt(a),ki(a),new yt(`${e} has unknown type ${t}`);n[i]=o}return n},Cn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((S(),E)[t>>>2>>>0]=Ot(r)),e},wn={},Tn=e=>{var t=wn[e];return t===void 0?gt(e):t};function En(e,t,n){var[r,...i]=Sn(e,t>>>0);t=r.Sc.bind(r);var a=i.map(e=>e.Rc.bind(e));e--;var o={toValue:Dt};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=Tn,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.fe||(o.toReturnWire=t,o.emval_returnValue=Cn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,xn(Object.defineProperty(n,`name`,{value:s}))}function Dn(e,t){return t>>>=0,(e=Dt(e>>>0))==Dt(t)}function On(e){return(e>>>=0)?(e=Tn(e),Ot(globalThis[e])):Ot(globalThis)}function kn(e){return e=Tn(e>>>0),Ot(t[e])}function An(e,t){return t>>>=0,e=Dt(e>>>0),t=Dt(t),Ot(e[t])}function jn(e){9<(e>>>=0)&&(Tt[e+1]+=1)}function Mn(e,t,n,r,i){return bn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function Nn(e,t,n,r,i){return Mn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function Pn(){return Ot([])}function Fn(e){e=Dt(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function Ln(){return Ot({})}function Rn(e){for(var t=Dt(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}Et(e)}function zn(e,t,n){t>>>=0,n>>>=0,e=Dt(e>>>0),t=Dt(t),n=Dt(n),e[t]=n}function Bn(e,t){e=Ie(e),t>>>=0,e=new Date(1e3*e),(S(),T)[t>>>2>>>0]=e.getUTCSeconds(),(S(),T)[t+4>>>2>>>0]=e.getUTCMinutes(),(S(),T)[t+8>>>2>>>0]=e.getUTCHours(),(S(),T)[t+12>>>2>>>0]=e.getUTCDate(),(S(),T)[t+16>>>2>>>0]=e.getUTCMonth(),(S(),T)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(S(),T)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(S(),T)[t+28>>>2>>>0]=e}var Vn=e=>e%4==0&&(e%100!=0||e%400==0),Hn=[0,31,60,91,121,152,182,213,244,274,305,335],Un=[0,31,59,90,120,151,181,212,243,273,304,334];function Wn(e,t){e=Ie(e),t>>>=0,e=new Date(1e3*e),(S(),T)[t>>>2>>>0]=e.getSeconds(),(S(),T)[t+4>>>2>>>0]=e.getMinutes(),(S(),T)[t+8>>>2>>>0]=e.getHours(),(S(),T)[t+12>>>2>>>0]=e.getDate(),(S(),T)[t+16>>>2>>>0]=e.getMonth(),(S(),T)[t+20>>>2>>>0]=e.getFullYear()-1900,(S(),T)[t+24>>>2>>>0]=e.getDay();var n=(Vn(e.getFullYear())?Hn:Un)[e.getMonth()]+e.getDate()-1|0;(S(),T)[t+28>>>2>>>0]=n,(S(),T)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(S(),T)[t+32>>>2>>>0]=e}function Gn(e){e>>>=0;var t=new Date((S(),T)[e+20>>>2>>>0]+1900,(S(),T)[e+16>>>2>>>0],(S(),T)[e+12>>>2>>>0],(S(),T)[e+8>>>2>>>0],(S(),T)[e+4>>>2>>>0],(S(),T)[e>>>2>>>0],0),n=(S(),T)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(S(),T)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(Vn(t.getFullYear())?Hn:Un)[t.getMonth()]+t.getDate()-1|0,(S(),T)[e+28>>>2>>>0]=n,(S(),T)[e>>>2>>>0]=t.getSeconds(),(S(),T)[e+4>>>2>>>0]=t.getMinutes(),(S(),T)[e+8>>>2>>>0]=t.getHours(),(S(),T)[e+12>>>2>>>0]=t.getDate(),(S(),T)[e+16>>>2>>>0]=t.getMonth(),(S(),T)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Kn(e,t,n,r,a,o,s){return i?O(16,1,e,t,n,r,a,o,s):-52}function qn(e,t,n,r,a,o){if(i)return O(17,1,e,t,n,r,a,o)}var Jn={},Yn=()=>performance.timeOrigin+performance.now();function Xn(e,t){return i?O(18,1,e,t):(Jn[e]&&(clearTimeout(Jn[e].id),delete Jn[e]),t&&(Jn[e]={id:setTimeout(()=>{delete Jn[e],Yt(()=>ea(e,performance.timeOrigin+performance.now()))},t),Ce:t}),0)}function Zn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=new Date().getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(S(),E)[e>>>2>>>0]=60*o,(S(),T)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),$n=1;function er(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!$n)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(S(),oe)[n>>>3>>>0]=BigInt(e),0}var tr=[],nr=(e,t)=>{tr.length=0;for(var n;n=(S(),w)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,tr.push(n==112?(S(),E)[t>>>2>>>0]:n==106?(S(),oe)[t>>>3>>>0]:n==105?(S(),T)[t>>>2>>>0]:(S(),ae)[t>>>3>>>0]),t+=r?8:4}return tr};function rr(e,t,n){return e>>>=0,t=nr(t>>>0,n>>>0),Qa[e](...t)}function ir(e,t,n){return e>>>=0,t=nr(t>>>0,n>>>0),Qa[e](...t)}var ar=()=>{};function or(e,t){return b(nt(e>>>0,t>>>0))}var sr=()=>{throw be+=1,`unwind`};function cr(){return 4294901760}var lr=()=>1,ur=()=>navigator.hardwareConcurrency;function dr(e){e>>>=0;var t=(S(),w).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-Me.buffer.byteLength+65535)/65536|0;try{Me.grow(r),le();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}var fr=e=>{var t=Lt(e)+1,n=aa(t);return It(e,n,t),n},pr=(e,t)=>{(S(),E)[e>>>2>>>0]=t;var n=(S(),E)[e>>>2>>>0];(S(),E)[e+4>>>2>>>0]=(t-n)/4294967296},mr=e=>(S(),E)[e>>>2>>>0]+4294967296*(S(),T)[e+4>>>2>>>0],hr=[],gr=(e,t)=>{hr[e>>>0]=t},_r=[],vr=[],yr=(e,t)=>{vr[e]=new Promise(n=>t.finally(()=>n(e)))},j=e=>{if(e)return hr[e>>>0]},br=(e,t)=>{for(e=(S(),E)[e>>>2>>>0];e;e=(S(),E)[e>>>2>>>0])t[(S(),T)[e+4>>>2>>>0]](e)},xr=(e,t,n)=>{(S(),E)[e>>>2>>>0]=t,(S(),E)[e+4>>>2>>>0]=n},Sr=e=>{var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],nt(t,e)},Cr=e=>{var t=(S(),E)[e>>>2>>>0];return e=(S(),E)[e+4>>>2>>>0],t?nt(t,e):e===0?``:void 0},wr=e=>{var t=Cr(e+4),n=(n=(S(),E)[e+12>>>2>>>0])?j(n):`auto`;if(e+=16){var r=j((S(),E)[e+4>>>2>>>0]),i=(S(),E)[e+16>>>2>>>0],a=(S(),E)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:Cr(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},Tr=(e,t)=>{function n(n,r){n=e[n],(S(),E)[t+r>>>2>>>0]=n}n(`maxTextureDimension1D`,4),n(`maxTextureDimension2D`,8),n(`maxTextureDimension3D`,12),n(`maxTextureArrayLayers`,16),n(`maxBindGroups`,20),n(`maxBindGroupsPlusVertexBuffers`,24),n(`maxBindingsPerBindGroup`,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,36),n(`maxSampledTexturesPerShaderStage`,40),n(`maxSamplersPerShaderStage`,44),n(`maxStorageBuffersPerShaderStage`,48),n(`maxStorageTexturesPerShaderStage`,52),n(`maxUniformBuffersPerShaderStage`,56),n(`minUniformBufferOffsetAlignment`,80),n(`minStorageBufferOffsetAlignment`,84),pr(t+64,e.maxUniformBufferBindingSize),pr(t+72,e.maxStorageBufferBindingSize),n(`maxVertexBuffers`,88),pr(t+96,e.maxBufferSize),n(`maxVertexAttributes`,104),n(`maxVertexBufferArrayStride`,108),n(`maxInterStageShaderVariables`,112),n(`maxColorAttachments`,116),n(`maxColorAttachmentBytesPerSample`,120),n(`maxComputeWorkgroupStorageSize`,124),n(`maxComputeInvocationsPerWorkgroup`,128),n(`maxComputeWorkgroupSizeX`,132),n(`maxComputeWorkgroupSizeY`,136),n(`maxComputeWorkgroupSizeZ`,140),n(`maxComputeWorkgroupsPerDimension`,144),e.Ae!==void 0&&n(`maxImmediateSize`,148)},Er=[,`validation`,`out-of-memory`,`internal`],Dr=[,`compatibility`,`core`],Or={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`},kr=[,`low-power`,`high-performance`],Ar=[,`occlusion`,`timestamp`],jr={undefined:1,unknown:1,destroyed:2};function Mr(e,t,n,r,i,a){t=Ie(t),n=Ie(n),r>>>=0,i>>>=0,a>>>=0;var o=j(e>>>0);if(e={},a){var s=(S(),E)[a+12>>>2>>>0];if(s){var c=(S(),E)[a+16>>>2>>>0];e.requiredFeatures=Array.from((S(),E).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>Or[e])}var l=(S(),E)[a+20>>>2>>>0];if(l){let t=function(e,t,n=!1){t=l+t,(t=(S(),E)[t>>>2>>>0])==4294967295||n&&t==0||(u[e]=t)},n=function(e,t){t=l+t;var n=(S(),E)[t>>>2>>>0],r=(S(),E)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(u[e]=mr(t))};var u={};t(`maxTextureDimension1D`,4),t(`maxTextureDimension2D`,8),t(`maxTextureDimension3D`,12),t(`maxTextureArrayLayers`,16),t(`maxBindGroups`,20),t(`maxBindGroupsPlusVertexBuffers`,24),t(`maxDynamicUniformBuffersPerPipelineLayout`,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,36),t(`maxSampledTexturesPerShaderStage`,40),t(`maxSamplersPerShaderStage`,44),t(`maxStorageBuffersPerShaderStage`,48),t(`maxStorageTexturesPerShaderStage`,52),t(`maxUniformBuffersPerShaderStage`,56),t(`minUniformBufferOffsetAlignment`,80),t(`minStorageBufferOffsetAlignment`,84),n(`maxUniformBufferBindingSize`,64),n(`maxStorageBufferBindingSize`,72),t(`maxVertexBuffers`,88),n(`maxBufferSize`,96),t(`maxVertexAttributes`,104),t(`maxVertexBufferArrayStride`,108),t(`maxInterStageShaderVariables`,112),t(`maxColorAttachments`,116),t(`maxColorAttachmentBytesPerSample`,120),t(`maxComputeWorkgroupStorageSize`,124),t(`maxComputeInvocationsPerWorkgroup`,128),t(`maxComputeWorkgroupSizeX`,132),t(`maxComputeWorkgroupSizeY`,136),t(`maxComputeWorkgroupSizeZ`,140),t(`maxComputeWorkgroupsPerDimension`,144),t(`maxImmediateSize`,148,!0),e.requiredLimits=u}(s=(S(),E)[a+24>>>2>>>0])&&(s={label:Cr(s+4)},e.defaultQueue=s),e.label=Cr(a+4)}be+=1,yr(t,o.requestDevice(e).then(e=>{--be,Yt(()=>{hr[i>>>0]=e.queue,hr[r>>>0]=e,be+=1,yr(n,e.lost.then(t=>{Yt(()=>{e.onuncapturederror=()=>{};var r=L(),i=fr(t.message);Ui(n,jr[t.reason],i),I(r)}),--be})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=L();e=fr(e.error.message),Ji(r,t,e),I(n)},`adapterInfo`in e||(e.adapterInfo=o.info),qi(t,1,r,0)})},e=>{--be,Yt(()=>{var i=L(),a=fr(e.message);qi(t,3,r,a),n&&Ui(n,4,a),I(i)})}))}function Nr(e){var t=j(e>>>=0),n=_r[e];if(n){for(var r=0;r>>=0;var r=j(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=na(16,i.byteLength);return(S(),w).set(new Uint8Array(i),a>>>0),_r[e].push(()=>ki(a)),a}function Fr(e,t,n){n>>>=0;var r=j(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=na(16,i.byteLength);return(S(),w).fill(0,a,i.byteLength),_r[e].push(()=>{new Uint8Array(i).set((S(),w).subarray(a>>>0,a+i.byteLength>>>0)),ki(a)}),a}function Ir(e,t,n,r,i){e>>>=0,t=Ie(t),n=Ie(n),i>>>=0;var a=j(e);_r[e]=[],i==4294967295&&(i=void 0),be+=1,yr(t,a.mapAsync(n,r>>>0,i).then(()=>{--be,Yt(()=>{Wi(t,1,0)})},n=>{--be,Yt(()=>{L();var r=fr(n.message);Wi(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete _r[e]})}))}function Lr(e){var t=j(e>>>=0),n=_r[e];if(n){for(var r=0;r>>0]}function zr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(S(),E)[t+32>>>2>>>0];t={label:Cr(t+4),usage:(S(),E)[t+16>>>2>>>0],size:mr(t+24),mappedAtCreation:r},e=j(e);try{var i=e.createBuffer(t)}catch{return!1}return hr[n>>>0]=i,r&&(_r[n]=[]),!0}function Br(e,t,n,r){e>>>=0,t=Ie(t),r>>>=0,n=wr(n>>>0),e=j(e),be+=1,yr(t,e.createComputePipelineAsync(n).then(e=>{--be,Yt(()=>{hr[r>>>0]=e,Hi(t,1,r,0)})},e=>{--be,Yt(()=>{var n=L(),i=fr(e.message);Hi(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),I(n)})}))}function Vr(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(S(),E)[t>>>2>>>0],i=(S(),T)[r+4>>>2>>>0];t={label:Cr(t+4),code:``},i===2&&(t.code=Sr(r+8)),e=j(e).createShaderModule(t),hr[n>>>0]=e}var Hr=e=>{(e=j(e)).onuncapturederror=null,e.destroy()};function Ur(e,t){t=Ie(t),e=j(e>>>0),be+=1,yr(t,e.popErrorScope().then(e=>{--be,Yt(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=L(),i=e?fr(e.message):0;Gi(t,1,n,i),I(r)})},e=>{--be,Yt(()=>{var n=L(),r=fr(e.message);Gi(t,1,5,r),I(n)})}))}function M(e,t,n,r){if(t=Ie(t),r>>>=0,n>>>=0){var i={featureLevel:Dr[(S(),T)[n+4>>>2>>>0]],powerPreference:kr[(S(),T)[n+8>>>2>>>0]],forceFallbackAdapter:!!(S(),E)[n+12>>>2>>>0]};(e=(S(),E)[n>>>2>>>0])!==0&&(S(),i.Fe=!!(S(),E)[e+8>>>2>>>0])}`gpu`in navigator?(be+=1,yr(t,navigator.gpu.requestAdapter(i).then(e=>{--be,Yt(()=>{if(e)hr[r>>>0]=e,Ki(t,1,r,0);else{var n=L(),i=fr(`WebGPU not available on this browser (requestAdapter returned null)`);Ki(t,3,r,i),I(n)}})},e=>{--be,Yt(()=>{var n=L(),i=fr(e.message);Ki(t,4,r,i),I(n)})}))):(i=L(),e=fr(`WebGPU not available on this browser (navigator.gpu is not available)`),Ki(t,3,r,e),I(i))}function Wr(e,t,n){return e>>>=0,t>>>=0,n>>>=0,vn(async()=>{var r=[];if(n){var i=(S(),T)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!Gr){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in Kr)Kr[e]===void 0?delete t[e]:t[e]=Kr[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Gr=n}return Gr};function Jr(e,t){if(i)return O(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of qr()){var o=t+r;(S(),E)[e+a>>>2>>>0]=o,r+=It(n,o,1/0)+1,a+=4}return 0}function Yr(e,t){if(i)return O(20,1,e,t);e>>>=0,t>>>=0;var n=qr();for(var r of((S(),E)[e>>>2>>>0]=n.length,e=0,n))e+=Lt(r)+1;return(S(),E)[t>>>2>>>0]=e,0}function Xr(e){return i?O(21,1,e):52}function Zr(e,t,n,r){return i?O(22,1,e,t,n,r):52}function N(e,t,n,r){return i?O(23,1,e,t,n,r):70}var Qr=[null,[],[]];function $r(e,t,n,r){if(i)return O(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(S(),E)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=Qr[u];d===0||d===10?((u===1?y:b)(tt(f)),f.length=0):f.push(d)}a+=c}return(S(),E)[r>>>2>>>0]=a,0}function ei(e){return e>>>0}function ti(e,t){return Tr(j(e>>>0).limits,t>>>0),1}function ni(e,t){return j(e>>>0).features.has(Or[t])}function ri(e){return BigInt(j(e>>>0).size)}function ii(e){return BigInt(j(e>>>0).usage)}function ai(e,t){if(e>>>=0,t>>>=0){var n=Cr(t+4);n={label:n,timestampWrites:t=(t=(S(),E)[t+12>>>2>>>0])===0?void 0:{querySet:j((S(),E)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(S(),E)[t+8>>>2>>>0],endOfPassWriteIndex:(S(),E)[t+12>>>2>>>0]}}}return t=j(e),e=Li(0),n=t.beginComputePass(n),hr[e>>>0]=n,e}function oi(e,t,n,r,i,a){n=Ie(n),i=Ie(i),a=Ie(a),j(e>>>0).copyBufferToBuffer(j(t>>>0),n,j(r>>>0),i,a)}function si(e){var t=j(e>>>0);return e=Fi(0),t=t.finish(),hr[e>>>0]=t,e}function ci(e,t,n,r,i,a){a=Ie(a),j(e>>>0).resolveQuerySet(j(t>>>0),n,r,j(i>>>0),a)}function li(e,t,n,r){j(e>>>0).dispatchWorkgroups(t,n,r)}function P(e,t,n){n=Ie(n),j(e>>>0).dispatchWorkgroupsIndirect(j(t>>>0),n)}function ui(e){j(e>>>0).end()}function di(e,t,n,r,i){r>>>=0,i>>>=0,e=j(e>>>0),n=j(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(S(),E),i>>>2,r)}function fi(e,t){j(e>>>0).setPipeline(j(t>>>0))}function pi(e,t,n){j(e>>>0).Ee(j(t>>>0),n)}function mi(e,t){var n=j(e>>>0);return e=Pi(0),t=n.getBindGroupLayout(t),hr[e>>>0]=t,e}function hi(e,t){function n(e){var t=(S(),E)[e+8>>>2>>>0],n=(S(),E)[e+32>>>2>>>0],r=(S(),E)[e+36>>>2>>>0],i=0;return br(e,{327681:e=>{i=(S(),E)[e+8>>>2>>>0]}}),t?((n=mr(e+24))==-1&&(n=void 0),t={buffer:j(t),offset:mr(e+16),size:n}):t=j(n||r||i),{binding:(S(),E)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:Cr(4+(t>>>=0)),layout:j((S(),E)[t+12>>>2>>>0]),entries:function(e,t){for(var r=[],i=0;i>>2>>>0],(S(),E)[t+20>>>2>>>0])},e=j(e);var r=Ni(0);return gr(r,e.createBindGroup(t)),r}function gi(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:Cr(t+4)}),t=j(e),e=Ii(0),n=t.createCommandEncoder(n),hr[e>>>0]=n,e}function _i(e,t){e>>>=0,t>>>=0,t={type:Ar[(S(),T)[t+12>>>2>>>0]],count:(S(),E)[t+16>>>2>>>0]};var n=j(e);return e=Ri(0),t=n.createQuerySet(t),hr[e>>>0]=t,e}function vi(e,t){e=j(e>>>0).adapterInfo,t>>>=0,(S(),E)[t+52>>>2>>>0]=e.subgroupMinSize,(S(),E)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=e.vendor+e.architecture+e.device+e.description,r=Lt(n)+1,i=Ai(r);return i&&It(n,i,r),n=i,r=Lt(e.vendor),xr(t+4,n,r),n+=r,r=Lt(e.architecture),xr(t+12,n,r),n+=r,r=Lt(e.device),xr(t+20,n,r),xr(t+28,n+r,Lt(e.description)),(S(),T)[t+36>>>2>>>0]=2,e=e.isFallbackAdapter?3:4,(S(),T)[t+40>>>2>>>0]=e,(S(),E)[t+44>>>2>>>0]=0,(S(),E)[t+48>>>2>>>0]=0,1}var yi={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function bi(e,t){t>>>=0;var n=j(e>>>0);e=Ai(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=yi[t])&&((S(),T)[e+r>>>2>>>0]=n,r+=4,i++);(S(),E)[t+4>>>2>>>0]=e,(S(),E)[t>>>2>>>0]=i}function xi(e,t){return Tr(j(e>>>0).limits,t>>>0),1}function Si(e,t){j(e>>>0).pushErrorScope(Er[t])}function Ci(e,t,n){t>>>=0,n>>>=0,e=j(e>>>0),t=Array.from((S(),T).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>j(e)),e.submit(t)}function wi(e,t,n,r,i){n=Ie(n),r>>>=0,i>>>=0,e=j(e>>>0),t=j(t>>>0),r=(S(),w).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||function(){for(var e=t.numThreads-1;e--;)je();ge.push(async()=>{var e=async function(){if(!i)return Promise.all(we.map(Ae))}();_e++,await e,--_e==0&&ve&&(e=ve,ve=null,e())})}(),i||(Me=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>L(),t.stackRestore=e=>I(e),t.stackAlloc=e=>aa(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(S(),C)[e>>>0]=t;break;case`i16`:(S(),ne)[e>>>1>>>0]=t;break;case`i32`:(S(),T)[e>>>2>>>0]=t;break;case`i64`:(S(),oe)[e>>>3>>>0]=BigInt(t);break;case`float`:(S(),ie)[e>>>2>>>0]=t;break;case`double`:(S(),ae)[e>>>3>>>0]=t;break;case`*`:(S(),E)[e>>>2>>>0]=t;break;default:de(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(S(),C)[e>>>0];case`i16`:return(S(),ne)[e>>>1>>>0];case`i32`:return(S(),T)[e>>>2>>>0];case`i64`:return(S(),oe)[e>>>3>>>0];case`float`:return(S(),ie)[e>>>2>>>0];case`double`:return(S(),ae)[e>>>3>>>0];case`*`:return(S(),E)[e>>>2>>>0];default:de(`invalid type for getValue: ${t}`)}},t.UTF8ToString=nt,t.stringToUTF8=It,t.lengthBytesUTF8=Lt;var Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,F,ra,ia,I,aa,L,oa,sa,ca,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,R,Va,Ha,Ua,Wa,Ga,Ka,qa,Ja,Ya,Xa,Za=[xe,Se,Xe,rt,it,at,ot,st,ct,lt,ut,dt,ft,pt,mt,k,Kn,qn,Xn,Jr,Yr,Xr,Zr,N,$r],Qa={937076:(e,n,r,i,a)=>{if(t===void 0||!t.Uc)return 1;if((e=nt(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Uc.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(S(),w).set(o,i>>>0);break;case 1:t.ad?t.ad(i,o):t.oe(i,o);break;default:return 4}return 0}catch{return 4}},937900:(e,n,r)=>{t.Sd(e,(S(),w).subarray(n>>>0,n+r>>>0))},937964:()=>t.me(),938006:e=>{t.jd(e)},938043:()=>typeof wasmOffsetConverter<`u`};function $a(e,t,n,r){var i=L();try{return ya(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function eo(e,t,n){var r=L();try{return ga(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;F(1,0)}}function to(e){var t=L();try{fa(e)}catch(e){if(I(t),e!==e+0)throw e;F(1,0)}}function no(e,t){var n=L();try{return da(e,t)}catch(e){if(I(n),e!==e+0)throw e;F(1,0)}}function ro(e,t,n){var r=L();try{ua(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;F(1,0)}}function io(e,t){var n=L();try{ba(e,t)}catch(e){if(I(n),e!==e+0)throw e;F(1,0)}}function ao(e,t,n,r,i,a,o){var s=L();try{return ha(e,t,n,r,i,a,o)}catch(e){if(I(s),e!==e+0)throw e;F(1,0)}}function oo(e,t,n,r,i,a){var o=L();try{pa(e,t,n,r,i,a)}catch(e){if(I(o),e!==e+0)throw e;F(1,0)}}function so(e,t,n,r){var i=L();try{va(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function co(e,t,n,r,i,a,o){var s=L();try{Sa(e,t,n,r,i,a,o)}catch(e){if(I(s),e!==e+0)throw e;F(1,0)}}function lo(e,t,n,r,i,a,o){var s=L();try{Ca(e,t,n,r,i,a,o)}catch(e){if(I(s),e!==e+0)throw e;F(1,0)}}function uo(e,t,n,r,i,a,o,s){var c=L();try{Ma(e,t,n,r,i,a,o,s)}catch(e){if(I(c),e!==e+0)throw e;F(1,0)}}function fo(e,t,n,r,i,a,o,s,c,l,u,d){var f=L();try{wa(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(I(f),e!==e+0)throw e;F(1,0)}}function po(e,t,n,r,i){var a=L();try{return xa(e,t,n,r,i)}catch(e){if(I(a),e!==e+0)throw e;F(1,0)}}function mo(e,t,n,r,i){var a=L();try{ma(e,t,n,r,i)}catch(e){if(I(a),e!==e+0)throw e;F(1,0)}}function ho(e,t,n,r,i,a,o,s){var c=L();try{_a(e,t,n,r,i,a,o,s)}catch(e){if(I(c),e!==e+0)throw e;F(1,0)}}function go(e){var t=L();try{return Na(e)}catch(e){if(I(t),e!==e+0)throw e;F(1,0)}}function _o(e,t,n){var r=L();try{return Pa(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;F(1,0)}}function vo(e,t){var n=L();try{return Ga(e,t)}catch(e){if(I(n),e!==e+0)throw e;return F(1,0),0n}}function yo(e,t,n,r,i){var a=L();try{Fa(e,t,n,r,i)}catch(e){if(I(a),e!==e+0)throw e;F(1,0)}}function bo(e){var t=L();try{return Ta(e)}catch(e){if(I(t),e!==e+0)throw e;return F(1,0),0n}}function xo(e,t,n,r,i,a){var o=L();try{return Aa(e,t,n,r,i,a)}catch(e){if(I(o),e!==e+0)throw e;F(1,0)}}function So(e,t,n,r,i,a){var o=L();try{return Ia(e,t,n,r,i,a)}catch(e){if(I(o),e!==e+0)throw e;F(1,0)}}function Co(e,t,n,r,i,a){var o=L();try{return La(e,t,n,r,i,a)}catch(e){if(I(o),e!==e+0)throw e;F(1,0)}}function wo(e,t,n,r,i,a,o,s){var c=L();try{return ja(e,t,n,r,i,a,o,s)}catch(e){if(I(c),e!==e+0)throw e;F(1,0)}}function To(e,t,n,r,i){var a=L();try{return Ra(e,t,n,r,i)}catch(e){if(I(a),e!==e+0)throw e;return F(1,0),0n}}function Eo(e,t,n,r){var i=L();try{return za(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function Do(e,t,n,r){var i=L();try{return Ba(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function Oo(e,t,n,r,i,a,o,s,c,l,u,d){var f=L();try{return R(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(I(f),e!==e+0)throw e;F(1,0)}}function ko(e,t,n,r,i,a,o,s,c,l,u){var d=L();try{Va(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(I(d),e!==e+0)throw e;F(1,0)}}function Ao(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=L();try{Ha(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(I(g),e!==e+0)throw e;F(1,0)}}function jo(e,t,n,r){var i=L();try{return Ua(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function Mo(e,t,n,r,i){var a=L();try{return Wa(e,t,n,r,i)}catch(e){if(I(a),e!==e+0)throw e;F(1,0)}}function No(e,t,n){var r=L();try{return Da(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;return F(1,0),0n}}function Po(e,t,n){var r=L();try{return Ea(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;F(1,0)}}function Fo(e,t,n){var r=L();try{return Oa(e,t,n)}catch(e){if(I(r),e!==e+0)throw e;F(1,0)}}function Io(e,t,n,r){var i=L();try{ka(e,t,n,r)}catch(e){if(I(i),e!==e+0)throw e;F(1,0)}}function Lo(){if(0<_e)ve=Lo;else if(i)m?.(t),ue();else{for(var e=ge;0{let n=new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=Vi(t);return t=Bi(t,n),hr[n>>>0]=e.queue,hr[t>>>0]=e,t})(e,t=Mi(0));t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=Di(n);o.set(t,i),n===0&&e(r??j(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||de(),t=zi(t),hr[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(ji(t[0]),delete e[s])},t.webgpuGetBuffer=e=>j(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=j(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.ad=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=j(e),!r){var s=Di(i);r=j(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterMLConstant=(e,r,i,a,o,s)=>n.registerMLConstant(e,r,i,a,o,t.Uc,s),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},D?t:new Promise((e,t)=>{m=e,h=t})}var Ue,We,Ge=s(()=>{"use strict";Ue=He,We=globalThis.self?.name?.startsWith(`em-pthread`),We&&He()}),Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at,ot=s(()=>{"use strict";Fe(),Ke=typeof location>`u`?void 0:location.origin,qe=self.location.href>`file:`&&self.location.href<`file;`,Je=()=>qe?new URL(new URL(`ort.webgpu.bundle.min.mjs`,self.location.href).href,Ke).href:self.location.href,Ye=Je(),Xe=()=>{if(Ye&&!Ye.startsWith(`blob:`))return Ye.substring(0,Ye.lastIndexOf(`/`)+1)},Ze=(e,t)=>{try{let n=t??Ye;return(n?new URL(e,n):new URL(e)).origin===Ke}catch{return!1}},Qe=(e,t)=>{let n=t??Ye;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},$e=(e,t)=>`${t??`./`}${e}`,et=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},tt=async e=>(await import(e)).default,nt=(Be(),u(Ie)).default,rt=async()=>{if(!Ye)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Ze(Ye))return[void 0,nt()];let e=await et(Ye);return[e,nt(e)]},it=(Ge(),u(Ve)).default,at=async(e,t,n,r)=>{let i=it&&!(e||t);if(i)if(Ye)i=Ze(Ye)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,it];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??Qe(r,t),a=n&&i&&!Ze(i,t),o=a?await et(i):i??$e(r,t);return[a?o:void 0,await tt(o)]}}}),st,ct,lt,ut,dt,ft,pt,mt,k,ht=s(()=>{"use strict";ot(),ct=!1,lt=!1,ut=!1,dt=()=>{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}},ft=()=>{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}},pt=()=>{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}},mt=async e=>{if(ct)return Promise.resolve();if(lt)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(ut)throw Error(`previous call to 'initializeWebAssembly()' failed.`);lt=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!pt())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!ft())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=dt();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 at(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=Xe();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{lt=!1,ct=!0,st=t,e(),d&&URL.revokeObjectURL(d)},e=>{lt=!1,ut=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},k=()=>{if(ct&&st)return st;throw Error(`WebAssembly is not initialized yet.`)}}),gt,_t,A,vt=s(()=>{"use strict";ht(),gt=(e,t)=>{let n=k(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},_t=(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`)_t(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)}}}),yt,bt=s(()=>{"use strict";ht(),vt(),yt=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=gt(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&&_t(e.extra,``,new WeakSet,(e,i)=>{let a=gt(e,r),o=gt(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}}}),xt,St,Ct,wt,Tt,Et,Dt,Ot=s(()=>{"use strict";ht(),vt(),xt=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}`)}},St=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Ct=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)},wt=(e,t,n,r)=>{let i=gt(t,r),a=gt(n,r);k()._OrtAddSessionConfigEntry(e,i,a)!==0&&A(`Can't set a session config entry: ${t} - ${n}.`)},Tt=(e,t,n,r)=>{let i=gt(t,r),a=gt(n,r);e.push([i,a])},Et=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`,typeof i!=`string`){let t=i?.deviceType;t&&wt(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&&Tt(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Tt(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Tt(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Tt(a,`validationMode`,r.validationMode,n)}let o=k().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Tt(a,`deviceId`,e.toString(),n),Tt(a,`webgpuInstance`,t.toString(),n),Tt(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=gt(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{let t=k(),n=0,r=[],i=e||{};Ct(i);try{let e=xt(i.graphOptimizationLevel??`all`),a=St(i.executionMode??`sequential`),o=typeof i.logId==`string`?gt(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`?gt(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 Et(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);wt(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=gt(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&A(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&_t(i.extra,``,new WeakSet,(e,t)=>{wt(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}}}),kt,At,jt,Mt,Nt,Pt,Ft,It,Lt=s(()=>{"use strict";kt=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}`)}},At=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}`)}},jt=(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},Mt=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Nt=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}`)}},Pt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Ft=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,It=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}`)}}}),Rt,zt=s(()=>{"use strict";Fe(),Rt=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<1073741824)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)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Bt,Vt=s(()=>{"use strict";Lt(),Bt=(e,t)=>new(Mt(t))(e)}),Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt=s(()=>{"use strict";Lt(),Ht=[`V`,`I`,`W`,`E`,`F`],Ut=(e,t)=>{console.log(`[${Ht[e]},${new Date().toISOString()}]${t}`)},Kt=(e,t)=>{Wt=e,Gt=t},qt=(e,t)=>{let n=Nt(e);n>=Nt(Wt)&&Ut(n,typeof t==`function`?t():t)},Jt=(...e)=>{Gt&&qt(...e)}}),Xt,Zt,Qt,$t,en,tn,nn,rn,an,on,sn,cn=s(()=>{"use strict";Lt(),Yt(),Xt=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Zt=(e,t)=>{if(t===`int32`)return e;let n=Xt.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(Mt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||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>2147483647))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'`)}},Qt=(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}`)}},$t=1,en=()=>$t++,tn=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),nn=(e,t)=>{let n=Xt.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},rn=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 nn(this.dataType,this.tensorShape)}destroy(){Jt(`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=Qt(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else 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}},an=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=tn.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Jt(`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!==nn(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=Zt(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Jt(`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?Qt(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},on=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=en();return this.tensorTrackersById.set(e,new an(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){Jt(`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){Jt(`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=en(),o=new rn({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new an(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)){Jt(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Jt(`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 rn({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)}},sn=(...e)=>new on(...e)}),ln={};c(ln,{WebNNBackend:()=>fn});var un,dn,fn,pn=s(()=>{"use strict";Lt(),ht(),Vt(),cn(),Yt(),un=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),dn=(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])},fn=class{constructor(e){this.tensorManager=sn(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Kt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Jt(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Jt(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Jt(`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}}else 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=>dn(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=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){Jt(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=un.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){Jt(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=un.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`);Jt(`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 Bt(n,t)}}registerMLTensor(e,t,n,r){let i=un.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Jt(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=Zt(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return Jt(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}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=un.get(kt(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn=s(()=>{"use strict";Pe(),bt(),Ot(),Lt(),ht(),vt(),zt(),mn=(e,t)=>{k()._OrtInit(e,t)!==0&&A(`Can't initialize onnxruntime.`)},hn=async e=>{mn(e.wasm.numThreads,Nt(e.logLevel))},gn=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(pn(),u(ln)).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])}},_n=new Map,vn=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)}},yn=(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{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]},xn=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]=bn(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Dt(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Rt(typeof n==`string`?n:n.data).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;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=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]=vn(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`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=>It(e))}),_n.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?.()}},Sn=e=>{let t=k(),n=_n.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.`),_n.delete(e)},Cn=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=jt(kt(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=jt(kt(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,kt(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;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(kt(l),p,m,g,u.length,It(f));e===0&&A(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},wn=async(e,t,n,r,i,a)=>{let o=k(),s=o.PTR_SIZE,c=_n.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=[],ee=[],S=o.stackSave(),te=o.stackAlloc(h*s),C=o.stackAlloc(h*s),w=o.stackAlloc(g*s),ne=o.stackAlloc(g*s);try{[_,v]=yt(a),Se(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=At(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;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=jt(a,g);if(i===void 0||!Pt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);S.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Mt(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(jt(a,g)===void 0||!Ft(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,S.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=S.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),S.push([u,h,[],`cpu`])}else{let e=new(Mt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),S.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.`),_n.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))S[e][2]=t;return Ce(`wasm ProcessOutputTensor`),S}finally{o.webnnOnRunEnd?.(l),o.stackRestore(S),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))}},Tn=e=>{let t=k(),n=_n.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)},En=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn=s(()=>{"use strict";Pe(),Dn(),ht(),ot(),On=()=>!!S.wasm.proxy&&typeof document<`u`,An=!1,jn=!1,Mn=!1,Fn=new Map,In=(e,t)=>{let n=Fn.get(e);n?n.push(t):Fn.set(e,[t])},Ln=()=>{if(An||!jn||Mn||!kn)throw Error(`worker not ready`)},Rn=e=>{switch(e.data.type){case`init-wasm`:An=!1,e.data.err?(Mn=!0,Pn[1](e.data.err)):(jn=!0,Pn[0]()),Nn&&=(URL.revokeObjectURL(Nn),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Fn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},zn=async()=>{if(!jn){if(An)throw Error(`multiple calls to 'initWasm()' detected.`);if(Mn)throw Error(`previous call to 'initWasm()' failed.`);if(An=!0,On())return new Promise((e,t)=>{kn?.terminate(),rt().then(([n,r])=>{try{kn=r,kn.onerror=e=>t(e),kn.onmessage=Rn,Pn=[e,t];let i={type:`init-wasm`,in:S};!i.in.wasm.wasmPaths&&(n||qe)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.asyncify-BrebZMa_.wasm`,``+self.location.href).href}),kn.postMessage(i),Nn=n}catch(e){t(e)}},t)});try{await mt(S.wasm),await hn(S),jn=!0}catch(e){throw Mn=!0,e}finally{An=!1}}},Bn=async e=>{if(On())return Ln(),new Promise((t,n)=>{In(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:S}};kn.postMessage(r)});await gn(S,e)},Vn=async e=>On()?(Ln(),new Promise((t,n)=>{In(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};kn.postMessage(r,[e.buffer])})):bn(e),Hn=async(e,t)=>{if(On()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Ln(),new Promise((n,r)=>{In(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),kn.postMessage(i,a)})}else return xn(e,t)},Un=async e=>{if(On())return Ln(),new Promise((t,n)=>{In(`release`,[t,n]);let r={type:`release`,in:e};kn.postMessage(r)});Sn(e)},Wn=async(e,t,n,r,i,a)=>{if(On()){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 Ln(),new Promise((i,o)=>{In(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};kn.postMessage(c,En(s))})}else return wn(e,t,n,r,i,a)},Gn=async e=>{if(On())return Ln(),new Promise((t,n)=>{In(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};kn.postMessage(r)});Tn(e)}}),qn,Jn,Yn,Xn=s(()=>{"use strict";Pe(),Kn(),Lt(),Fe(),zt(),qn=(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()}`)}},Jn=e=>{switch(e[3]){case`cpu`:return new _e(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Pt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return _e.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Ft(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return _e.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Yn=class{async fetchModelAndCopyToWasmMemory(e){return Vn(await Rt(e))}async loadModel(e,t){O();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Hn(n,t),xe()}async dispose(){return Un(this.sessionId)}async run(e,t,n){O();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)=>qn(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?qn(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Wn(this.sessionId,i,s,o,c,n),u={};for(let e=0;e$n,initializeFlags:()=>Qn,wasmBackend:()=>er});var Qn,$n,er,tr=s(()=>{"use strict";Pe(),Kn(),Xn(),Qn=()=>{(typeof S.wasm.initTimeout!=`number`||S.wasm.initTimeout<0)&&(S.wasm.initTimeout=0);let e=S.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.`),S.wasm.simd=!1),typeof S.wasm.proxy!=`boolean`&&(S.wasm.proxy=!1),typeof S.wasm.trace!=`boolean`&&(S.wasm.trace=!1),typeof S.wasm.numThreads!=`number`||!Number.isInteger(S.wasm.numThreads)||S.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)S.wasm.numThreads=1;else{let e=typeof navigator>`u`?o(`node:os`).cpus().length:navigator.hardwareConcurrency;S.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},$n=class{async init(e){Qn(),await zn(),await Bn(e)}async createInferenceSessionHandler(e,t){let n=new Yn;return await n.loadModel(e,t),n}},er=new $n});Pe(),Pe(),Pe();var nr=`1.25.0-dev.20260327-722743c0e2`,rr=Ne;{let e=(tr(),u(Zn)).wasmBackend;p(`webgpu`,e,5),p(`webnn`,e,5),p(`cpu`,e,10),p(`wasm`,e,10)}Object.defineProperty(S.versions,`web`,{value:nr,enumerable:!0});let ir=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:`1.24.3`},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}`);ir=e}},get logLevel(){return ir}},`logLevel`,{enumerable:!0});let ar=(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{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{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{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,sr(o,s)}else 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(sr(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return sr(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},lr=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new yr({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ur=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new yr({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},dr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new yr({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},fr=(e,t,n)=>new yr({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),pr=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),mr=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),hr=!1,gr=()=>{if(!hr){hr=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(pr.set(`int64`,BigInt64Array),mr.set(BigInt64Array,`int64`)),t&&(pr.set(`uint64`,BigUint64Array),mr.set(BigUint64Array,`uint64`)),r?(pr.set(`float16`,n),mr.set(n,`float16`)):pr.set(`float16`,Uint16Array)}},_r=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new yr(e.type,e.data,t);case`cpu-pinned`:return new yr({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new yr({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new yr({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new yr({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var yr=class{constructor(e,t,n){gr();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=pr.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=pr.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=mr.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=_r(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 cr(e,t)}static fromTexture(e,t){return lr(e,t)}static fromGpuBuffer(e,t){return ur(e,t)}static fromMLTensor(e,t){return dr(e,t)}static fromPinnedBuffer(e,t,n){return fr(e,t,n)}toDataURL(e){return ar(this,e)}toImageData(e){return or(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 vr(this,e)}};let j=yr;var br={url:self.location.href},xr=Object.defineProperty,Sr=(e,t)=>{for(var n in t)xr(e,n,{get:t[n],enumerable:!0})},Cr={},wr={},Tr={},Er=`4.0.1`,Dr=typeof self<`u`,Or=!Qr(Cr),kr=!Qr(wr),Ar=Dr&&`caches`in self,jr=globalThis.Deno!==void 0;globalThis.Bun;var Mr=jr&&Ar&&!Or,Nr=typeof process<`u`,Pr=Nr&&process?.release?.name===`node`&&!Mr,Fr=typeof window<`u`&&window.document!==void 0,Ir=Dr&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),Lr=Fr||Ir||Mr,Rr=Pr||typeof navigator<`u`&&`gpu`in navigator,zr=typeof navigator<`u`&&`ml`in navigator,Br=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,Vr=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Hr=typeof ServiceWorkerGlobalScope<`u`&&Dr&&self instanceof ServiceWorkerGlobalScope,Ur=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent,t=(navigator.vendor||``).indexOf(`Apple`)>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`);return t&&n})(),M=Object.freeze({IS_BROWSER_ENV:Fr,IS_WEBWORKER_ENV:Ir,IS_WEB_ENV:Lr,IS_SERVICE_WORKER_ENV:Hr,IS_DENO_WEB_RUNTIME:Mr,IS_WEB_CACHE_AVAILABLE:Ar,IS_WEBGPU_AVAILABLE:Rr,IS_WEBNN_AVAILABLE:zr,IS_SAFARI:Ur,IS_PROCESS_AVAILABLE:Nr,IS_NODE_ENV:Pr,IS_FS_AVAILABLE:Or,IS_PATH_AVAILABLE:kr,IS_CRYPTO_AVAILABLE:Br,IS_CHROME_AVAILABLE:Vr}),Wr=Or&&kr,Gr=`./`;if(Wr){let e=Object(br).url;e?Gr=wr.dirname(wr.dirname(Tr.fileURLToPath(e))):typeof __dirname<`u`&&(Gr=wr.dirname(__dirname))}var Kr=Wr?wr.join(Gr,`/.cache/`):null,qr=`/models/`,Jr=Wr?wr.join(Gr,qr):qr,Yr=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Xr=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Zr=Xr.WARNING,N={version:Er,backends:{onnx:{}},get logLevel(){return Zr},set logLevel(e){Zr=e,N.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Fr||Ir||Mr),localModelPath:Jr,useFS:Or,useBrowserCache:Ar,useFSCache:Or,cacheDir:Kr,useCustomCache:!1,customCache:null,useWasmCache:Ar||Or,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Yr};function Qr(e){return Object.keys(e).length===0}var $r=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 ei(e,t){e&&e(t)}var ti=class extends $r{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};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 ni(e){return Number.isInteger(e)||typeof e==`bigint`}function ri(e){return e==null||e===-1}function ii(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function ai(...e){return Array.prototype.concat.apply([],e)}function oi(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function si(e,t){return Math.abs((e+t)%(2*t)-t)}function ci(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function li(e,t){let n=0;for(let r of e)r===t&&++n;return n}var P={error(...e){N.logLevel<=Xr.ERROR&&console.error(...e)},warn(...e){N.logLevel<=Xr.WARNING&&console.warn(...e)},info(...e){N.logLevel<=Xr.INFO&&console.log(...e)},debug(...e){N.logLevel<=Xr.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},ui=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let n of e){let e=t;for(let t=0;tr&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r{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]]))})(),pi=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(fi),mi=`.,!?…。,、।۔،`,hi=new Map([[`(?i:'s|'t|'re|'ve|'m|'ll|'d)`,`(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))`],[`(?i:[sdmt]|ll|ve|re)`,`(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`],[`[^\\r\\n\\p{L}\\p{N}]?+`,`[^\\r\\n\\p{L}\\p{N}]?`],[`[^\\s\\p{L}\\p{N}]++`,`[^\\s\\p{L}\\p{N}]+`],[`(?>\\p{Nd}{510})`,`(?:\\p{Nd}{510})`],[`\\p{Nd}{3}+`,`(?:\\p{Nd}{3})+`],[`\\G`,``],[` ?[^(\\s|[${mi}])]+`,` ?[^\\s${mi}]+`]]),gi=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,_i=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`),vi=(e,t=!0)=>{if(e.Regex!==void 0){let t=e.Regex.replace(/\\([#&~])/g,`$1`);t=t.replace(/\\A/g,`^`).replace(/\\z/g,`$`).replace(/\\Z/g,`(?=\\r?\\n?$)`);for(let[e,n]of hi)t=t.replaceAll(e,n);try{return new RegExp(t,`gu`)}catch(e){if(!(e instanceof SyntaxError)||!e.message.toLowerCase().includes(`invalid property name`))throw e;let n=!1,r=t.replace(/(\\[pP])\{([^}=]+)\}/g,(e,t,r)=>{try{return RegExp(`\\p{${r}}`,`u`),`${t}{${r}}`}catch{return n=!0,`${t}{Script=${r}}`}});if(!n)throw e;try{return new RegExp(r,`gu`)}catch{throw e}}}else if(e.String!==void 0){let n=yi(e.String);return new RegExp(t?n:`(${n})`,`gu`)}else return console.warn(`Unknown pattern type:`,e),null},yi=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),bi=(e,t,n)=>{let r=[],i=0;for(;ie>=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,Si=e=>Number.isInteger(e)||typeof e==`bigint`,Ci=e=>{let t=0;for(let n of e)++t;return t},wi=e=>Oi(e.toLowerCase()),Ti=(...e)=>Array.prototype.concat.apply([],e),Ei=e=>new Map(Object.entries(e)),Di=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r0&&n.push(t),r=i.index+t.length}return re.replace(/\p{M}/gu,``),ki=(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},Ai=e=>e.match(/\S+/g)||[],ji=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Mi=class extends ji{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},Ni=class extends Mi{tokenize_chinese_chars(e){let t=[];for(let n=0;ne.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},Fi=class extends Mi{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>qi(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},Ii=class extends Mi{normalize(e){let t=vi(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??``)}},Li=class extends Mi{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},Ri=class extends Li{constructor(){super(...arguments),this.form=`NFC`}},zi=class extends Li{constructor(){super(...arguments),this.form=`NFD`}},Bi=class extends Li{constructor(){super(...arguments),this.form=`NFKC`}},Vi=class extends Li{constructor(){super(...arguments),this.form=`NFKD`}},Hi=class extends Mi{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}},Ui=class extends Mi{normalize(e){return Oi(e)}},Wi=class extends Mi{normalize(e){return e.toLowerCase()}},Gi=class extends Mi{normalize(e){return e=this.config.prepend+e,e}};function Ki(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new Ni(e);case`Precompiled`:return new Pi(e);case`Sequence`:return new Fi(e);case`Replace`:return new Ii(e);case`NFC`:return new Ri(e);case`NFD`:return new zi(e);case`NFKC`:return new Bi(e);case`NFKD`:return new Vi(e);case`Strip`:return new Hi(e);case`StripAccents`:return new Ui(e);case`Lowercase`:return new Wi(e);case`Prepend`:return new Gi(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var qi=Ki,Ji=class extends ji{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)}},Yi=class extends Ji{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=fi,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(``))}},Xi=class extends Ji{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Zi=class extends Ji{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]}},Qi=class extends Ji{constructor(e){super(),this.config=e,this.pattern=vi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):Di(e,this.pattern)}},$i=class extends Ji{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${gi}]+|[${gi}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},ea=class extends Ji{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)||[]}},ta=class extends Ji{constructor(){super(),this.pattern=RegExp(`[^\\s${gi}]+|[${gi}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},na=class extends Ji{constructor(e){super(),this.config=e,this.pattern=vi(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},F=class extends Ji{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>aa(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},ra=class extends Ji{pre_tokenize_text(e){return Ai(e)}},ia=class extends Ji{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;nthis.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i0&&(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}},sa=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},ca=class{constructor(){this.root=sa.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=sa.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let n=``;for(let r of e){if(n+=r,t=t.children.get(r),t===void 0)return;t.is_leaf&&(yield n)}}},la=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}},ua=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 la(this.bos_token_id??0,0,0,0,0),i=new la(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=this.nodes.length,a=new la(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let 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 da(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r[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=da(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new ca,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;ne>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.size0&&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.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},ha=class extends L{constructor(e){super(e),this.tokens_to_ids=Ei(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;this.merges=Array.isArray(e.merges[0])?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 ma(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 pa((e,t)=>e.score`<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}},ga=class extends L{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=Ei(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 _a(e,t){switch(e.type){case`WordPiece`:return new oa(e);case`Unigram`:return new fa(e,t.eos_token);case`BPE`:return new ha(e);default:if(e.vocab)return Array.isArray(e.vocab)?new fa(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new ha(e):new oa(e):new ga(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 va=_a,ya=class extends ji{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ba=class extends ya{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=Ti(i,e),a=Ti(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=Ti(i,t),a=Ti(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},xa=class extends ya{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Sa=class extends ya{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=Ti([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=Ti(e,i,t,a),r=Ti(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},Ca=class extends ya{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=Ti([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=Ti(e,i,t,a),r=Ti(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},wa=class extends ya{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>Ea(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 Ta(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new ba(e);case`ByteLevel`:return new xa(e);case`BertProcessing`:return new Sa(e);case`RobertaProcessing`:return new Ca(e);case`Sequence`:return new wa(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var Ea=Ta,Da=class extends ji{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},Oa=class extends Da{constructor(e){super(e),this.byte_decoder=pi,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}},ka=class extends Da{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=_i(e)),e})}},Aa=class extends Da{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;nt.replaceAll(this.suffix,n===e.length-1?``:` `))}},Ma=class extends Da{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;ne!==this.pad_token).join(``);return this.cleanup&&(n=_i(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Na=class extends Da{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>za(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},Pa=class extends Da{decode_chain(e){let t=vi(this.config.pattern),n=this.config.content??``;return t===null?e:e.map(e=>e.replaceAll(t,n))}},Fa=class extends Da{decode_chain(e){return[e.join(``)]}},Ia=class extends Da{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`)){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 Ra(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new Oa(e);case`WordPiece`:return new ka(e);case`Metaspace`:return new Aa(e);case`BPEDecoder`:return new ja(e);case`CTC`:return new Ma(e);case`Sequence`:return new Na(e);case`Replace`:return new Pa(e);case`Fuse`:return new Fa(e);case`Strip`:return new Ia(e);case`ByteFallback`:return new La(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var za=Ra,Ba=class{constructor(e,t){let n=ki(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=ki(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=qi(this.tokenizer.normalizer),this.pre_tokenizer=aa(this.tokenizer.pre_tokenizer),this.model=va(this.tokenizer.model,this.config),this.post_processor=Ea(this.tokenizer.post_processor),this.decoder=za(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=new Map;for(let e of this.tokenizer.added_tokens){let t=new di(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 ui(i),this.splitter_normalized=new ui(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||!Si(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=_i(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{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=wi(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{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:Ti(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=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let n=0;n=`,R.ComparisonBinaryOperator],[`==`,R.ComparisonBinaryOperator],[`!=`,R.ComparisonBinaryOperator],[`<`,R.ComparisonBinaryOperator],[`>`,R.ComparisonBinaryOperator],[`+`,R.AdditiveBinaryOperator],[`-`,R.AdditiveBinaryOperator],[`~`,R.AdditiveBinaryOperator],[`*`,R.MultiplicativeBinaryOperator],[`/`,R.MultiplicativeBinaryOperator],[`%`,R.MultiplicativeBinaryOperator],[`=`,R.Equals]],Ka=new Map([[`n`,` +`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function qa(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/{%\s*(end)?generation\s*%}/gs,``)}function Ja(e,t={}){let n=[],r=qa(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=Ka.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n;continue}if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`)}return t},s=()=>{let e=n.at(-1);e&&e.type===R.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i0){n.push(new Va(e,R.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 Va(t,R.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new Va(`{%`,R.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new Va(`{{`,R.OpenExpression)),a=0,i+=3;continue}if(o(Wa),r.slice(i,i+3)===`-%}`){n.push(new Va(`%}`,R.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new Va(`}}`,R.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===R.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case R.Identifier:case R.NumericLiteral:case R.StringLiteral:case R.CloseParen:case R.CloseSquareBracket:break;default:{++i;let e=o(Ua);n.push(new Va(`${t}${e}`,e.length>0?R.NumericLiteral:R.UnaryOperator));continue}}}for(let[e,t]of Ga)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new Va(e,t)),t===R.OpenExpression?a=0:t===R.OpenCurlyBracket?++a:t===R.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new Va(e,R.StringLiteral)),++i;continue}if(Ua(t)){let e=o(Ua);if(r[i]===`.`&&Ua(r[i+1])){++i;let t=o(Ua);e=`${e}.${t}`}n.push(new Va(e,R.NumericLiteral));continue}if(Ha(t)){let e=o(Ha);n.push(new Va(e,R.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return n}var Ya=class{type=`Statement`},Xa=class extends Ya{constructor(e){super(),this.body=e}type=`Program`},Za=class extends Ya{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},Qa=class extends Ya{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},$a=class extends Ya{type=`Break`},eo=class extends Ya{type=`Continue`},to=class extends Ya{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},no=class extends Ya{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},ro=class extends Ya{constructor(e){super(),this.value=e}type=`Comment`},io=class extends Ya{type=`Expression`},ao=class extends io{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},oo=class extends io{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},so=class extends io{constructor(e){super(),this.value=e}type=`Identifier`},co=class extends io{constructor(e){super(),this.value=e}type=`Literal`},lo=class extends co{type=`IntegerLiteral`},uo=class extends co{type=`FloatLiteral`},fo=class extends co{type=`StringLiteral`},po=class extends co{type=`ArrayLiteral`},mo=class extends co{type=`TupleLiteral`},ho=class extends co{type=`ObjectLiteral`},go=class extends io{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},_o=class extends io{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},vo=class extends Ya{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},yo=class extends io{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},bo=class extends io{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},xo=class extends io{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},So=class extends io{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},Co=class extends io{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},wo=class extends io{constructor(e){super(),this.argument=e}type=`SpreadExpression`},To=class extends Ya{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},Eo=class extends io{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function Do(e){let t=new Xa([]),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 R.Comment:return new ro(e[n++].value);case R.Text:return l();case R.OpenStatement:return u();case R.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===R.OpenStatement&&e[n+1]?.type===R.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 fo(r(R.Text,`Expected text token`).value)}function u(){if(r(R.OpenStatement,`Expected opening statement token`),e[n].type!==R.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(R.OpenStatement,`Expected {% token`),i(`endif`),r(R.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(R.OpenStatement,`Expected {% token`),i(`endmacro`),r(R.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(R.OpenStatement,`Expected {% token`),i(`endfor`),r(R.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(R.OpenParen)&&(e=w());let t=oe();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=w();r(R.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(R.OpenStatement,`Expected '{%'`),i(`endcall`),r(R.CloseStatement,`Expected closing statement token`),c=new To(new oo(t,l),e,u);break}case`break`:++n,r(R.CloseStatement,`Expected closing statement token`),c=new $a;break;case`continue`:++n,r(R.CloseStatement,`Expected closing statement token`),c=new eo;break;case`filter`:{++n;let e=oe();e instanceof so&&o(R.OpenParen)&&(e=C(e)),r(R.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(R.OpenStatement,`Expected '{%'`),i(`endfilter`),r(R.CloseStatement,`Expected '%}'`),c=new vo(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(R.OpenExpression,`Expected opening expression token`);let e=_();return r(R.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(R.Equals))++n,t=h();else{for(r(R.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(R.OpenStatement,`Expected {% token`),i(`endset`)}return r(R.CloseStatement,`Expected closing statement token`),new to(e,t,c)}function p(){let e=_();r(R.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(R.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new Za(e,t,i)}function m(){let e=oe();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=w();r(R.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new no(e,t,n)}function h(e=!1){let t=e?oe:_,r=[t()],i=o(R.Comma);for(;i&&(++n,r.push(t()),o(R.Comma)););return i?new mo(r):r[0]}function g(){let e=h(!0);if(!(e instanceof so||e instanceof mo))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(R.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(R.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new Qa(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new Eo(t,e,v())):new yo(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new go(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new go(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new xo(r,x())}return t??ee()}function ee(){let t=S();for(;;){let r;if(c(`not`,`in`))r=new Va(`not in`,R.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(R.ComparisonBinaryOperator))r=e[n++];else break;let i=S();t=new go(r,t,i)}return t}function S(){let t=E();for(;o(R.AdditiveBinaryOperator);){let r=e[n];++n;let i=E();t=new go(r,t,i)}return t}function te(){let e=T(oe());return o(R.OpenParen)?C(e):e}function C(e){let t=new oo(e,w());return t=T(t),o(R.OpenParen)&&(t=C(t)),t}function w(){r(R.OpenParen,`Expected opening parenthesis for arguments list`);let e=ne();return r(R.CloseParen,`Expected closing parenthesis for arguments list`),e}function ne(){let t=[];for(;!o(R.CloseParen);){let r;if(e[n].type===R.MultiplicativeBinaryOperator&&e[n].value===`*`)++n,r=new wo(_());else if(r=_(),o(R.Equals)){if(++n,!(r instanceof so))throw SyntaxError(`Expected identifier for keyword argument`);let e=_();r=new Co(r,e)}t.push(r),o(R.Comma)&&++n}return t}function re(){let e=[],t=!1;for(;!o(R.CloseSquareBracket);)o(R.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(R.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 So(...e)}return e[0]}function T(t){for(;o(R.Dot)||o(R.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===R.OpenSquareBracket;if(o)a=re(),r(R.CloseSquareBracket,`Expected closing square bracket`);else if(a=oe(),a.type!==`Identifier`)throw SyntaxError(`Expected identifier following dot operator`);t=new ao(t,a,o)}return t}function E(){let t=ie();for(;o(R.MultiplicativeBinaryOperator);){let r=e[n++],i=ie();t=new go(r,t,i)}return t}function ie(){let e=ae();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=oe();if(!(r instanceof so))throw SyntaxError(`Expected identifier for the test`);e=new bo(e,t,r)}return e}function ae(){let e=te();for(;o(R.Pipe);){++n;let t=oe();if(!(t instanceof so))throw SyntaxError(`Expected identifier for the filter`);o(R.OpenParen)&&(t=C(t)),e=new _o(e,t)}return e}function oe(){let t=e[n++];switch(t.type){case R.NumericLiteral:{let e=t.value;return e.includes(`.`)?new uo(Number(e)):new lo(Number(e))}case R.StringLiteral:{let r=t.value;for(;o(R.StringLiteral);)r+=e[n++].value;return new fo(r)}case R.Identifier:return new so(t.value);case R.OpenParen:{let e=h();return r(R.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case R.OpenSquareBracket:{let e=[];for(;!o(R.CloseSquareBracket);)e.push(_()),o(R.Comma)&&++n;return++n,new po(e)}case R.OpenCurlyBracket:{let e=new Map;for(;!o(R.CloseCurlyBracket);){let t=_();r(R.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(R.Comma)&&++n}return++n,new ho(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n0)for(let i=e;it;i+=n)r.push(i);return r}function ko(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*oe.toUpperCase())}function jo(e){return Mo(new Date,e)}function Mo(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 No(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Po(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(No(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var Fo=class extends Error{},Io=class extends Error{},Lo=class{type=`RuntimeValue`;value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new V(!!this.value)}toString(){return String(this.value)}},z=class extends Lo{type=`IntegerValue`},Ro=class extends Lo{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},B=class extends Lo{type=`StringValue`;builtins=new Map([[`upper`,new Go(()=>new B(this.value.toUpperCase()))],[`lower`,new Go(()=>new B(this.value.toLowerCase()))],[`strip`,new Go(()=>new B(this.value.trim()))],[`title`,new Go(()=>new B(Ao(this.value)))],[`capitalize`,new Go(()=>new B(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new z(this.value.length)],[`rstrip`,new Go(()=>new B(this.value.trimEnd()))],[`lstrip`,new Go(()=>new B(this.value.trimStart()))],[`startswith`,new Go(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof B)return new V(this.value.startsWith(t.value));if(t instanceof H){for(let e of t.value){if(!(e instanceof B))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new V(!0)}return new V(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new Go(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof B)return new V(this.value.endsWith(t.value));if(t instanceof H){for(let e of t.value){if(!(e instanceof B))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new V(!0)}return new V(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new Go(e=>{let t=e[0]??new Ko;if(!(t instanceof B||t instanceof Ko))throw Error(`sep argument must be a string or null`);let n=e[1]??new z(-1);if(!(n instanceof z))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof Ko){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 H(r.map(e=>new B(e)))})],[`replace`,new Go(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof B&&n instanceof B))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new Ko:e[2]:new Ko,!(r instanceof z||r instanceof Ko))throw Error(`replace() count argument must be a number or null`);return new B(Po(this.value,t.value,n.value,r.value))})]])},V=class extends Lo{type=`BooleanValue`},zo=/[\x7f-\uffff]/g;function Bo(e){return e.replace(zo,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function Vo(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=Bo(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=` +`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>Vo(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{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=Bo(s));let c=`${s}${l}${Vo(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 Ho=class extends Lo{type=`ObjectValue`;__bool__(){return new V(this.value.size>0)}builtins=new Map([[`get`,new Go(([e,t])=>{if(!(e instanceof B))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Ko})],[`items`,new Go(()=>this.items())],[`keys`,new Go(()=>this.keys())],[`values`,new Go(()=>this.values())],[`dictsort`,new Go(e=>{let t=new Map,n=e.filter(e=>e instanceof Uo?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new V(!1);if(!(r instanceof V))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new B(`key`);if(!(i instanceof B))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 V(!1);if(!(a instanceof V))throw Error(`reverse must be a boolean`);return new H(Array.from(this.value.entries()).map(([e,t])=>new H([new B(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=Zo(o,s,r.value);return a.value?-c:c}))})]]);items(){return new H(Array.from(this.value.entries()).map(([e,t])=>new H([new B(e),t])))}keys(){return new H(Array.from(this.value.keys()).map(e=>new B(e)))}values(){return new H(Array.from(this.value.values()))}toString(){return Vo(this,{},0,!1)}},Uo=class extends Ho{type=`KeywordArgumentsValue`},H=class extends Lo{type=`ArrayValue`;builtins=new Map([[`length`,new z(this.value.length)]]);__bool__(){return new V(this.value.length>0)}toString(){return Vo(this,{},0,!1)}},Wo=class extends H{type=`TupleValue`},Go=class extends Lo{type=`FunctionValue`},Ko=class extends Lo{type=`NullValue`},qo=class extends Lo{type=`UndefinedValue`},Jo=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new Go(e=>{if(e.length===0)return new Ho(new Map);if(e.length!==1||!(e[0]instanceof Ho))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof Go],[`odd`,e=>{if(!(e instanceof z))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof z))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 z||e instanceof Ro],[`integer`,e=>e instanceof z],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof Ho],[`sequence`,e=>e instanceof H||e instanceof Ho||e instanceof B],[`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]]);set(e,t){return this.declareVariable(e,$o(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 qo}catch{return new qo}}};function Yo(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,Oo),e.set(`strftime_now`,jo),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function Xo(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r instanceof Ho)r=r.value.get(e)??new qo;else if(r instanceof H){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&te instanceof z||e instanceof Ro||e instanceof V,i=e=>e instanceof V?e.value?1:0:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return nr?1:0}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),ri?1:0}default:throw Error(`Cannot compare type: ${e.type}`)}}var Qo=class{global;constructor(e){this.global=e??new Jo}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 V(n.value==r.value);case`!=`:return new V(n.value!=r.value)}if(n instanceof qo||r instanceof qo){if(r instanceof qo&&[`in`,`not in`].includes(e.operator.value))return new V(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else if(n instanceof Ko||r instanceof Ko)throw Error(`Cannot perform operation on null values`);else if(e.operator.value===`~`)return new B(n.value.toString()+r.value.toString());else if((n instanceof z||n instanceof Ro)&&(r instanceof z||r instanceof Ro)){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 Ro||r instanceof Ro?new Ro(a):new z(a)}case`/`:return new Ro(t/i);case`%`:{let e=t%i;return n instanceof Ro||r instanceof Ro?new Ro(e):new z(e)}case`<`:return new V(t`:return new V(t>i);case`>=`:return new V(t>=i);case`<=`:return new V(t<=i)}}else if(n instanceof H&&r instanceof H)switch(e.operator.value){case`+`:return new H(n.value.concat(r.value))}else if(r instanceof H){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new V(t);case`not in`:return new V(!t)}}if(n instanceof B||r instanceof B)switch(e.operator.value){case`+`:return new B(n.value.toString()+r.value.toString())}if(n instanceof B&&r instanceof B)switch(e.operator.value){case`in`:return new V(r.value.includes(n.value));case`not in`:return new V(!r.value.includes(n.value))}if(n instanceof B&&r instanceof Ho)switch(e.operator.value){case`in`:return new V(r.value.has(n.value));case`not in`:return new V(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=new Map;for(let i of e)if(i.type===`SpreadExpression`){let e=i,r=this.evaluate(e.argument,t);if(!(r instanceof H))throw Error(`Cannot unpack non-iterable type: ${r.type}`);for(let e of r.value)n.push(e)}else if(i.type===`KeywordArgumentExpression`){let e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw Error(`Positional arguments must come before keyword arguments`);n.push(this.evaluate(i,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 B(Vo(e,{}));if(e instanceof H)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 z(e.value.length);case`reverse`:return new H(e.value.slice().reverse());case`sort`:return new H(e.value.slice().sort((e,t)=>Zo(e,t,!1)));case`join`:return new B(e.value.map(e=>e.value).join(``));case`string`:return new B(Vo(e,{},0,!1));case`unique`:{let t=new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new H(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof B)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof Go)return t.value([],n);if(t instanceof z)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new B(e.value.trim());case`indent`:return new B(e.value.split(` +`).map((e,t)=>t===0||e.length===0?e:` `+e).join(` +`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new z(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new Ro(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof z||e instanceof Ro)switch(r.value){case`abs`:return e instanceof z?new z(Math.abs(e.value)):new Ro(Math.abs(e.value));case`int`:return new z(Math.floor(e.value));case`float`:return new Ro(e.value);case`string`:return new B(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof Ho)switch(r.value){case`items`:return new H(Array.from(e.value.entries()).map(([e,t])=>new H([new B(e),t])));case`length`:return new z(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof Go?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof V)switch(r.value){case`bool`:return new V(e.value);case`int`:return new z(e.value?1:0);case`float`:return new Ro(e.value?1:0);case`string`:return new B(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}else 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 Ko;if(!(i instanceof z||i instanceof Ko))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new V(!1);if(!(a instanceof V))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new V(!1);if(!(o instanceof V))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new Ko,c=null;if(s instanceof H||s instanceof Wo){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof B)||!(t instanceof B))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof Ko))throw Error(`If set, separators must be a tuple of two strings`);return new B(Vo(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}else if(i===`join`){let t;if(e instanceof B)t=Array.from(e.value);else if(e instanceof H)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 B(``);if(!(s instanceof B))throw Error(`separator must be a string`);return new B(t.join(s.value))}else if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new z(0):new Ro(0));if(e instanceof B){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new z(t):new Ro(t)}else if(e instanceof z||e instanceof Ro)return e;else if(e instanceof V)return i===`int`?new z(e.value?1:0):new Ro(e.value?1:0);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}else if(i===`default`){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new B(``),o=t[1]??i.get(`boolean`)??new V(!1);if(!(o instanceof V))throw Error("`default` filter flag must be a boolean");return e instanceof qo||o.value&&!e.__bool__().value?a:e}if(e instanceof H){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new V(!1);if(!(a instanceof V))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new V(!1);if(!(o instanceof V))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new Ko;if(!(s instanceof B||s instanceof z||s instanceof Ko))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof Ko?e:Xo(e,s instanceof z?String(s.value):s.value);return new H(e.value.slice().sort((e,t)=>{let n=Zo(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!(e instanceof Ho)))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 H(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 B))throw Error(`attribute must be a string`);let r=t.get(`default`);return new H(e.value.map(e=>{if(!(e instanceof Ho))throw Error(`items in map must be an object`);let t=Xo(e,n.value);return t instanceof qo?r??new qo:t}))}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}else if(e instanceof B){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new z(4);if(!(a instanceof z))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new V(!1),s=t.at(2)??i.get(`blank`)??new V(!1),c=e.value.split(` +`),l=` `.repeat(a.value);return new B(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(` +`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof Go))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new Uo(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}else if(e instanceof Ho){let t=e.builtins.get(i);if(t&&t instanceof Go){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new Uo(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}else 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 V(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new qo}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new V(!n.value);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 B(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 Uo(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 H||e instanceof B))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 z||r instanceof qo))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof z||i instanceof qo))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof z||a instanceof qo))throw Error(`Slice step must be numeric or undefined`);return e instanceof H?new H(ko(e.value,r.value,i.value,a.value)):new B(ko(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=new B(e.property.value);let i;if(n instanceof Ho){if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof H||n instanceof B)if(r instanceof z)i=n.value.at(r.value),n instanceof B&&(i=new B(n.value.at(r.value)));else if(r instanceof B)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof B))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof Lo?i:new qo}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 H))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;et.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;r0?a[t-1]:new qo],[`nextitem`,t{let r=new Jo(n);t=t.slice();let i;t.at(-1)?.type===`KeywordArgumentsValue`&&(i=t.pop());for(let n=0;n{let r=new Jo(n);if(e.callerArgs)for(let n=0;nthis.evaluate(e,t)));case`TupleLiteral`:return new Wo(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof B))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new Ho(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 Ko;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function $o(e){switch(typeof e){case`number`:return Number.isInteger(e)?new z(e):new Ro(e);case`string`:return new B(e);case`boolean`:return new V(e);case`undefined`:return new qo;case`object`:return e===null?new Ko:Array.isArray(e)?new H(e.map($o)):new Ho(new Map(Object.entries(e).map(([e,t])=>[e,$o(t)])));case`function`:return new Go((t,n)=>$o(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var es=` +`,ts=`{%- `,ns=` -%}`;function rs(e){switch(e.operator.type){case`MultiplicativeBinaryOperator`:return 4;case`AdditiveBinaryOperator`:return 3;case`ComparisonBinaryOperator`:return 2;case`Identifier`:return e.operator.value===`and`?1:e.operator.value===`in`||e.operator.value===`not in`?2:0}return 0}function is(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return os(e.body,0,n).replace(/\n$/,``)}function as(...e){return ts+e.join(` `)+ns}function os(e,t,n){return e.map(e=>ss(e,t,n)).join(es)}function ss(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return os(e.body,t,n);case`If`:return cs(e,t,n);case`For`:return ls(e,t,n);case`Set`:return us(e,t,n);case`Macro`:return ds(e,t,n);case`Break`:return r+as(`break`);case`Continue`:return r+as(`continue`);case`CallStatement`:return fs(e,t,n);case`FilterStatement`:return ps(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+U(e)+` -}}`}}function cs(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+as(`if`,U(i[0].test))+es+os(i[0].body,t+1,n);for(let e=1;e0&&(o+=es+r+as(`else`)+es+os(a.alternate,t+1,n)),o+=es+r+as(`endif`),o}function ls(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${U(t.lhs)} if ${U(t.test)}`}else i=U(e.iterable);let a=r+as(`for`,U(e.loopvar),`in`,i)+es+os(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=es+r+as(`else`)+es+os(e.defaultBlock,t+1,n)),a+=es+r+as(`endfor`),a}function us(e,t,n){let r=n.repeat(t),i=U(e.assignee),a=e.value?U(e.value):``,o=r+as(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+es+os(e.body,t+1,n)+es+r+as(`endset`)}function ds(e,t,n){let r=n.repeat(t),i=e.args.map(U).join(`, `);return r+as(`macro`,`${e.name.value}(${i})`)+es+os(e.body,t+1,n)+es+r+as(`endmacro`)}function fs(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(U).join(`, `)})`:``,a=U(e.call),o=r+as(`call${i}`,a)+es;return o+=os(e.body,t+1,n)+es,o+=r+as(`endcall`),o}function ps(e,t,n){let r=n.repeat(t),i=r+as(`filter`,e.filter.type===`Identifier`?e.filter.value:U(e.filter))+es;return i+=os(e.body,t+1,n)+es,i+=r+as(`endfilter`),i}function U(e,t=-1){switch(e.type){case`SpreadExpression`:return`*${U(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:return`${e.value}`;case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let n=e,r=rs(n),i=U(n.left,r),a=U(n.right,r+1),o=`${i} ${n.operator.value} ${a}`;return r`${U(e)}: ${U(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?U(t.start):``}:${t.stop?U(t.stop):``}${t.step?`:${U(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${U(t.value)}`}case`Ternary`:{let n=e,r=`${U(n.trueExpr)} if ${U(n.condition,0)} else ${U(n.falseExpr)}`;return t>-1?`(${r})`:r}default:throw Error(`Unknown expression type: ${e.type}`)}}var ms=class{parsed;constructor(e){this.parsed=Do(Ja(e,{lstrip_blocks:!0,trim_blocks:!0}))}render(e){let t=new Jo;if(Yo(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new Qo(t).run(this.parsed).value}format(e){return is(this.parsed,e?.indent||` `)}},hs={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`},gs=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Cr.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=Cr.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=Cr.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`,hs[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 Cr.promises.readFile(this.filePath)).buffer}async blob(){let e=await Cr.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await Cr.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},_s=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(M.IS_CRYPTO_AVAILABLE){let t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0;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&4294967295);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,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,1566083941))-i>>>0;t[0]=2147483648,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]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let 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[vs(this._random_fn,t)]}};function vs(e,t){let n=0;for(let e=0;evs(bs.random,e),Ss=new _s,Cs=class{constructor(e){this.path=e}async match(e){let t=new gs(wr.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=wr.join(this.path,e),i=r+`.tmp.${M.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${Ss._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await Cr.promises.mkdir(wr.dirname(r),{recursive:!0});let s=Cr.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=>{if(t){n(t);return}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 Cr.promises.rename(i,r)}catch(e){try{await Cr.promises.unlink(i)}catch{}throw e}}async delete(e){let t=wr.join(this.path,e);try{return await Cr.promises.unlink(t),!0}catch{return!1}}},ws={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`},Ts=100,Es=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Ds(...e){return e=e.map((t,n)=>(n&&(t=t.replace(RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(RegExp(`/$`),``)),t)),e.join(`/`)}function Os(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 ks(e){return!(!Es.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function As(e,t,n){if(!n)return null;let r=ws[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}async function js(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&P.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 Ms(e){return Os(e,[`blob:`])}function Ns(e){let t;if(typeof location<`u`&&location.href)t=location.href;else if(br!==void 0&&self.location.href)t=self.location.href;else return e;return new URL(e,t).href}var Ps=`SHA-256`,Fs=`experimental_transformers-hash-cache`,Is=e=>({algorithm:Ps,value:e}),Ls=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(Fs),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 navigator.crossOriginStorage.requestFileHandles([Is(t)]),n=await e.getFile();return new Response(n,{headers:{"Content-Length":String(n.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 navigator.crossOriginStorage.requestFileHandles([Is(t)],{create:!0}),r=await n.createWritable();await r.write(e),await r.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(Ps,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function Rs(e=null){let t=null;if(N.useCustomCache){if(!N.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!N.customCache.match||!N.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=N.customCache}if(!t&&N.experimental_useCrossOriginStorage&&Ls.isAvailable()&&(t=new Ls),!t&&N.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(N.cacheKey)}catch(e){P.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&N.useFSCache){if(!M.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new Cs(e??N.cacheDir)}return t}async function zs(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var Bs=new class{#e;#t;constructor(e){this.#e=e,this.#t=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 Vs(e,t){let n=Bs.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(Bs.delete(e),Promise.reject(t)));return Bs.put(e,r),r}async function Hs(e){if(!Os(e,[`http:`,`https:`]))return null;let t=Ks(e);return t.set(`Range`,`bytes=0-0`),N.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function Us(e,t,n={}){return Vs(JSON.stringify([e,t,n?.revision,n?.cache_dir,n?.local_files_only]),()=>Ws(e,t,n))}async function Ws(e,t,n){let r=await Rs(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=qs(e,t,n,r),c=await Js(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(N.allowLocalModels&&!Os(i,[`http:`,`https:`]))try{let e=await Gs(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(N.allowRemoteModels&&!n.local_files_only&&s)try{let e=await Hs(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}}}catch(e){P.warn(`Unable to fetch file metadata for "${a}": ${e}`)}return{exists:!1,fromCache:!1}}async function Gs(e){return N.useFS&&!Os(e,[`http:`,`https:`,`blob:`])?new gs(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):N.fetch(e,{headers:Ks(e)})}function Ks(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!{}?.TESTING_REMOTELY,r=N.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),Os(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e={}?.HF_TOKEN??{}?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function qs(e,t,n={},r=null){let i=n.revision??`main`,a=Ds(e,t),o=ks(e),s=o?Ds(N.localModelPath,a):a,c=Ds(N.remoteHost,N.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof Cs?i===`main`?a:Ds(e,i,t):c,validModelId:o}}async function Js(e,t,n){if(e)return await zs(e,t,n)}async function Ys(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0){if(!a){let a=o.progress_callback?n=>ei(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=>{P.warn(`Unable to add response to browser cache: ${e}.`)})}}}async function Xs(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=qs(e,t,r,a),d,f=!1,p;p=await Js(a,s,l);let m=p!==void 0;if(m)d=l;else{if(N.allowLocalModels){if(!Os(o,[`http:`,`https:`]))try{p=await Gs(s),d=s}catch(e){P.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(!N.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||!N.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw Error(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await Gs(c),p.status!==200)return As(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}ei(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(M.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()),ei(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 Us(e,t,r);n.size&&(i=n.size)}catch{}n=await js(p,n=>{ei(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}h=n}if(f&&d&&typeof p!=`string`&&await Ys(e,t,a,d,p,h,r),M.IS_NODE_ENV&&i&&r.progress_callback&&typeof p!=`string`){let n=parseInt(p.headers.get(`content-length`),10)||0;ei(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n,total:n})}if(ei(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!M.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof gs)return p.filePath;let g=await a?.match(d);if(g instanceof gs)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 Zs=new Map;async function Qs(e,t,n=!0,r={},i=!1){if(!N.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(!N.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}ei(r.progress_callback,{status:`initiate`,name:e,file:t});let a=`${e}::${t}`,o=Zs.get(a);return o||(o=Xs(e,t,n,r,i,await Rs(r?.cache_dir)).then(e=>(Zs.delete(a),e),e=>{throw Zs.delete(a),e}),Zs.set(a,o)),await o}async function $s(e,t,n=!0,r={}){let i=await Qs(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function ec(e,t,n=!0,r={}){let i=await $s(e,t,n,r);return i===null?{}:JSON.parse(i)}function tc(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=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=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function rc(e){let t=oc(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 ic(e){let t=oc(e)[0],n=0;for(let r=0;re-t-r)}function ac(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[t,n]}function sc(e){return e>0&&(e&e-1)==0}var cc=class{constructor(e){if(this.size=e|0,this.size<=1||!sc(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;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;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>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o>>1,i>>>1)}else for(o=0,s=0;o>>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>>1;for(let t=2;t>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 cc(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>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function fc(e,t){let n=10**t;return Math.round(e*n)/n}function pc(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function mc(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;t0||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 hc=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let t=new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t>10,s=t&1023;if(o===31)i=a|2139095040|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_c});var _c={};async function vc(e){let t=e.split(`/`).pop(),n;try{if(n=await Rs(),n){let t=await n.match(e);if(t)return t}}catch(e){P.warn(`Failed to load ${t} from cache:`,e)}let r=await N.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){P.warn(`Failed to cache ${t}:`,e)}return r}async function yc(e){let t=await vc(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return P.warn(`Failed to read WASM binary:`,e),null}}async function bc(e){if(M.IS_SERVICE_WORKER_ENV||M.IS_CHROME_AVAILABLE)return e;let t=await vc(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 P.warn(`Failed to read WASM factory:`,e),null}}var xc=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 Sc(e){return e<=Xr.DEBUG?0:e<=Xr.INFO?2:e<=Xr.WARNING||e<=Xr.ERROR?3:4}var Cc={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},wc=[],Tc,Ec,Dc=Symbol.for(`onnxruntime`);if(Dc in globalThis)Ec=globalThis[Dc];else if(M.IS_NODE_ENV){switch(Ec=gc,process.platform){case`win32`:wc.push(`dml`);break;case`linux`:process.arch===`x64`&&wc.push(`cuda`);break;case`darwin`:wc.push(`coreml`);break}wc.push(`webgpu`),wc.push(`cpu`),Tc=[`cpu`]}else Ec=t,M.IS_WEBNN_AVAILABLE&&wc.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),M.IS_WEBGPU_AVAILABLE&&wc.push(`webgpu`),wc.push(`wasm`),Tc=[`wasm`];var Oc=Ec.InferenceSession;function kc(e=null){if(!e)return Tc;switch(e){case`auto`:return wc;case`gpu`:return wc.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(wc.includes(e))return[xc[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${wc.join(`, `)}.`)}var Ac=Promise.resolve(),jc=null;async function Mc(){if(jc)return jc;if(!(N.useWasmCache&&typeof Lc?.wasm?.wasmPaths==`object`&&Lc?.wasm?.wasmPaths?.wasm&&Lc?.wasm?.wasmPaths?.mjs)){if(M.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return jc=Promise.resolve(),jc}return jc=(async()=>{let e=Lc.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!Ms(e.wasm)?(async()=>{try{let n=await yc(Ns(e.wasm));n&&(Lc.wasm.wasmBinary=n,t=!0)}catch(e){P.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!Ms(e.mjs)?(async()=>{try{let t=await bc(Ns(e.mjs));t&&(Lc.wasm.wasmPaths.mjs=t)}catch(e){P.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Lc.wasm.wasmPaths.mjs=e.mjs)})(),jc}async function Nc(e,t,n){await Mc();let r=Sc(N.logLevel??Xr.WARNING),i=()=>Oc.create(e,{logSeverityLevel:r,...t}),a=await(M.IS_WEB_ENV?Ac=Ac.then(i):i());return a.config=n,a}var Pc=Promise.resolve();async function Fc(e,t){let n=()=>e.run(t);return M.IS_WEB_ENV?Pc=Pc.then(n):n()}function Ic(e){return e instanceof Ec.Tensor}var Lc=Ec?.env;function Rc(){return Lc?.wasm?.proxy}if(Lc){let e=function(e){Lc.logLevel=Cc[Sc(e)]};if(Lc.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Lc.versions?.web&&!Lc.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Lc.versions.web}/dist/`;Lc.wasm.wasmPaths=M.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Lc.wasm.proxy=!1}Lc.webgpu&&(Lc.webgpu.powerPreference=`high-performance`),e(N.logLevel??Xr.WARNING),N.backends.onnx={...Lc,setLogLevel:e}}var zc=async(e,t,n)=>{let r=await Nc(new Uint8Array(e),t);return(async e=>{let t=Rc(),i=await Fc(r,Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])));return Array.isArray(n)?n.map(e=>new W(i[e])):new W(i[n])})},Bc=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=zc([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||=zc([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||=zc([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||=zc([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||=zc([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||=zc([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=zc([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||=zc([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}},Vc=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`}),Hc=M.IS_NODE_ENV?`cpu`:`wasm`;function Uc(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 (${Hc}).`),Hc):Hc}var Wc=(function(){let e;return async function(){if(e===void 0)if(!M.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}return e}})(),Gc=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`}),Kc=Gc.fp32,qc=Object.freeze({[Vc.wasm]:Gc.q8}),Jc=Object.freeze({[Gc.fp32]:``,[Gc.fp16]:`_fp16`,[Gc.int8]:`_int8`,[Gc.uint8]:`_uint8`,[Gc.q8]:`_quantized`,[Gc.q4]:`_q4`,[Gc.q4f16]:`_q4f16`,[Gc.bnb4]:`_bnb4`});function Yc(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===Gc.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==Gc.auto&&Gc.hasOwnProperty(e))return e}s=qc[n]??Kc}else s=a&&Gc.hasOwnProperty(a)?a:qc[n]??Kc;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var Xc=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}),W=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 Ic(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new j(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;r0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}else return new e(this.type,[this.data[t]],r)}indexOf(e){let t=this.data;for(let n=0;na)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=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 Qc(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]=dl(o,this,n,r);if(t!==1)for(let e=0;e=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 ml(this.dims)}squeeze(t=null){return new e(this.type,this.data,ol(this.dims,t))}squeeze_(e=null){return this.dims=ol(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,sl(this.dims,t))}unsqueeze_(e){return this.dims=sl(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;er===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;tt?1:0;return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;eMath.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=oc(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=dl((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=ac(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=oc(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.lengthe===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=ml(r),l=ml(i);for(let e=0;eBigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,hc(this.data),this.dims);return new e(t,Xc[t].from(this.data,n),this.dims)}};function Zc(e,t){let n=e.length;if(n!==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.lengthnew W(`int64`,e,[e.length]);async function il(e,t,n,r,i){return await(await Bc.slice)({x:e,s:rl(t),e:rl(n),a:rl(r),t:rl(i??Array(r.length).fill(1))})}function al(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;ee!==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 sl(e,t){return t=cl(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function cl(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 ll(e,t=0){t=cl(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=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 W(a,i,n)}function ul(e,t=0){return ll(e.map(e=>e.unsqueeze(t)),t)}function dl(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=cl(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=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 fl(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 W(e.type,[t],[]);return[new W(e.type,[r],[]),a]}t=cl(t,a.length);let o=pl(e,t,r),s=o.data,[c,l,u]=dl((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;ee+t,0);return new W(e.type,[t/i.length],[])}t=cl(t,r.length);let[a,o,s]=dl((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e=0;--n)t[n]=r,r*=e[n];return t}function hl(e,t,n,r){return new W(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function gl(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 hl(e,t,n,r)}function _l(e,t){return gl(e.dims,t)}function vl(e){return hl(e,1n,`int64`,BigInt64Array)}function yl(e){return vl(e.dims)}function bl(e){return hl(e,0n,`int64`,BigInt64Array)}function xl(e){return bl(e.dims)}function Sl(e){let t=e.reduce((e,t)=>e*t,1);return new W(`float32`,Float32Array.from({length:t},()=>bs.gauss()),e)}function Cl(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;e0?1:0,r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new W(r,o,[e.dims[0],e.dims[1]/8])}async function wl(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await Us(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function Tl(e,t){let n=await wl(e);return await Promise.all(n.map(n=>ec(e,n,!0,t)))}function El(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 Dl=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function Ol(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`?ai(e[i],s):ai(s,e[i])}}function kl(e,t){for(let n of Object.keys(e))e[n].length=t}function Al(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}`)}else return t}return null}function jl(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var G=class extends $r{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Ba(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Al(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Al(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Al(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Al(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Al(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Al(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=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=new Map;let n=jl(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 Tl(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,{text_pair:t=null,add_special_tokens:n=!0,padding:r=!1,truncation:i=null,max_length:a=null,return_tensor:o=!0,return_token_type_ids:s=null}={}){let c=Array.isArray(e),l;if(c){if(e.length===0)throw Error(`text array must be non-empty`);if(t!==null){if(!Array.isArray(t))throw Error(`text_pair must also be an array`);if(e.length!==t.length)throw Error(`text and text_pair must have the same length`);l=e.map((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:n,return_token_type_ids:s}))}else l=e.map(e=>this._encode_plus(e,{add_special_tokens:n,return_token_type_ids:s}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");l=[this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:s})]}if(a===null?a=this.model_max_length:i===null&&(r===!0?(P.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):r===!1&&(P.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."),i=!0)),r===!0&&(a=Math.min(oc(l.map(e=>e.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),r||i)for(let e=0;ea?i&&kl(l[e],a):r&&Ol(l[e],a,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let u={};if(o){if(!(r&&i)&&l.some(e=>{for(let t of Object.keys(e))if(e[t].length!==l[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=[l.length,l[0].input_ids.length];for(let t of Object.keys(l[0]))u[t]=new W(`int64`,BigInt64Array.from(l.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(l[0]))u[e]=l.map(t=>t[e]);if(!c)for(let e of Object.keys(u))u[e]=u[e][0]}return u}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens: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 W&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof W&&(e=El(e)),!Array.isArray(e)||e.length===0||!ni(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,{tools:t=null,documents:n=null,chat_template:r=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:o=!1,truncation:s=!1,max_length:c=null,return_tensor:l=!0,return_dict:u=!0,tokenizer_kwargs:d={},...f}={}){if(r=this.get_chat_template({chat_template:r,tools:t}),typeof r!=`string`)throw Error(`chat_template must be a string, but got ${typeof r}`);let p=this._compiled_template_cache.get(r);p===void 0&&(p=new ms(r),this._compiled_template_cache.set(r,p));let m=Object.create(null);for(let e of Dl){let t=Al(this.config,e);t&&(m[e]=t)}let h=p.render({messages:e,add_generation_prompt:i,tools:t,documents:n,...m,...f});if(a){let e=this._call(h,{add_special_tokens:!1,padding:o,truncation:s,max_length:c,return_tensor:l,...d});return u?e:e.input_ids}return h}};function Ml(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(`, `)}}`);for(let t of e._tokenizer.post_processor.config.single)if(`SpecialToken`in t&&e.languageRegex.test(t.SpecialToken.id)){t.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 Nl={};Sr(Nl,{AlbertTokenizer:()=>Pl,AutoTokenizer:()=>Mu,BartTokenizer:()=>Fl,BertTokenizer:()=>Il,BlenderbotSmallTokenizer:()=>Ll,BlenderbotTokenizer:()=>Rl,BloomTokenizer:()=>zl,CLIPTokenizer:()=>Vl,CamembertTokenizer:()=>Bl,CodeGenTokenizer:()=>Ul,CodeLlamaTokenizer:()=>Hl,CohereAsrTokenizer:()=>Gl,CohereTokenizer:()=>Wl,ConvBertTokenizer:()=>Kl,DebertaTokenizer:()=>Jl,DebertaV2Tokenizer:()=>ql,DistilBertTokenizer:()=>Yl,ElectraTokenizer:()=>Xl,EsmTokenizer:()=>Zl,FalconTokenizer:()=>Ql,GPT2Tokenizer:()=>tu,GPTNeoXTokenizer:()=>eu,GemmaTokenizer:()=>$l,HerbertTokenizer:()=>nu,LlamaTokenizer:()=>ru,M2M100Tokenizer:()=>iu,MBart50Tokenizer:()=>su,MBartTokenizer:()=>ou,MPNetTokenizer:()=>uu,MarianTokenizer:()=>au,MgpstrTokenizer:()=>cu,MobileBertTokenizer:()=>lu,NllbTokenizer:()=>du,NougatTokenizer:()=>fu,PreTrainedTokenizer:()=>G,Qwen2Tokenizer:()=>pu,RoFormerTokenizer:()=>hu,RobertaTokenizer:()=>mu,SiglipTokenizer:()=>gu,SpeechT5Tokenizer:()=>_u,SqueezeBertTokenizer:()=>vu,T5Tokenizer:()=>yu,TokenizersBackend:()=>G,VitsTokenizer:()=>xu,Wav2Vec2CTCTokenizer:()=>Su,WhisperTokenizer:()=>ku,XLMRobertaTokenizer:()=>Au,XLMTokenizer:()=>ju});var Pl=class extends G{return_token_type_ids=!0},Fl=class extends G{},Il=class extends G{return_token_type_ids=!0},Ll=class extends G{},Rl=class extends G{},zl=class extends G{},Bl=class extends G{},Vl=class extends G{},Hl=class extends G{},Ul=class extends G{},Wl=class extends G{},Gl=class extends G{},Kl=class extends G{return_token_type_ids=!0},ql=class extends G{return_token_type_ids=!0},Jl=class extends G{return_token_type_ids=!0},Yl=class extends G{},Xl=class extends G{return_token_type_ids=!0},Zl=class extends G{},Ql=class extends G{},$l=class extends G{},eu=class extends G{},tu=class extends G{},nu=class extends G{return_token_type_ids=!0},ru=class extends G{padding_side=`left`},iu=class extends G{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 Ml(this,e,t,n)}},au=class extends G{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)),P.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)||P.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ai([e],super._encode_text(t))}}},ou=class extends G{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 Ml(this,e,t,n)}},su=class extends ou{},cu=class extends G{},lu=class extends G{return_token_type_ids=!0},uu=class extends G{},du=class extends G{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 Ml(this,e,t,n)}},fu=class extends G{},pu=class extends G{},mu=class extends G{},hu=class extends G{return_token_type_ids=!0},gu=class extends G{},_u=class extends G{},vu=class extends G{return_token_type_ids=!0},yu=class extends G{},bu=class extends Da{decode_chain(e){let t=``;for(let n=1;n[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 Eu(e){e=e.toLowerCase();let t=Tu.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),wu.has(e))t=e;else{let t=e.length===2?wu.keys():wu.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var Du=RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),Ou=.1,ku=class extends G{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=d&&g<=f){let e=fc((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g0&&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=fc(i[n]+u,2),t;if(n+10?(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=Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e0,o=a?[]:null,s=a?t[0]:null;for(let c=1;ce===g[n]&&s[i+n][0]-Ou<=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){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=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=Du.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]=ai(o[c],o[l]),s[l]=ai(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;le),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},Au=class extends G{},ju=class extends G{return_token_type_ids=!0;constructor(e,t){super(e,t),P.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Mu=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 Tl(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=Nl[c];return l||=(P.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),G),new l(o,s)}},Nu=`https://github.com/huggingface/transformers.js/issues/new/choose`,Pu=`preprocessor_config.json`,Fu=Pu,Iu=`processor_config.json`,Lu=`chat_template.jinja`,K=class extends $r{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?ec(e,Iu,!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?$s(e,Lu,!0,t):null]);return new this(n,r,i)}},Ru={};Sr(Ru,{ChatterboxProcessor:()=>jd,CohereAsrProcessor:()=>Nd,Florence2Processor:()=>Cp,Gemma3Processor:()=>wp,Gemma3nProcessor:()=>Tp,Gemma4Processor:()=>Ep,Glm46VProcessor:()=>Op,GraniteSpeechProcessor:()=>kp,GroundingDinoProcessor:()=>jp,Idefics3Processor:()=>Fp,JinaCLIPProcessor:()=>Lp,Lfm2VlProcessor:()=>Rp,LlavaProcessor:()=>zp,MgpstrProcessor:()=>Vp,MoonshineProcessor:()=>Hp,OwlViTProcessor:()=>Up,PaliGemmaProcessor:()=>Kp,Phi3VProcessor:()=>Yp,PixtralProcessor:()=>Xp,Processor:()=>K,PyAnnoteProcessor:()=>Zp,Qwen2VLProcessor:()=>Dp,Qwen2_5_VLProcessor:()=>Qp,Qwen3VLProcessor:()=>$p,Sam2Processor:()=>tm,Sam2VideoProcessor:()=>nm,SamProcessor:()=>em,SmolVLMProcessor:()=>Fp,SpeechT5Processor:()=>rm,UltravoxProcessor:()=>im,VLChatProcessor:()=>Ip,VoxtralProcessor:()=>lm,VoxtralRealtimeProcessor:()=>hm,Wav2Vec2Processor:()=>gm,Wav2Vec2ProcessorWithLM:()=>_m,WhisperProcessor:()=>vm});var zu=class extends $r{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await ec(e,Pu,!0,t);return new this(n)}};function Bu(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 \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Vu={};Sr(Vu,{ASTFeatureExtractor:()=>ud,ChatterboxFeatureExtractor:()=>fd,ClapFeatureExtractor:()=>pd,CohereAsrFeatureExtractor:()=>gd,DacFeatureExtractor:()=>_d,EncodecFeatureExtractor:()=>dd,FeatureExtractor:()=>zu,Gemma3nAudioFeatureExtractor:()=>vd,Gemma4AudioFeatureExtractor:()=>yd,GraniteSpeechFeatureExtractor:()=>bd,MoonshineFeatureExtractor:()=>xd,ParakeetFeatureExtractor:()=>hd,PyAnnoteFeatureExtractor:()=>Sd,SeamlessM4TFeatureExtractor:()=>Cd,SnacFeatureExtractor:()=>wd,SpeechT5FeatureExtractor:()=>Td,VoxtralRealtimeFeatureExtractor:()=>Od,Wav2Vec2FeatureExtractor:()=>Ed,WeSpeakerFeatureExtractor:()=>Dd,WhisperFeatureExtractor:()=>kd});var Hu={fromWeb:()=>{}};async function Uu(e,t){if(M.IS_BROWSER_ENV){if(M.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(M.IS_FS_AVAILABLE){let n=t.stream();await(Hu.fromWeb(n),Cr.createWriteStream(e),void 0)}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function Wu(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 Gs(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&P.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;r2595*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 Yu(e,t=`htk`){let n=Ju[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 Xu={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 Zu(e,t=`htk`){let n=Xu[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 Qu(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;nArray(e.length));for(let t=0;te+r*n)}function ed(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=$u(Yu(n,o),Yu(r,o),t+2),l=Zu(c,o),u;if(s){let t=i/((e-1)*2);u=Yu(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=$u(0,Math.floor(i/2),e);let d=Qu(u,l);if(a!==null&&a===`slaney`)for(let n=0;ni)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(C!==n)throw Error(`Length of the window (${C}) 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=td(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 w=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&ww?x&&(T=b):T=re=b);let E=new uc(i),ie=new Float64Array(i),ae=new Float64Array(E.outputBufferSize),oe=new Float32Array(ne*T);for(let i=0;i=1;--e)ie[e]-=l*ie[e-1];ie[0]*=1-l}for(let e=0;ee**.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 sd(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44),i=new DataView(r);return cd(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),cd(i,8,`WAVE`),cd(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),cd(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer)],{type:`audio/wav`})}function cd(e,t,n){for(let r=0;re+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),sd(e,this.sampling_rate)}async save(e){return Uu(e,this.toBlob())}},ud=class extends zu{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=ed(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=od(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return ad(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){Bu(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;t0)if(n===`rand_trunc`){let n=Math.floor(bs.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=1;--n)e[n]-=t*e[n-1];return await ad(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){Bu(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;e1?n-1:1;for(let e=0;e=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;at&&(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=gl([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},yd=class extends vd{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 ad(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={}){Bu(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({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},Cd=class extends zu{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=ed(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=od(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),ad(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}={}){Bu(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;r0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new W(a.type,n,[c,t]),i&&(o=new W(`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;ne+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){Bu(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 W(`float32`,t,n),attention_mask:new W(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},Dd=class extends zu{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=ed(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=od(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),ad(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){Bu(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;tr?(e.length>this.config.n_samples&&P.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)}}},Ad=class{static async from_pretrained(e,t={}){let n=await ec(e,Pu,!0,t),r=n.feature_extractor_type,i=Vu[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${Nu}.`);return new i(n)}},jd=class extends K{static tokenizer_class=Mu;static feature_extractor_class=Ad;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},Md=new Set([`ja`,`zh`]),Nd=class extends K{static tokenizer_class=Mu;static feature_extractor_class=Ad;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=Md.has(t)?``:` `;return[n[0].trimEnd(),...n.slice(1).map(e=>e.trim())].join(r)}async _call(e){return await this.feature_extractor(e)}},Pd={},Fd,Id,Ld;if(M.IS_WEB_ENV)Fd=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},Ld=self.createImageBitmap,Id=self.ImageData;else if(Pd)Ld=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new Bd(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 Rd={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},zd=new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),Bd=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(!M.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 Gs(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(M.IS_WEB_ENV){let t=await Ld(e),n=Fd(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)}else{let t=Pd(await e.arrayBuffer());return await Ld(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.transpose(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=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)}else{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 Ld(e)}}async toBlob(e=`image/png`,t=1){if(!M.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 W(`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(!M.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=Fd(e.width,e.height),n=new Id(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;enew 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(M.IS_WEB_ENV){if(M.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=zd.get(t)??`image/png`;return Uu(e,await this.toBlob(n))}else if(M.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(M.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return Pd(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},Vd=Bd.read.bind(Bd);function Hd(e,t,n=0,r=null){let i=e/t,a=pc(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),at&&i.push(e)}else{let e=oc(n.data)[1];if(e===c-1||(a=rc(n.data),a[e]e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function Kd(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;el[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;ee!==void 0);i.push({segmentation:c,labels:f})}return i}function qd(e,t,n,r){let i=[],a=[],o=[];for(let s=0;sn&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function Jd(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function Yd(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new W(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;tf[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a200)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*si?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=ac(n.data)[0],i=oc(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;ethis.preprocess(e)));return{pixel_values:ul(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 ec(e,Fu,!0,t);return new this(n)}},$d={};Sr($d,{BeitFeatureExtractor:()=>ef,BitImageProcessor:()=>tf,CHMv2ImageProcessor:()=>rf,CLIPFeatureExtractor:()=>of,CLIPImageProcessor:()=>af,ChineseCLIPFeatureExtractor:()=>nf,ConvNextFeatureExtractor:()=>cf,ConvNextImageProcessor:()=>sf,DINOv3ViTImageProcessor:()=>pf,DPTFeatureExtractor:()=>_f,DPTImageProcessor:()=>gf,DeiTFeatureExtractor:()=>uf,DeiTImageProcessor:()=>lf,DetrFeatureExtractor:()=>ff,DetrImageProcessor:()=>df,DonutFeatureExtractor:()=>hf,DonutImageProcessor:()=>mf,EfficientNetImageProcessor:()=>vf,GLPNFeatureExtractor:()=>Tf,Gemma3ImageProcessor:()=>yf,Gemma4ImageProcessor:()=>Sf,Glm46VImageProcessor:()=>wf,GroundingDinoImageProcessor:()=>Ef,Idefics3ImageProcessor:()=>Df,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>kf,Lfm2VlImageProcessor:()=>Ff,LlavaOnevisionImageProcessor:()=>If,Mask2FormerImageProcessor:()=>zf,MaskFormerFeatureExtractor:()=>Rf,MaskFormerImageProcessor:()=>Lf,MobileNetV1FeatureExtractor:()=>Vf,MobileNetV1ImageProcessor:()=>Bf,MobileNetV2FeatureExtractor:()=>Uf,MobileNetV2ImageProcessor:()=>Hf,MobileNetV3FeatureExtractor:()=>Gf,MobileNetV3ImageProcessor:()=>Wf,MobileNetV4FeatureExtractor:()=>qf,MobileNetV4ImageProcessor:()=>Kf,MobileViTFeatureExtractor:()=>Yf,MobileViTImageProcessor:()=>Jf,NougatImageProcessor:()=>Xf,OwlViTFeatureExtractor:()=>Qf,OwlViTImageProcessor:()=>Zf,Owlv2ImageProcessor:()=>$f,Phi3VImageProcessor:()=>ap,PixtralImageProcessor:()=>op,PvtImageProcessor:()=>sp,Qwen2VLImageProcessor:()=>Cf,RTDetrImageProcessor:()=>cp,Sam2ImageProcessor:()=>lp,Sam3ImageProcessor:()=>lp,SamImageProcessor:()=>lp,SapiensFeatureExtractor:()=>dp,SapiensImageProcessor:()=>up,SegformerFeatureExtractor:()=>pp,SegformerImageProcessor:()=>fp,SiglipImageProcessor:()=>mp,SmolVLMImageProcessor:()=>Df,Swin2SRImageProcessor:()=>hp,VLMImageProcessor:()=>Of,ViTFeatureExtractor:()=>_p,ViTImageProcessor:()=>gp,VitMatteImageProcessor:()=>vp,VitPoseImageProcessor:()=>yp,YolosFeatureExtractor:()=>xp,YolosImageProcessor:()=>bp});var ef=class extends q{},tf=class extends q{},nf=class extends q{},rf=class extends q{},af=class extends q{},of=class extends af{},sf=class extends q{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw 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}},cf=class extends sf{},lf=class extends q{},uf=class extends lf{},df=class extends q{async _call(e){let t=await super._call(e),n=gl([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Gd(...e)}post_process_panoptic_segmentation(...e){return Zd(...e)}post_process_instance_segmentation(...e){return Qd(...e)}},ff=class extends df{},pf=class extends q{},mf=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})}},hf=class extends mf{},gf=class extends q{},_f=class extends gf{},vf=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))}},yf=class extends q{};function bf(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 xf(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;ta),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 W(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},wf=class extends Cf{get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size,r=this.config.temporal_patch_size??2;return Xd(e.height,e.width,n,this.min_pixels,this.max_pixels,r)}},Tf=class extends q{},Ef=class extends q{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=vl([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},Df=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 el(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,ll(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>el(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(ll(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=gl([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=gl([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;rn||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;ne*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},kf=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 Af(e,t){return Math.round(e/t)*t}function jf(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.5*i*i*n[0]*n[1]&&(o=n)}return o}function Mf(e,t){let n=[],r=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 Nf(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;ethis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=Mf(this.min_tiles,this.max_tiles),[r,i]=jf(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]=Xd(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 el(l,{size:[a,i]});m=[];for(let t=0;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||ip(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 el(e,{size:[ep,ep],mode:`bicubic`});if(t>0){let a=[],s=ip(t),c=rp(r/s),l=rp(n/s);for(let t=0;te.map(e=>ep*np(e/ep)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new W(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},op=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]}},sp=class extends q{},cp=class extends q{post_process_object_detection(...e){return Gd(...e)}},lp=class extends q{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=ii(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;re!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new W(`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;ar&&(t[n]=1);u=new W(`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}={}){}},up=class extends q{post_process_semantic_segmentation(...e){return Kd(...e)}},dp=class extends up{},fp=class extends q{post_process_semantic_segmentation(...e){return Kd(...e)}},pp=class extends fp{},mp=class extends q{},hp=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})}},gp=class extends q{},_p=class extends gp{},vp=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:ul(n.map((e,t)=>ll([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)}}},yp=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/gm,bboxes:/([^<]+)?/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(``,``).replaceAll(``,``);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}}},wp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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,this.full_image_sequence=` + +${r}${i.repeat(this.image_seq_length)}${a} + +`}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}}},Tp=class extends K{static image_processor_class=Sp;static feature_extractor_class=Ad;static tokenizer_class=Mu;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,this.full_audio_sequence=` + +${i}${a.repeat(this.audio_seq_length)}${o} + +`,this.image_token_id=s,this.boi_token=c,this.image_token=l,this.full_image_sequence=` + +${c}${l.repeat(this.image_seq_length)}${u} + +`}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}}},Ep=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([ec(e,Iu,!0,t),Mu.from_pretrained(e,t),$s(e,Lu,!1,t)]),a={tokenizer:r};return n.image_processor&&(a.image_processor=new Sf(n.image_processor)),n.feature_extractor&&(a.feature_extractor=new yd(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,()=>` + +${this.boi_token}${this.image_token.repeat(n[a++])}${this.eoi_token} + +`))}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,()=>` + +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[o++].length,i))}${this.eoa_token} + +`))}return{...this.tokenizer(e,r),...i,...a}}},Dp=class extends K{static image_processor_class=Sp;static tokenizer_class=Mu;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}}},Op=class extends Dp{static image_token=`<|image|>`},kp=class extends K{static tokenizer_class=Mu;static feature_extractor_class=Ad;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 W(`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 Ap(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 jp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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=>Wd(e))),f=[];for(let e=0;ee.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i`+i.repeat(e);o+=` +`}return o+=` +${r}${a}`+i.repeat(e)+`${r}`,o}function Np(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function Pp(e,t,n,r,i,a){return e===0&&t===0?Np(n,r,i,a):Mp(n,e,t,r,i,a)}var Fp=class extends K{static image_processor_class=Sp;static tokenizer_class=Mu;static uses_processor_config=!0;fake_image_token=``;image_token=``;global_img_token=``;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;tPp(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;ee.images).flatMap(e=>e.images).map(e=>Bd.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;e0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},Lp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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}}},Rp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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??``,{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`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},zp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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;e0?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`;function Gp(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e} +`}var Kp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(P.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(Wp))?a=t.map(e=>{let t=e.replaceAll(Wp,Wp.repeat(i)),n=t.lastIndexOf(Wp),a=n===-1?0:n+Wp.length;return t.slice(0,a)+r+t.slice(a)+` +`}):(P.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 `` 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=>Gp(t,r,i,Wp,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},qp=`<|image|>`,Jp=/<\|image_\d+\|>/g,Yp=class extends K{static image_processor_class=Sp;static tokenizer_class=Mu;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(Jp).join(qp.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(qp);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},Xp=class extends K{static tokenizer_class=Mu;static image_processor_class=Sp;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;ecm(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?ll(u,0):u[0];let d=i[0];for(let e=0;e0){if(l>Ts)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${Ts}).`);let t=Dm(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await Qs(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await Qs(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function Am(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=Uc(n.device??a.device,t,{warn:e=>P.info(e)}),s=kc(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=Yc(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>P.info(e)});if(!Jc.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(Gc).join(`, `)}`);if(o===`webgpu`&&!M.IS_NODE_ENV&&l===Gc.fp16&&!await Wc())throw Error(`The device (${o}) does not support fp16.`);let u=a.kv_cache_dtype,d=u?typeof u==`string`?u:u[l]??`float32`:void 0;if(d&&![`float32`,`float16`].includes(d))throw Error(`Invalid kv_cache_dtype: ${d}. Should be one of: float32, float16`);let f=Jc[l],p={...n.session_options};p.executionProviders??=s;let m=a.free_dimension_overrides;m?p.freeDimensionOverrides??=m:o.startsWith(`webnn`)&&!p.freeDimensionOverrides&&P.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 h=Om(e,t,n,f),g=await km(e,t,f,n,n.use_external_data_format??a.use_external_data_format,p);if(g.length>0&&(!M.IS_NODE_ENV||g.some(e=>typeof e!=`string`))&&(p.externalData=g),r&&o===`webgpu`&&u!==!1){let e=Sm(n.config,{prefix:`present`,session_name:i});if(Object.keys(e).length>0&&!Rc()){let t={};for(let n in e)t[n]=`gpu-buffer`;p.preferredOutputLocation=t}}return{buffer_or_path:await h,session_options:p,session_config:{dtype:l,kv_cache_dtype:d,device:o}}}async function jm(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 Am(e,t[i],n,a,i);return[i,await Nc(o,s,c)]})))}function Mm(e){for(let t in e)Ic(e[t])?e[t]=new W(e[t]):typeof e[t]==`object`&&Mm(e[t]);return e}async function J(e,t){let n=Nm(e,t);try{return Mm(await Fc(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return M.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 P.error(`An error occurred during model execution: "${e}".`),P.error(`Inputs given to model:`,t),e}}function Nm(e,t){let n=Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];if(!(e instanceof W)){r.push(i);continue}n[i]=Rc()?e.clone():e}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));P.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var Pm=class{},Y=class extends Pm{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},Fm=class extends Pm{constructor({logits:e}){super(),this.logits=e}},Im=class extends Pm{constructor({logits:e}){super(),this.logits=e}},Lm=class extends Pm{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Rm=class extends Pm{constructor({logits:e}){super(),this.logits=e}},zm=class extends Pm{constructor({alphas:e}){super(),this.alphas=e}},Bm=class extends $r{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Vm=class extends $r{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Hm=class extends $r{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()}},Um=class extends Bm{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=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=ic(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>oc(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},Jm=class extends Bm{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r1 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;ee.length>=this.max_length)}},ah=class extends nh{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)})}},oh=class extends nh{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return Array(e.length).fill(this.interrupted)}},sh=class extends $r{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 xs(e)}static getSampler(e){if(e.do_sample)return new lh(e);if(e.num_beams>1)return new uh(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 ch(e)}},ch=class extends sh{async sample(e){let t=oc(e.data)[1];return[[BigInt(t),0]]}},lh=class extends sh{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 nl(e,t),i=rc(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},uh=class extends sh{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 nl(e,t),i=rc(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},dh=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 W))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;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.`)}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},fh={[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={...fh[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={...fh[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={...fh[X.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},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={...fh[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`}},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function ph(e,t,n={}){let r=fh[e]??fh.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function mh(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=Ch.get(e);if(t!==void 0)return t}if(e.model_type){let t=Ch.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(_h))if(t.has(e.model_type)){let n=Ch.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;P.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: ${Nu}`)}return X.EncoderOnly}function hh(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?Vs(JSON.stringify([e,n,r,i]),()=>Tm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):Tm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function gh(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await hh(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=mh(t),f=(e,t=null)=>{t??=e;let n=Jc[Yc(u,e,Uc(l,e))]??``,r=`${t}${n}.onnx`,i=`${c}/${r}`;a.push(i);let o=Em(s,r,e);for(let e of Dm(r,o)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=ph(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 _h=null;function vh(e){_h=e}function yh(e){if(e instanceof W)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 W(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}else return new W(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function bh(e){return new W(`bool`,[e],[1])}var xh={[X.DecoderOnly]:{can_generate:!0,forward:kh,prepare_inputs:Fh},[X.DecoderOnlyWithoutHead]:{can_generate:!1,forward:kh,prepare_inputs:Fh},[X.Seq2Seq]:{can_generate:!0,forward:Eh,prepare_inputs:Ih},[X.Vision2Seq]:{can_generate:!0,forward:Eh,prepare_inputs:Ih},[X.Musicgen]:{can_generate:!0,forward:Eh},[X.EncoderDecoder]:{can_generate:!1,forward:Eh},[X.ImageTextToText]:{can_generate:!0,forward:Mh,prepare_inputs:Lh},[X.AudioTextToText]:{can_generate:!0,forward:jh,prepare_inputs:Lh},[X.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Lh},[X.Phi3V]:{can_generate:!0,prepare_inputs:Lh},[X.MultiModality]:{can_generate:!0},[X.AutoEncoder]:{can_generate:!1,forward:Oh},[X.Chatterbox]:{can_generate:!0,forward:Dh},[X.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Fh},default:{can_generate:!1,forward:Dh}};function Sh(e,t){let n=Ch.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=Ch.get(i);e!==void 0&&(n=e,r=!0)}let a=xh[n]??xh.default,o=fh[n]??fh.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var Ch=new Map,wh=new Map,Th=new Map,Z=class extends $r{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}=Sh(Th.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=Th.get(this);n=f.config=await Tm.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=Sh(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&P.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${Nu}.`)}if(t&&!(t instanceof ti)){let r={};try{let t=await gh(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>Us(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){P.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new ti(t,r))}let _=[jm(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(Vh(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 Hm;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new Ym(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new Jm(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new Qm(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new Xm(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 Zm(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new Um(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new Wm(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new Gm(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new Km(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new $m(e.guidance_scale)),e.temperature===0&&e.do_sample&&(P.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 eh(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=th){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,ci(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new rh;return e.max_length!==null&&n.push(new ih(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new ah(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[_h.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,_h.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,_h.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,_h.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Th.get(this.constructor),n=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=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new W(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=ll([n.decoder_attention_mask,vl([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=ll([n.attention_mask,vl([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=ci(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,...ci(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Dh(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=ll([i,_l(i,0)],0),`attention_mask`in t&&(t.attention_mask=ll([t.attention_mask,xl(t.attention_mask)],0));else if(t.decoder_input_ids){let e=yh(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=ll(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 W)){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\` expcted to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=yh(o)}return s.decoder_attention_mask=yl(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=sh.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=this.getAttentions(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,ci(v,this._return_dict_in_generate_keys));let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;te))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=this.getPastKeyValues(v,s.past_key_values,!0),ee=new W(`int64`,_.flat(),[_.length,_[0].length]);if(t.return_dict_in_generate)return{sequences:ee,past_key_values:x,...y,...b};for(let e of Object.values(v))e.location===`gpu-buffer`&&e.dispose();return ee}getPastKeyValues(e,t,n=!1){let r=Object.create(null);for(let i in e)if(i.startsWith(`present`)){let a=i.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present`,`past_key_values`),o=i.includes(`encoder`);if(o&&t?r[a]=t[a]:r[a]=e[i],t&&(!o||n)){let e=t[a];e.location===`gpu-buffer`&&e.dispose()}}return new dh(r)}getAttentions(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}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{let t=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,r=t?.config?.kv_cache_dtype??`float32`,i=r===`float16`?Xc.float16:Xc.float32,a=Sm(this.config,{batch_size:n});for(let t in a)e[t]=new W(r,new i(a[t].reduce((e,t)=>e*t,1)),a[t])}}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,ci(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 Eh(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Dh(e,ci(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 kh(e,o,!0)}async function Dh(e,t){let n=e.sessions.model,r=ci(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=xl(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=vl([e[0],e[2],e[3]])}return await J(n,r)}async function Oh(e,t){let n=await e.encode(t);return await e.decode(n)}async function kh(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=bh(!!i)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=Ph(a,i,[`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type)?1:0)),r.inputNames.includes(`num_logits_to_keep`)&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new W(`int64`,[0n],[])),e.addPastKeyValues(a,i),await J(r,ci(a,r.inputNames))}async function Ah(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,...f}){if(!c){c=await e.encode_text({input_ids:a,...f});let s=ci(f,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...f});({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=ll([vl([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}=f;[s]=e.get_rope_index(a,t,n,o)}return await kh(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d},!0)}async function jh(e,t){return await Ah(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 Mh(e,t){return await Ah(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 Nh(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;ee.dims[1]||i[e.at(-1)])),{...n,decoder_input_ids:yh(t)}}function Lh(e,...t){return e.config.is_encoder_decoder?Ih(e,...t):Fh(e,...t)}function Rh({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[r,await ec(e,t[r],!1,n)])))}var Hh={};Sr(Hh,{ASTForAudioClassification:()=>ag,ASTModel:()=>ig,ASTPreTrainedModel:()=>rg,AfmoeForCausalLM:()=>$h,AfmoeModel:()=>Qh,AfmoePreTrainedModel:()=>Zh,AlbertForMaskedLM:()=>qh,AlbertForQuestionAnswering:()=>Kh,AlbertForSequenceClassification:()=>Gh,AlbertModel:()=>Wh,AlbertPreTrainedModel:()=>Uh,ApertusForCausalLM:()=>Xh,ApertusModel:()=>Yh,ApertusPreTrainedModel:()=>Jh,ArceeForCausalLM:()=>ng,ArceeModel:()=>tg,ArceePreTrainedModel:()=>eg,BartForConditionalGeneration:()=>cg,BartForSequenceClassification:()=>lg,BartModel:()=>sg,BartPretrainedModel:()=>og,BeitForImageClassification:()=>fg,BeitModel:()=>dg,BeitPreTrainedModel:()=>ug,BertForMaskedLM:()=>hg,BertForQuestionAnswering:()=>vg,BertForSequenceClassification:()=>gg,BertForTokenClassification:()=>_g,BertModel:()=>mg,BertPreTrainedModel:()=>pg,BlenderbotForConditionalGeneration:()=>xg,BlenderbotModel:()=>bg,BlenderbotPreTrainedModel:()=>yg,BlenderbotSmallForConditionalGeneration:()=>wg,BlenderbotSmallModel:()=>Cg,BlenderbotSmallPreTrainedModel:()=>Sg,BloomForCausalLM:()=>Dg,BloomModel:()=>Eg,BloomPreTrainedModel:()=>Tg,CHMv2ForDepthEstimation:()=>Vg,CHMv2PreTrainedModel:()=>Bg,CLIPModel:()=>qg,CLIPPreTrainedModel:()=>Kg,CLIPSegForImageSegmentation:()=>e_,CLIPSegModel:()=>$g,CLIPSegPreTrainedModel:()=>Qg,CLIPTextModel:()=>Jg,CLIPTextModelWithProjection:()=>Yg,CLIPVisionModel:()=>Xg,CLIPVisionModelWithProjection:()=>Zg,CamembertForMaskedLM:()=>Ag,CamembertForQuestionAnswering:()=>Ng,CamembertForSequenceClassification:()=>jg,CamembertForTokenClassification:()=>Mg,CamembertModel:()=>kg,CamembertPreTrainedModel:()=>Og,ChatterboxModel:()=>Lg,ChatterboxPreTrainedModel:()=>Ig,ChineseCLIPModel:()=>zg,ChineseCLIPPreTrainedModel:()=>Rg,ClapAudioModelWithProjection:()=>Gg,ClapModel:()=>Ug,ClapPreTrainedModel:()=>Hg,ClapTextModelWithProjection:()=>Wg,CodeGenForCausalLM:()=>r_,CodeGenModel:()=>n_,CodeGenPreTrainedModel:()=>t_,Cohere2ForCausalLM:()=>l_,Cohere2Model:()=>c_,Cohere2PreTrainedModel:()=>s_,CohereAsrForConditionalGeneration:()=>f_,CohereAsrModel:()=>d_,CohereAsrPreTrainedModel:()=>u_,CohereForCausalLM:()=>o_,CohereModel:()=>a_,CoherePreTrainedModel:()=>i_,ConvBertForMaskedLM:()=>h_,ConvBertForQuestionAnswering:()=>v_,ConvBertForSequenceClassification:()=>g_,ConvBertForTokenClassification:()=>__,ConvBertModel:()=>m_,ConvBertPreTrainedModel:()=>p_,ConvNextForImageClassification:()=>x_,ConvNextModel:()=>b_,ConvNextPreTrainedModel:()=>y_,ConvNextV2ForImageClassification:()=>w_,ConvNextV2Model:()=>C_,ConvNextV2PreTrainedModel:()=>S_,DFineForObjectDetection:()=>j_,DFineModel:()=>A_,DFinePreTrainedModel:()=>k_,DINOv3ConvNextModel:()=>xv,DINOv3ConvNextPreTrainedModel:()=>bv,DINOv3ViTModel:()=>Cv,DINOv3ViTPreTrainedModel:()=>Sv,DPTForDepthEstimation:()=>Pv,DPTModel:()=>Nv,DPTPreTrainedModel:()=>Mv,DacDecoderModel:()=>L_,DacDecoderOutput:()=>N_,DacEncoderModel:()=>I_,DacEncoderOutput:()=>M_,DacModel:()=>F_,DacPreTrainedModel:()=>P_,DebertaForMaskedLM:()=>B_,DebertaForQuestionAnswering:()=>U_,DebertaForSequenceClassification:()=>V_,DebertaForTokenClassification:()=>H_,DebertaModel:()=>z_,DebertaPreTrainedModel:()=>R_,DebertaV2ForMaskedLM:()=>Y_,DebertaV2ForQuestionAnswering:()=>Q_,DebertaV2ForSequenceClassification:()=>X_,DebertaV2ForTokenClassification:()=>Z_,DebertaV2Model:()=>J_,DebertaV2PreTrainedModel:()=>q_,DecisionTransformerModel:()=>ev,DecisionTransformerPreTrainedModel:()=>$_,DeepseekV3ForCausalLM:()=>K_,DeepseekV3Model:()=>G_,DeepseekV3PreTrainedModel:()=>W_,DeiTForImageClassification:()=>rv,DeiTModel:()=>nv,DeiTPreTrainedModel:()=>tv,DepthAnythingForDepthEstimation:()=>av,DepthAnythingPreTrainedModel:()=>iv,DepthProForDepthEstimation:()=>sv,DepthProPreTrainedModel:()=>ov,DetrForObjectDetection:()=>uv,DetrForSegmentation:()=>dv,DetrModel:()=>lv,DetrObjectDetectionOutput:()=>fv,DetrPreTrainedModel:()=>cv,DetrSegmentationOutput:()=>pv,Dinov2ForImageClassification:()=>gv,Dinov2Model:()=>hv,Dinov2PreTrainedModel:()=>mv,Dinov2WithRegistersForImageClassification:()=>yv,Dinov2WithRegistersModel:()=>vv,Dinov2WithRegistersPreTrainedModel:()=>_v,DistilBertForMaskedLM:()=>kv,DistilBertForQuestionAnswering:()=>Ov,DistilBertForSequenceClassification:()=>Ev,DistilBertForTokenClassification:()=>Dv,DistilBertModel:()=>Tv,DistilBertPreTrainedModel:()=>wv,DonutSwinModel:()=>jv,DonutSwinPreTrainedModel:()=>Av,EdgeTamModel:()=>cT,EfficientNetForImageClassification:()=>Lv,EfficientNetModel:()=>Iv,EfficientNetPreTrainedModel:()=>Fv,ElectraForMaskedLM:()=>Bv,ElectraForQuestionAnswering:()=>Uv,ElectraForSequenceClassification:()=>Vv,ElectraForTokenClassification:()=>Hv,ElectraModel:()=>zv,ElectraPreTrainedModel:()=>Rv,Ernie4_5ForCausalLM:()=>Kv,Ernie4_5Model:()=>Gv,Ernie4_5PretrainedModel:()=>Wv,EsmForMaskedLM:()=>Yv,EsmForSequenceClassification:()=>Xv,EsmForTokenClassification:()=>Zv,EsmModel:()=>Jv,EsmPreTrainedModel:()=>qv,EuroBertForMaskedLM:()=>ey,EuroBertForSequenceClassification:()=>ty,EuroBertForTokenClassification:()=>ny,EuroBertModel:()=>$v,EuroBertPreTrainedModel:()=>Qv,ExaoneForCausalLM:()=>ay,ExaoneModel:()=>iy,ExaonePreTrainedModel:()=>ry,FalconForCausalLM:()=>cy,FalconH1ForCausalLM:()=>dy,FalconH1Model:()=>uy,FalconH1PreTrainedModel:()=>ly,FalconModel:()=>sy,FalconPreTrainedModel:()=>oy,FastViTForImageClassification:()=>my,FastViTModel:()=>py,FastViTPreTrainedModel:()=>fy,Florence2ForConditionalGeneration:()=>gy,Florence2PreTrainedModel:()=>hy,GLPNForDepthEstimation:()=>Xy,GLPNModel:()=>Yy,GLPNPreTrainedModel:()=>Jy,GPT2LMHeadModel:()=>db,GPT2Model:()=>ub,GPT2PreTrainedModel:()=>lb,GPTBigCodeForCausalLM:()=>$y,GPTBigCodeModel:()=>Qy,GPTBigCodePreTrainedModel:()=>Zy,GPTJForCausalLM:()=>mb,GPTJModel:()=>pb,GPTJPreTrainedModel:()=>fb,GPTNeoForCausalLM:()=>nb,GPTNeoModel:()=>tb,GPTNeoPreTrainedModel:()=>eb,GPTNeoXForCausalLM:()=>ab,GPTNeoXModel:()=>ib,GPTNeoXPreTrainedModel:()=>rb,Gemma2ForCausalLM:()=>Sy,Gemma2Model:()=>xy,Gemma2PreTrainedModel:()=>by,Gemma3ForCausalLM:()=>Ay,Gemma3ForConditionalGeneration:()=>ky,Gemma3Model:()=>Oy,Gemma3PreTrainedModel:()=>Dy,Gemma3nForCausalLM:()=>Ny,Gemma3nForConditionalGeneration:()=>My,Gemma3nPreTrainedModel:()=>jy,Gemma4ForCausalLM:()=>Fy,Gemma4ForConditionalGeneration:()=>Py,GemmaForCausalLM:()=>yy,GemmaModel:()=>vy,GemmaPreTrainedModel:()=>_y,GlmForCausalLM:()=>Ry,GlmModel:()=>Ly,GlmMoeDsaForCausalLM:()=>Vy,GlmMoeDsaModel:()=>By,GlmMoeDsaPreTrainedModel:()=>zy,GlmOcrForConditionalGeneration:()=>qy,GlmPreTrainedModel:()=>Iy,GptOssForCausalLM:()=>cb,GptOssModel:()=>sb,GptOssPreTrainedModel:()=>ob,GraniteForCausalLM:()=>_b,GraniteModel:()=>gb,GraniteMoeHybridForCausalLM:()=>bb,GraniteMoeHybridModel:()=>yb,GraniteMoeHybridPreTrainedModel:()=>vb,GranitePreTrainedModel:()=>hb,GraniteSpeechForConditionalGeneration:()=>Cb,GroundingDinoForObjectDetection:()=>Tb,GroundingDinoPreTrainedModel:()=>wb,GroupViTModel:()=>Db,GroupViTPreTrainedModel:()=>Eb,HeliumForCausalLM:()=>Ab,HeliumModel:()=>kb,HeliumPreTrainedModel:()=>Ob,HieraForImageClassification:()=>Nb,HieraModel:()=>Mb,HieraPreTrainedModel:()=>jb,HubertForCTC:()=>Vb,HubertForSequenceClassification:()=>Hb,HubertModel:()=>Bb,HubertPreTrainedModel:()=>zb,HunYuanDenseV1ForCausalLM:()=>Gb,HunYuanDenseV1Model:()=>Wb,HunYuanDenseV1PreTrainedModel:()=>Ub,IJepaForImageClassification:()=>Yb,IJepaModel:()=>Jb,IJepaPreTrainedModel:()=>qb,Idefics3ForConditionalGeneration:()=>Kb,JAISLMHeadModel:()=>Qb,JAISModel:()=>Zb,JAISPreTrainedModel:()=>Xb,JinaCLIPModel:()=>ex,JinaCLIPPreTrainedModel:()=>$b,JinaCLIPTextModel:()=>tx,JinaCLIPVisionModel:()=>nx,Lfm2ForCausalLM:()=>ax,Lfm2Model:()=>ix,Lfm2MoeForCausalLM:()=>lx,Lfm2MoeModel:()=>cx,Lfm2MoePreTrainedModel:()=>sx,Lfm2PreTrainedModel:()=>rx,Lfm2VlForConditionalGeneration:()=>ux,LightOnOcrForConditionalGeneration:()=>ox,LiteWhisperForConditionalGeneration:()=>gD,Llama4ForCausalLM:()=>hx,Llama4PreTrainedModel:()=>mx,LlamaForCausalLM:()=>px,LlamaModel:()=>fx,LlamaPreTrainedModel:()=>dx,LlavaForConditionalGeneration:()=>wy,LlavaOnevisionForConditionalGeneration:()=>wy,LlavaPreTrainedModel:()=>Cy,LlavaQwen2ForCausalLM:()=>Ey,LongT5ForConditionalGeneration:()=>vx,LongT5Model:()=>_x,LongT5PreTrainedModel:()=>gx,M2M100ForConditionalGeneration:()=>xx,M2M100Model:()=>bx,M2M100PreTrainedModel:()=>yx,MBartForCausalLM:()=>Mx,MBartForConditionalGeneration:()=>Ax,MBartForSequenceClassification:()=>jx,MBartModel:()=>kx,MBartPreTrainedModel:()=>Ox,MPNetForMaskedLM:()=>VS,MPNetForQuestionAnswering:()=>WS,MPNetForSequenceClassification:()=>HS,MPNetForTokenClassification:()=>US,MPNetModel:()=>BS,MPNetPreTrainedModel:()=>zS,MT5ForConditionalGeneration:()=>XS,MT5Model:()=>YS,MT5PreTrainedModel:()=>JS,MarianMTModel:()=>wx,MarianModel:()=>Cx,MarianPreTrainedModel:()=>Sx,MaskFormerForInstanceSegmentation:()=>Dx,MaskFormerModel:()=>Ex,MaskFormerPreTrainedModel:()=>Tx,Metric3DForDepthEstimation:()=>Px,Metric3DPreTrainedModel:()=>Nx,Metric3Dv2ForDepthEstimation:()=>Ix,Metric3Dv2PreTrainedModel:()=>Fx,MgpstrForSceneTextRecognition:()=>zx,MgpstrModelOutput:()=>Lx,MgpstrPreTrainedModel:()=>Rx,MimiDecoderModel:()=>Gx,MimiDecoderOutput:()=>Vx,MimiEncoderModel:()=>Wx,MimiEncoderOutput:()=>Bx,MimiModel:()=>Ux,MimiPreTrainedModel:()=>Hx,Mistral4ForCausalLM:()=>Zx,Mistral4Model:()=>Xx,Mistral4PreTrainedModel:()=>Yx,MistralForCausalLM:()=>Jx,MistralModel:()=>qx,MistralPreTrainedModel:()=>Kx,MobileBertForMaskedLM:()=>eS,MobileBertForQuestionAnswering:()=>nS,MobileBertForSequenceClassification:()=>tS,MobileBertModel:()=>$x,MobileBertPreTrainedModel:()=>Qx,MobileLLMForCausalLM:()=>aS,MobileLLMModel:()=>iS,MobileLLMPreTrainedModel:()=>rS,MobileNetV1ForImageClassification:()=>cS,MobileNetV1ForSemanticSegmentation:()=>lS,MobileNetV1Model:()=>sS,MobileNetV1PreTrainedModel:()=>oS,MobileNetV2ForImageClassification:()=>fS,MobileNetV2ForSemanticSegmentation:()=>pS,MobileNetV2Model:()=>dS,MobileNetV2PreTrainedModel:()=>uS,MobileNetV3ForImageClassification:()=>gS,MobileNetV3ForSemanticSegmentation:()=>_S,MobileNetV3Model:()=>hS,MobileNetV3PreTrainedModel:()=>mS,MobileNetV4ForImageClassification:()=>bS,MobileNetV4ForSemanticSegmentation:()=>xS,MobileNetV4Model:()=>yS,MobileNetV4PreTrainedModel:()=>vS,MobileViTForImageClassification:()=>wS,MobileViTModel:()=>CS,MobileViTPreTrainedModel:()=>SS,MobileViTV2ForImageClassification:()=>DS,MobileViTV2Model:()=>ES,MobileViTV2PreTrainedModel:()=>TS,ModernBertDecoderForCausalLM:()=>FS,ModernBertDecoderModel:()=>PS,ModernBertDecoderPreTrainedModel:()=>NS,ModernBertForMaskedLM:()=>AS,ModernBertForSequenceClassification:()=>jS,ModernBertForTokenClassification:()=>MS,ModernBertModel:()=>kS,ModernBertPreTrainedModel:()=>OS,Moondream1ForConditionalGeneration:()=>Ty,MoonshineForConditionalGeneration:()=>RS,MoonshineModel:()=>LS,MoonshinePreTrainedModel:()=>IS,MptForCausalLM:()=>qS,MptModel:()=>KS,MptPreTrainedModel:()=>GS,MultiModalityCausalLM:()=>QS,MultiModalityPreTrainedModel:()=>ZS,MusicgenForCausalLM:()=>tC,MusicgenForConditionalGeneration:()=>nC,MusicgenModel:()=>eC,MusicgenPreTrainedModel:()=>$S,NanoChatForCausalLM:()=>aC,NanoChatModel:()=>iC,NanoChatPreTrainedModel:()=>rC,NemotronHForCausalLM:()=>cC,NemotronHModel:()=>sC,NemotronHPreTrainedModel:()=>oC,NeoBertForMaskedLM:()=>dC,NeoBertForQuestionAnswering:()=>mC,NeoBertForSequenceClassification:()=>fC,NeoBertForTokenClassification:()=>pC,NeoBertModel:()=>uC,NeoBertPreTrainedModel:()=>lC,NomicBertModel:()=>gC,NomicBertPreTrainedModel:()=>hC,OPTForCausalLM:()=>PC,OPTModel:()=>NC,OPTPreTrainedModel:()=>MC,Olmo2ForCausalLM:()=>SC,Olmo2Model:()=>xC,Olmo2PreTrainedModel:()=>bC,Olmo3ForCausalLM:()=>TC,Olmo3Model:()=>wC,Olmo3PreTrainedModel:()=>CC,OlmoForCausalLM:()=>yC,OlmoHybridForCausalLM:()=>OC,OlmoHybridModel:()=>DC,OlmoHybridPreTrainedModel:()=>EC,OlmoModel:()=>vC,OlmoPreTrainedModel:()=>_C,OpenELMForCausalLM:()=>jC,OpenELMModel:()=>AC,OpenELMPreTrainedModel:()=>kC,OwlViTForObjectDetection:()=>BC,OwlViTModel:()=>zC,OwlViTPreTrainedModel:()=>RC,Owlv2ForObjectDetection:()=>LC,Owlv2Model:()=>IC,Owlv2PreTrainedModel:()=>FC,PaliGemmaForConditionalGeneration:()=>VC,ParakeetForCTC:()=>UC,ParakeetPreTrainedModel:()=>HC,PatchTSMixerForPrediction:()=>KC,PatchTSMixerModel:()=>GC,PatchTSMixerPreTrainedModel:()=>WC,PatchTSTForPrediction:()=>YC,PatchTSTModel:()=>JC,PatchTSTPreTrainedModel:()=>qC,Phi3ForCausalLM:()=>tw,Phi3Model:()=>ew,Phi3PreTrainedModel:()=>$C,Phi3VForCausalLM:()=>rw,Phi3VPreTrainedModel:()=>nw,PhiForCausalLM:()=>QC,PhiModel:()=>ZC,PhiPreTrainedModel:()=>XC,PreTrainedModel:()=>Z,PvtForImageClassification:()=>ow,PvtModel:()=>aw,PvtPreTrainedModel:()=>iw,PyAnnoteForAudioFrameClassification:()=>lw,PyAnnoteModel:()=>cw,PyAnnotePreTrainedModel:()=>sw,Qwen2ForCausalLM:()=>fw,Qwen2Model:()=>dw,Qwen2MoeForCausalLM:()=>hw,Qwen2MoeModel:()=>mw,Qwen2MoePreTrainedModel:()=>pw,Qwen2PreTrainedModel:()=>uw,Qwen2VLForCausalLM:()=>Wy,Qwen2VLForConditionalGeneration:()=>Uy,Qwen2VLPreTrainedModel:()=>Hy,Qwen2_5_VLForCausalLM:()=>Ky,Qwen2_5_VLForConditionalGeneration:()=>Gy,Qwen3ForCausalLM:()=>vw,Qwen3Model:()=>_w,Qwen3MoeForCausalLM:()=>xw,Qwen3MoeModel:()=>bw,Qwen3MoePreTrainedModel:()=>yw,Qwen3NextForCausalLM:()=>ww,Qwen3NextModel:()=>Cw,Qwen3NextPreTrainedModel:()=>Sw,Qwen3PreTrainedModel:()=>gw,Qwen3VLForCausalLM:()=>Ew,Qwen3VLForConditionalGeneration:()=>Tw,Qwen3VLMoeForCausalLM:()=>Ow,Qwen3VLMoeForConditionalGeneration:()=>Dw,Qwen3_5ForCausalLM:()=>Aw,Qwen3_5ForConditionalGeneration:()=>kw,Qwen3_5MoeForCausalLM:()=>Mw,Qwen3_5MoeForConditionalGeneration:()=>jw,RFDetrForObjectDetection:()=>Rw,RFDetrModel:()=>Lw,RFDetrObjectDetectionOutput:()=>zw,RFDetrPreTrainedModel:()=>Iw,RTDetrForObjectDetection:()=>D_,RTDetrModel:()=>E_,RTDetrObjectDetectionOutput:()=>O_,RTDetrPreTrainedModel:()=>T_,RTDetrV2ForObjectDetection:()=>eT,RTDetrV2Model:()=>$w,RTDetrV2ObjectDetectionOutput:()=>tT,RTDetrV2PreTrainedModel:()=>Qw,ResNetForImageClassification:()=>Fw,ResNetModel:()=>Pw,ResNetPreTrainedModel:()=>Nw,RoFormerForMaskedLM:()=>Jw,RoFormerForQuestionAnswering:()=>Zw,RoFormerForSequenceClassification:()=>Yw,RoFormerForTokenClassification:()=>Xw,RoFormerModel:()=>qw,RoFormerPreTrainedModel:()=>Kw,RobertaForMaskedLM:()=>Hw,RobertaForQuestionAnswering:()=>Gw,RobertaForSequenceClassification:()=>Uw,RobertaForTokenClassification:()=>Ww,RobertaModel:()=>Vw,RobertaPreTrainedModel:()=>Bw,Sam2ImageSegmentationOutput:()=>aT,Sam2Model:()=>sT,Sam2PreTrainedModel:()=>oT,Sam3TrackerModel:()=>lT,SamImageSegmentationOutput:()=>nT,SamModel:()=>iT,SamPreTrainedModel:()=>rT,SapiensForDepthEstimation:()=>fT,SapiensForNormalEstimation:()=>pT,SapiensForSemanticSegmentation:()=>dT,SapiensPreTrainedModel:()=>uT,SegformerForImageClassification:()=>gT,SegformerForSemanticSegmentation:()=>_T,SegformerModel:()=>hT,SegformerPreTrainedModel:()=>mT,SiglipModel:()=>yT,SiglipPreTrainedModel:()=>vT,SiglipTextModel:()=>bT,SiglipVisionModel:()=>xT,SmolLM3ForCausalLM:()=>wT,SmolLM3Model:()=>CT,SmolLM3PreTrainedModel:()=>ST,SnacDecoderModel:()=>OT,SnacEncoderModel:()=>DT,SnacModel:()=>ET,SnacPreTrainedModel:()=>TT,SolarOpenForCausalLM:()=>jT,SolarOpenModel:()=>AT,SolarOpenPreTrainedModel:()=>kT,SpeechT5ForSpeechToText:()=>PT,SpeechT5ForTextToSpeech:()=>FT,SpeechT5HifiGan:()=>IT,SpeechT5Model:()=>NT,SpeechT5PreTrainedModel:()=>MT,SqueezeBertForMaskedLM:()=>zT,SqueezeBertForQuestionAnswering:()=>VT,SqueezeBertForSequenceClassification:()=>BT,SqueezeBertModel:()=>RT,SqueezeBertPreTrainedModel:()=>LT,StableLmForCausalLM:()=>WT,StableLmModel:()=>UT,StableLmPreTrainedModel:()=>HT,Starcoder2ForCausalLM:()=>qT,Starcoder2Model:()=>KT,Starcoder2PreTrainedModel:()=>GT,StyleTextToSpeech2Model:()=>YT,StyleTextToSpeech2PreTrainedModel:()=>JT,SupertonicForConditionalGeneration:()=>ZT,SupertonicPreTrainedModel:()=>XT,Swin2SRForImageSuperResolution:()=>iE,Swin2SRModel:()=>rE,Swin2SRPreTrainedModel:()=>nE,SwinForImageClassification:()=>eE,SwinForSemanticSegmentation:()=>tE,SwinModel:()=>$T,SwinPreTrainedModel:()=>QT,T5ForConditionalGeneration:()=>sE,T5Model:()=>oE,T5PreTrainedModel:()=>aE,TableTransformerForObjectDetection:()=>uE,TableTransformerModel:()=>lE,TableTransformerObjectDetectionOutput:()=>dE,TableTransformerPreTrainedModel:()=>cE,TrOCRForCausalLM:()=>pE,TrOCRPreTrainedModel:()=>fE,UltravoxModel:()=>Sb,UltravoxPreTrainedModel:()=>xb,UniSpeechForCTC:()=>gE,UniSpeechForSequenceClassification:()=>_E,UniSpeechModel:()=>hE,UniSpeechPreTrainedModel:()=>mE,UniSpeechSatForAudioFrameClassification:()=>SE,UniSpeechSatForCTC:()=>bE,UniSpeechSatForSequenceClassification:()=>xE,UniSpeechSatModel:()=>yE,UniSpeechSatPreTrainedModel:()=>vE,VaultGemmaForCausalLM:()=>TE,VaultGemmaModel:()=>wE,VaultGemmaPreTrainedModel:()=>CE,ViTForImageClassification:()=>kE,ViTMAEModel:()=>jE,ViTMAEPreTrainedModel:()=>AE,ViTMSNForImageClassification:()=>PE,ViTMSNModel:()=>NE,ViTMSNPreTrainedModel:()=>ME,ViTModel:()=>OE,ViTPreTrainedModel:()=>DE,VisionEncoderDecoderModel:()=>EE,VitMatteForImageMatting:()=>IE,VitMattePreTrainedModel:()=>FE,VitPoseForPoseEstimation:()=>RE,VitPosePreTrainedModel:()=>LE,VitsModel:()=>VE,VitsModelOutput:()=>zE,VitsPreTrainedModel:()=>BE,VoxtralForConditionalGeneration:()=>HE,VoxtralRealtimeForConditionalGeneration:()=>QE,VoxtralRealtimePreTrainedModel:()=>ZE,Wav2Vec2BertForCTC:()=>tD,Wav2Vec2BertForSequenceClassification:()=>nD,Wav2Vec2BertModel:()=>eD,Wav2Vec2BertPreTrainedModel:()=>$E,Wav2Vec2ForAudioFrameClassification:()=>Rb,Wav2Vec2ForCTC:()=>Ib,Wav2Vec2ForSequenceClassification:()=>Lb,Wav2Vec2Model:()=>Fb,Wav2Vec2PreTrainedModel:()=>Pb,WavLMForAudioFrameClassification:()=>lD,WavLMForCTC:()=>oD,WavLMForSequenceClassification:()=>sD,WavLMForXVector:()=>cD,WavLMModel:()=>aD,WavLMPreTrainedModel:()=>iD,WeSpeakerResNetModel:()=>dD,WeSpeakerResNetPreTrainedModel:()=>uD,WhisperForConditionalGeneration:()=>hD,WhisperModel:()=>mD,WhisperPreTrainedModel:()=>pD,XLMForQuestionAnswering:()=>SD,XLMForSequenceClassification:()=>bD,XLMForTokenClassification:()=>xD,XLMModel:()=>vD,XLMPreTrainedModel:()=>_D,XLMRobertaForMaskedLM:()=>TD,XLMRobertaForQuestionAnswering:()=>OD,XLMRobertaForSequenceClassification:()=>ED,XLMRobertaForTokenClassification:()=>DD,XLMRobertaModel:()=>wD,XLMRobertaPreTrainedModel:()=>CD,XLMWithLMHeadModel:()=>yD,XVectorOutput:()=>rD,YolosForObjectDetection:()=>jD,YolosModel:()=>AD,YolosObjectDetectionOutput:()=>MD,YolosPreTrainedModel:()=>kD,YoutuForCausalLM:()=>FD,YoutuModel:()=>PD,YoutuPreTrainedModel:()=>ND});var Uh=class extends Z{},Wh=class extends Uh{},Gh=class extends Uh{async _call(e){return new Y(await super._call(e))}},Kh=class extends Uh{async _call(e){return new Lm(await super._call(e))}},qh=class extends Uh{async _call(e){return new Im(await super._call(e))}},Jh=class extends Z{},Yh=class extends Jh{},Xh=class extends Jh{},Zh=class extends Z{},Qh=class extends Zh{},$h=class extends Zh{},eg=class extends Z{},tg=class extends eg{},ng=class extends eg{},rg=class extends Z{},ig=class extends rg{},ag=class extends rg{},og=class extends Z{},sg=class extends og{},cg=class extends og{},lg=class extends og{async _call(e){return new Y(await super._call(e))}},ug=class extends Z{},dg=class extends ug{},fg=class extends ug{async _call(e){return new Y(await super._call(e))}},pg=class extends Z{},mg=class extends pg{},hg=class extends pg{async _call(e){return new Im(await super._call(e))}},gg=class extends pg{async _call(e){return new Y(await super._call(e))}},_g=class extends pg{async _call(e){return new Fm(await super._call(e))}},vg=class extends pg{async _call(e){return new Lm(await super._call(e))}},yg=class extends Z{},bg=class extends yg{},xg=class extends yg{},Sg=class extends Z{},Cg=class extends Sg{},wg=class extends Sg{},Tg=class extends Z{},Eg=class extends Tg{},Dg=class extends Tg{},Og=class extends Z{},kg=class extends Og{},Ag=class extends Og{async _call(e){return new Im(await super._call(e))}},jg=class extends Og{async _call(e){return new Y(await super._call(e))}},Mg=class extends Og{async _call(e){return new Fm(await super._call(e))}},Ng=class extends Og{async _call(e){return new Lm(await super._call(e))}},Pg=4299n,Fg=6561n,Ig=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`]},Lg=class extends Ig{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,audio_features:l=null,audio_tokens:u=null,speaker_embeddings:d=null,speaker_features:f=null,...p}){let m;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof W)){let t=e.dims[0];if(r==null)r=gl([t],.5);else if(typeof r==`number`)r=gl([t],r);else if(Array.isArray(r))r=new W(`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),l&&u&&d&&f&&(m={audio_features:l,audio_tokens:u,speaker_embeddings:d,speaker_features:f}),m||n)m??=await this.encode_speech(n),a=ll([m.audio_features,a],1),t=vl([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=vl([a.dims[0],n+e])}}return{...await kh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c},!1),...m}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.input_ids.dims[1]===1?t.position_ids=new W(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==Fg)-1),[e.length,1]):t.position_ids=new W(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=Fg?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),Fh(this,e,t,n)}async generate(e){let{sequences:t,audio_tokens:n,speaker_embeddings:r,speaker_features:i}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=ll([n,a,gl([a.dims[0],3],Pg)],1),{waveform:s}=await J(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:i,speaker_embeddings:r});return s}},Rg=class extends Z{},zg=class extends Rg{},Bg=class extends Z{},Vg=class extends Bg{},Hg=class extends Z{},Ug=class extends Hg{},Wg=class extends Hg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Gg=class extends Hg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},Kg=class extends Z{},qg=class extends Kg{},Jg=class extends Kg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Yg=class extends Kg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Xg=class extends Kg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},Zg=class extends Kg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},Qg=class extends Z{},$g=class extends Qg{},e_=class extends Qg{},t_=class extends Z{},n_=class extends t_{},r_=class extends t_{},i_=class extends Z{},a_=class extends i_{},o_=class extends i_{},s_=class extends Z{},c_=class extends s_{},l_=class extends s_{},u_=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`]},d_=class extends u_{},f_=class extends u_{},p_=class extends Z{},m_=class extends p_{},h_=class extends p_{async _call(e){return new Im(await super._call(e))}},g_=class extends p_{async _call(e){return new Y(await super._call(e))}},__=class extends p_{async _call(e){return new Fm(await super._call(e))}},v_=class extends p_{async _call(e){return new Lm(await super._call(e))}},y_=class extends Z{},b_=class extends y_{},x_=class extends y_{async _call(e){return new Y(await super._call(e))}},S_=class extends Z{},C_=class extends S_{},w_=class extends S_{async _call(e){return new Y(await super._call(e))}},T_=class extends Z{},E_=class extends T_{},D_=class extends T_{async _call(e){return new O_(await super._call(e))}},O_=class extends Pm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},k_=class extends Z{},A_=class extends k_{},j_=class extends k_{async _call(e){return new O_(await super._call(e))}},M_=class extends Pm{constructor({audio_codes:e}){super(),this.audio_codes=e}},N_=class extends Pm{constructor({audio_values:e}){super(),this.audio_values=e}},P_=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},F_=class extends P_{async encode(e){return new M_(await J(this.sessions.encoder_model,e))}async decode(e){return new N_(await J(this.sessions.decoder_model,e))}},I_=class extends P_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},L_=class extends P_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},R_=class extends Z{},z_=class extends R_{},B_=class extends R_{async _call(e){return new Im(await super._call(e))}},V_=class extends R_{async _call(e){return new Y(await super._call(e))}},H_=class extends R_{async _call(e){return new Fm(await super._call(e))}},U_=class extends R_{async _call(e){return new Lm(await super._call(e))}},W_=class extends Z{},G_=class extends W_{},K_=class extends W_{},q_=class extends Z{},J_=class extends q_{},Y_=class extends q_{async _call(e){return new Im(await super._call(e))}},X_=class extends q_{async _call(e){return new Y(await super._call(e))}},Z_=class extends q_{async _call(e){return new Fm(await super._call(e))}},Q_=class extends q_{async _call(e){return new Lm(await super._call(e))}},$_=class extends Z{},ev=class extends $_{},tv=class extends Z{},nv=class extends tv{},rv=class extends tv{async _call(e){return new Y(await super._call(e))}},iv=class extends Z{},av=class extends iv{},ov=class extends Z{},sv=class extends ov{},cv=class extends Z{},lv=class extends cv{},uv=class extends cv{async _call(e){return new fv(await super._call(e))}},dv=class extends cv{async _call(e){return new pv(await super._call(e))}},fv=class extends Pm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},pv=class extends Pm{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},mv=class extends Z{},hv=class extends mv{},gv=class extends mv{async _call(e){return new Y(await super._call(e))}},_v=class extends Z{},vv=class extends _v{},yv=class extends _v{async _call(e){return new Y(await super._call(e))}},bv=class extends Z{},xv=class extends bv{},Sv=class extends Z{},Cv=class extends Sv{},wv=class extends Z{},Tv=class extends wv{},Ev=class extends wv{async _call(e){return new Y(await super._call(e))}},Dv=class extends wv{async _call(e){return new Fm(await super._call(e))}},Ov=class extends wv{async _call(e){return new Lm(await super._call(e))}},kv=class extends wv{async _call(e){return new Im(await super._call(e))}},Av=class extends Z{},jv=class extends Av{},Mv=class extends Z{},Nv=class extends Mv{},Pv=class extends Mv{},Fv=class extends Z{},Iv=class extends Fv{},Lv=class extends Fv{async _call(e){return new Y(await super._call(e))}},Rv=class extends Z{},zv=class extends Rv{},Bv=class extends Rv{async _call(e){return new Im(await super._call(e))}},Vv=class extends Rv{async _call(e){return new Y(await super._call(e))}},Hv=class extends Rv{async _call(e){return new Fm(await super._call(e))}},Uv=class extends Rv{async _call(e){return new Lm(await super._call(e))}},Wv=class extends Z{},Gv=class extends Wv{},Kv=class extends Wv{},qv=class extends Z{},Jv=class extends qv{},Yv=class extends qv{async _call(e){return new Im(await super._call(e))}},Xv=class extends qv{async _call(e){return new Y(await super._call(e))}},Zv=class extends qv{async _call(e){return new Fm(await super._call(e))}},Qv=class extends Z{},$v=class extends Qv{},ey=class extends Qv{async _call(e){return new Im(await super._call(e))}},ty=class extends Qv{async _call(e){return new Y(await super._call(e))}},ny=class extends Qv{async _call(e){return new Fm(await super._call(e))}},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 Z{},py=class extends fy{},my=class extends fy{async _call(e){return new Y(await super._call(e))}},hy=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`},gy=class extends hy{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:ll([t,e],1),attention_mask:ll([vl(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}){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 Dh(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})}return await kh(this,{inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o},!0)}},_y=class extends Z{},vy=class extends _y{},yy=class extends _y{},by=class extends Z{},xy=class extends by{},Sy=class extends by{},Cy=class extends Z{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},wy=class extends Cy{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return zh({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},Ty=class extends wy{},Ey=class extends wy{},Dy=class extends Z{},Oy=class extends Dy{},ky=class extends wy{},Ay=class extends ky{},jy=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`]},My=class extends jy{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,...d}){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,...d});({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 kh(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u},!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 zh({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 Bh({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},Ny=class extends My{},Py=class extends My{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})}},Fy=class extends Py{},Iy=class extends Z{},Ly=class extends Iy{},Ry=class extends Iy{},zy=class extends Z{},By=class extends zy{},Vy=class extends zy{},Hy=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},Uy=class extends Hy{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=Nh(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>oc(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new W(`int64`,r,[3,...n]),new W(`int64`,i,[i.length,1])]}else{let[t,n]=e.dims;return[new W(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),bl([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==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;et>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;l0?oc(f.at(-1))[0]+1:0;f.push(Array.from({length:3*ee},(e,t)=>S+t%ee));let te=ee+S,C=y*b*x,w=Array.from({length:C},(e,t)=>te+Math.floor(t/(b*x))),ne=Array.from({length:C},(e,t)=>te+Math.floor(t/x)%b),re=Array.from({length:C},(e,t)=>te+t%x);f.push([w,ne,re].flat()),p=d+C}if(p0?oc(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||=yl(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;eo[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(oc(r)[0]+1-i[e].length)}return[new W(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new W(`int64`,d,[d.length,1])]}else 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 zh({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(en+e);t.position_ids=ul([r,r,r],0)}}return t}},Wy=class extends Uy{},Gy=class extends Uy{image_grid_thw_name=`image_grid_thw`},Ky=class extends Wy{image_grid_thw_name=`image_grid_thw`},qy=class extends Gy{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?1:0;for(let t=1;t<=e.length;++t){let n=tl+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}},Jy=class extends Z{},Yy=class extends Jy{},Xy=class extends Jy{},Zy=class extends Z{},Qy=class extends Zy{},$y=class extends Zy{},eb=class extends Z{},tb=class extends eb{},nb=class extends eb{},rb=class extends Z{},ib=class extends rb{},ab=class extends rb{},ob=class extends Z{},sb=class extends ob{},cb=class extends ob{},lb=class extends Z{},ub=class extends lb{},db=class extends lb{},fb=class extends Z{},pb=class extends fb{},mb=class extends fb{},hb=class extends Z{},gb=class extends hb{},_b=class extends hb{},vb=class extends Z{},yb=class extends vb{},bb=class extends vb{},xb=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},Sb=class extends xb{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return Bh({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},Cb=class extends Sb{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},wb=class extends Z{},Tb=class extends wb{},Eb=class extends Z{},Db=class extends Eb{},Ob=class extends Z{},kb=class extends Ob{},Ab=class extends Ob{},jb=class extends Z{},Mb=class extends jb{},Nb=class extends jb{async _call(e){return new Y(await super._call(e))}},Pb=class extends Z{},Fb=class extends Pb{},Ib=class extends Pb{async _call(e){return new Rm(await super._call(e))}},Lb=class extends Pb{async _call(e){return new Y(await super._call(e))}},Rb=class extends Pb{async _call(e){return new Fm(await super._call(e))}},zb=class extends Z{},Bb=class extends Pb{},Vb=class extends Pb{async _call(e){return new Rm(await super._call(e))}},Hb=class extends Pb{async _call(e){return new Y(await super._call(e))}},Ub=class extends Z{},Wb=class extends Ub{},Gb=class extends Ub{},Kb=class extends wy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},qb=class extends Z{},Jb=class extends qb{},Yb=class extends qb{async _call(e){return new Y(await super._call(e))}},Xb=class extends Z{},Zb=class extends Xb{},Qb=class extends Xb{},$b=class extends Z{},ex=class extends $b{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=vl([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=gl([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}},tx=class extends $b{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},nx=class extends $b{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},rx=class extends Z{},ix=class extends rx{},ax=class extends rx{},ox=class extends wy{},sx=class extends Z{},cx=class extends sx{},lx=class extends sx{},ux=class extends wy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},dx=class extends Z{},fx=class extends dx{},px=class extends dx{},mx=class extends Z{},hx=class extends mx{},gx=class extends Z{},_x=class extends gx{},vx=class extends gx{},yx=class extends Z{},bx=class extends yx{},xx=class extends yx{},Sx=class extends Z{},Cx=class extends Sx{},wx=class extends Sx{},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 Ox{async _call(e){return new Y(await super._call(e))}},Mx=class extends Ox{},Nx=class extends Z{},Px=class extends Nx{},Fx=class extends Z{},Ix=class extends Fx{},Lx=class extends Pm{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]}},Rx=class extends Z{},zx=class extends Rx{async _call(e){return new Lx(await super._call(e))}},Bx=class extends Pm{constructor({audio_codes:e}){super(),this.audio_codes=e}},Vx=class extends Pm{constructor({audio_values:e}){super(),this.audio_values=e}},Hx=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},Ux=class extends Hx{async encode(e){return new Bx(await J(this.sessions.encoder_model,e))}async decode(e){return new Vx(await J(this.sessions.decoder_model,e))}},Wx=class extends Hx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},Gx=class extends Hx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},Kx=class extends Z{},qx=class extends Kx{},Jx=class extends Kx{},Yx=class extends Z{},Xx=class extends Yx{},Zx=class extends Yx{},Qx=class extends Z{},$x=class extends Qx{},eS=class extends Qx{async _call(e){return new Im(await super._call(e))}},tS=class extends Qx{async _call(e){return new Y(await super._call(e))}},nS=class extends Qx{async _call(e){return new Lm(await super._call(e))}},rS=class extends Z{},iS=class extends rS{},aS=class extends rS{},oS=class extends Z{},sS=class extends oS{},cS=class extends oS{async _call(e){return new Y(await super._call(e))}},lS=class extends oS{},uS=class extends Z{},dS=class extends uS{},fS=class extends uS{async _call(e){return new Y(await super._call(e))}},pS=class extends uS{},mS=class extends Z{},hS=class extends mS{},gS=class extends mS{async _call(e){return new Y(await super._call(e))}},_S=class extends mS{},vS=class extends Z{},yS=class extends vS{},bS=class extends vS{async _call(e){return new Y(await super._call(e))}},xS=class extends vS{},SS=class extends Z{},CS=class extends SS{},wS=class extends SS{async _call(e){return new Y(await super._call(e))}},TS=class extends Z{},ES=class extends TS{},DS=class extends TS{async _call(e){return new Y(await super._call(e))}},OS=class extends Z{},kS=class extends OS{},AS=class extends OS{async _call(e){return new Im(await super._call(e))}},jS=class extends OS{async _call(e){return new Y(await super._call(e))}},MS=class extends OS{async _call(e){return new Fm(await super._call(e))}},NS=class extends Z{},PS=class extends NS{},FS=class extends NS{},IS=class extends Z{requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},LS=class extends IS{},RS=class extends IS{},zS=class extends Z{},BS=class extends zS{},VS=class extends zS{async _call(e){return new Im(await super._call(e))}},HS=class extends zS{async _call(e){return new Y(await super._call(e))}},US=class extends zS{async _call(e){return new Fm(await super._call(e))}},WS=class extends zS{async _call(e){return new Lm(await super._call(e))}},GS=class extends Z{},KS=class extends GS{},qS=class extends GS{},JS=class extends Z{},YS=class extends JS{},XS=class extends JS{},ZS=class extends Z{},QS=class extends ZS{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,ci(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await J(t,ci({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await kh(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,ci(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=ll([t.input_ids,t.input_ids],0):(t.input_ids=ll([t.input_ids,_l(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=ll([t.attention_mask,_l(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=gl([0,0,3,384,384],1)),r&&(t.images_seq_mask=new W(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new W(`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]),r=this.sessions.image_decode,{decoded_image:i}=await J(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=Bd.fromTensor(e);o.push(t)}return o}},$S=class extends Z{},eC=class extends $S{},tC=class extends $S{},nC=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;t0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new W(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=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),Ih(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}},rC=class extends Z{},iC=class extends rC{},aC=class extends rC{},oC=class extends Z{},sC=class extends oC{},cC=class extends oC{},lC=class extends Z{},uC=class extends lC{},dC=class extends lC{async _call(e){return new Im(await super._call(e))}},fC=class extends lC{async _call(e){return new Y(await super._call(e))}},pC=class extends lC{async _call(e){return new Fm(await super._call(e))}},mC=class extends lC{async _call(e){return new Lm(await super._call(e))}},hC=class extends Z{},gC=class extends hC{},_C=class extends Z{},vC=class extends _C{},yC=class extends _C{},bC=class extends Z{},xC=class extends bC{},SC=class extends bC{},CC=class extends Z{},wC=class extends CC{},TC=class extends CC{},EC=class extends Z{},DC=class extends EC{},OC=class extends EC{},kC=class extends Z{},AC=class extends kC{},jC=class extends kC{},MC=class extends Z{},NC=class extends MC{},PC=class extends MC{},FC=class extends Z{},IC=class extends FC{},LC=class extends FC{},RC=class extends Z{},zC=class extends RC{},BC=class extends RC{},VC=class extends wy{},HC=class extends Z{},UC=class extends HC{async _call(e){return new Rm(await super._call(e))}},WC=class extends Z{},GC=class extends WC{},KC=class extends WC{},qC=class extends Z{},JC=class extends qC{},YC=class extends qC{},XC=class extends Z{},ZC=class extends XC{},QC=class extends XC{},$C=class extends Z{},ew=class extends $C{},tw=class extends $C{},nw=class extends Z{forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},rw=class extends nw{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,...l}){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{let e=this.config.normalized_config.hidden_size;t=new W(`float32`,[],[0,e])}({inputs_embeds:a}=await J(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await kh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c},!1)}},iw=class extends Z{},aw=class extends iw{},ow=class extends iw{async _call(e){return new Y(await super._call(e))}},sw=class extends Z{},cw=class extends sw{},lw=class extends sw{async _call(e){return new Fm(await super._call(e))}},uw=class extends Z{},dw=class extends uw{},fw=class extends uw{},pw=class extends Z{},mw=class extends pw{},hw=class extends pw{},gw=class extends Z{},_w=class extends gw{},vw=class extends gw{},yw=class extends Z{},bw=class extends yw{},xw=class extends yw{},Sw=class extends Z{},Cw=class extends Sw{},ww=class extends Sw{},Tw=class extends Gy{},Ew=class extends Ky{},Dw=class extends Tw{},Ow=class extends Ew{},kw=class extends Tw{},Aw=class extends kw{},jw=class extends kw{},Mw=class extends Aw{},Nw=class extends Z{},Pw=class extends Nw{},Fw=class extends Nw{async _call(e){return new Y(await super._call(e))}},Iw=class extends Z{},Lw=class extends Iw{},Rw=class extends Iw{async _call(e){return new zw(await super._call(e))}},zw=class extends O_{},Bw=class extends Z{},Vw=class extends Bw{},Hw=class extends Bw{async _call(e){return new Im(await super._call(e))}},Uw=class extends Bw{async _call(e){return new Y(await super._call(e))}},Ww=class extends Bw{async _call(e){return new Fm(await super._call(e))}},Gw=class extends Bw{async _call(e){return new Lm(await super._call(e))}},Kw=class extends Z{},qw=class extends Kw{},Jw=class extends Kw{async _call(e){return new Im(await super._call(e))}},Yw=class extends Kw{async _call(e){return new Y(await super._call(e))}},Xw=class extends Kw{async _call(e){return new Fm(await super._call(e))}},Zw=class extends Kw{async _call(e){return new Lm(await super._call(e))}},Qw=class extends Z{},$w=class extends Qw{},eT=class extends Qw{async _call(e){return new tT(await super._call(e))}},tT=class extends O_{},nT=class extends Pm{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},rT=class extends Z{},iT=class extends rT{async get_image_embeddings({pixel_values:e}){return await Dh(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??=vl(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 nT(await super._call(e))}},aT=class extends Pm{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}},oT=class extends Z{},sT=class extends oT{async get_image_embeddings({pixel_values:e}){return await Dh(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??=vl(t.slice(0,-1)),e.input_boxes??=gl([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=gl([t[0],t[1],0],-1n),e.input_points=gl([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,ci(e,n.inputNames))}async _call(e){return new aT(await super._call(e))}},cT=class extends sT{},lT=class extends sT{},uT=class extends Z{},dT=class extends uT{},fT=class extends uT{},pT=class extends uT{},mT=class extends Z{},hT=class extends mT{},gT=class extends mT{},_T=class extends mT{},vT=class extends Z{},yT=class extends vT{},bT=class extends vT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},xT=class extends Kg{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},ST=class extends Z{},CT=class extends ST{},wT=class extends ST{},TT=class extends Z{main_input_name=`input_values`;forward_params=[`input_values`]},ET=class extends TT{async encode(e){return await J(this.sessions.encoder_model,e)}async decode(e){return await J(this.sessions.decoder_model,e)}},DT=class extends TT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},OT=class extends TT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},kT=class extends Z{},AT=class extends kT{},jT=class extends kT{},MT=class extends Z{},NT=class extends MT{},PT=class extends MT{},FT=class extends MT{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let{encoder_outputs:o,encoder_attention_mask:s}=await Dh(this,{input_ids:e}),c=o.dims[1]/this.config.reduction_factor,l=Math.floor(c*i),u=Math.floor(c*r),d=this.config.num_mel_bins,f=[],p=null,m=null,h=0;for(;;){++h;let e=bh(!!m),r;r=m?m.output_sequence_out:new W(`float32`,new Float32Array(d),[1,1,d]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:s,speaker_embeddings:t,encoder_hidden_states:o};this.addPastKeyValues(i,p),m=await J(this.sessions.decoder_model_merged,i),p=this.getPastKeyValues(m,p);let{prob:a,spectrum:c}=m;if(f.push(c),h>=u&&(Array.from(a.data).filter(e=>e>=n).length>0||h>=l))break}let g=ll(f),{waveform:_}=await J(a.sessions.model,{spectrogram:g});return{spectrogram:g,waveform:_}}},IT=class extends Z{main_input_name=`spectrogram`},LT=class extends Z{},RT=class extends LT{},zT=class extends LT{async _call(e){return new Im(await super._call(e))}},BT=class extends LT{async _call(e){return new Y(await super._call(e))}},VT=class extends LT{async _call(e){return new Lm(await super._call(e))}},HT=class extends Z{},UT=class extends HT{},WT=class extends HT{},GT=class extends Z{},KT=class extends GT{},qT=class extends GT{},JT=class extends Z{},YT=class extends JT{},XT=class extends Z{},ZT=class extends XT{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;ee*t,1)),d[e]);let f=new W(l,new u(s*UE),[1,s,UE]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:f,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:p,text_hidden_size:n.hidden_size}}async function qE(e,t){let n=t.dims[2],r=Math.floor((WE+n-3)/2)+1,i=new W(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=vl([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 JE(e,t){for(;e.audio_embed_total_tokens0&&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=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var XE=class extends nh{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)}},ZE=class extends Z{forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},QE=class extends ZE{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=GE.get(this);i&&await JE(i,i.audio_consumed+r);let{inputs_embeds:a}=await J(this.sessions.embed_tokens,{input_ids:e});i&&YE(i,a,r);let o={inputs_embeds:a,...n};this.addPastKeyValues(o,t);let s=this.sessions.decoder_model_merged;return await J(s,ci(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=KE(this,e);GE.set(this,r);let i=new rh;i.push(new XE(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),GE.delete(this)}}},$E=class extends Z{},eD=class extends $E{},tD=class extends $E{async _call(e){return new Rm(await super._call(e))}},nD=class extends $E{async _call(e){return new Y(await super._call(e))}},rD=class extends Pm{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},iD=class extends Z{},aD=class extends iD{},oD=class extends iD{async _call(e){return new Rm(await super._call(e))}},sD=class extends iD{async _call(e){return new Y(await super._call(e))}},cD=class extends iD{async _call(e){return new rD(await super._call(e))}},lD=class extends iD{async _call(e){return new Fm(await super._call(e))}},uD=class extends Z{},dD=class extends uD{},fD=class extends th{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},pD=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`]},mD=class extends pD{},hD=class extends pD{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,fD)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(P.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${Eu(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&&(P.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??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new Hm,n.push(new qm(t,a))),t.begin_suppress_tokens&&(n??=new Hm,n.push(new Km(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`&&P.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(;de+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],ee=[];for(let e=0;e0)if(x)S=e-d;else{let e=ee.at(-1);S=(v[e-1]-a)*2,te=e}else S=e-d;let C=Math.floor(d/2),w=a+1500;for(let e=0;e=a&&(v[e]=Math.min(v[e]+C,w));f.push(...v.slice(0,te)),y&&p.push(...y.slice(0,te)),d+=S}f.push(o);let m=[...r,...f];if(s){let e=new W(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new W(`float32`,new Float32Array(t),[1,t.length])}}return new W(`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??P.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&&(P.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)=>ll(o.map(e=>e[t]),2)),c=ul(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)})).transpose(1,0,2,3),[l,u]=fl(c,-2,0,!0),d=c.clone();for(let e=0;e0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new W(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;et[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},gD=class extends hD{},_D=class extends Z{},vD=class extends _D{},yD=class extends _D{async _call(e){return new Im(await super._call(e))}},bD=class extends _D{async _call(e){return new Y(await super._call(e))}},xD=class extends _D{async _call(e){return new Fm(await super._call(e))}},SD=class extends _D{async _call(e){return new Lm(await super._call(e))}},CD=class extends Z{},wD=class extends CD{},TD=class extends CD{async _call(e){return new Im(await super._call(e))}},ED=class extends CD{async _call(e){return new Y(await super._call(e))}},DD=class extends CD{async _call(e){return new Fm(await super._call(e))}},OD=class extends CD{async _call(e){return new Lm(await super._call(e))}},kD=class extends Z{},AD=class extends kD{},jD=class extends kD{async _call(e){return new MD(await super._call(e))}},MD=class extends Pm{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},ND=class extends Z{},PD=class extends ND{},FD=class extends ND{},ID=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`]]),LD=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`]]),RD=new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),zD=new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`]]),BD=new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),VD=new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),HD=new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),UD=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`]]),WD=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`]]),GD=new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),KD=new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),qD=new Map([[`multi_modality`,`MultiModalityCausalLM`]]),JD=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`]]),YD=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`]]),XD=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),ZD=new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),QD=new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),$D=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),eO=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`]]),tO=new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),nO=new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),rO=new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),iO=new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),aO=new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),oO=new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),sO=new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),cO=new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),lO=new Map([[`wavlm`,`WavLMForXVector`]]),uO=new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),dO=new Map([[`vitmatte`,`VitMatteForImageMatting`]]),fO=new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),pO=new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),mO=new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),hO=new Map([[`sapiens`,`SapiensForNormalEstimation`]]),gO=new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),_O=new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),vO=[[ID,X.EncoderOnly],[LD,X.EncoderDecoder],[zD,X.DecoderOnlyWithoutHead],[RD,X.AutoEncoder],[UD,X.EncoderOnly],[WD,X.EncoderOnly],[GD,X.Seq2Seq],[BD,X.Seq2Seq],[KD,X.DecoderOnly],[qD,X.MultiModality],[JD,X.EncoderOnly],[YD,X.EncoderOnly],[XD,X.Vision2Seq],[ZD,X.ImageTextToText],[QD,X.AudioTextToText],[eO,X.EncoderOnly],[rO,X.EncoderOnly],[aO,X.EncoderOnly],[iO,X.EncoderOnly],[dO,X.EncoderOnly],[fO,X.EncoderOnly],[pO,X.EncoderOnly],[mO,X.EncoderOnly],[hO,X.EncoderOnly],[gO,X.EncoderOnly],[tO,X.EncoderOnly],[nO,X.EncoderOnly],[oO,X.MaskGeneration],[sO,X.EncoderOnly],[cO,X.EncoderOnly],[VD,X.Seq2Seq],[HD,X.EncoderOnly],[lO,X.EncoderOnly],[uO,X.EncoderOnly],[_O,X.EncoderOnly]];for(let[e,t]of vO)for(let n of e.values()){Ch.set(n,t);let e=Hh[n];Th.set(e,n),wh.set(n,e)}var yO=[[`MusicgenForConditionalGeneration`,nC,X.Musicgen],[`Phi3VForCausalLM`,rw,X.Phi3V],[`CLIPTextModelWithProjection`,Yg,X.EncoderOnly],[`SiglipTextModel`,bT,X.EncoderOnly],[`JinaCLIPTextModel`,tx,X.EncoderOnly],[`ClapTextModelWithProjection`,Wg,X.EncoderOnly],[`ClapAudioModelWithProjection`,Gg,X.EncoderOnly],[`DacEncoderModel`,I_,X.EncoderOnly],[`DacDecoderModel`,L_,X.EncoderOnly],[`MimiEncoderModel`,Wx,X.EncoderOnly],[`MimiDecoderModel`,Gx,X.EncoderOnly],[`SnacEncoderModel`,DT,X.EncoderOnly],[`SnacDecoderModel`,OT,X.EncoderOnly],[`Gemma3nForConditionalGeneration`,My,X.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,Py,X.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,ZT,X.Supertonic],[`ChatterboxModel`,Lg,X.Chatterbox],[`VoxtralRealtimeForConditionalGeneration`,QE,X.VoxtralRealtime]];for(let[e,t,n]of yO)Ch.set(e,n),Th.set(t,e),wh.set(e,t);var bO=new Map([[`modnet`,rO],[`birefnet`,rO],[`isnet`,rO],[`ben`,rO]]);for(let[e,t]of bO.entries())t.set(e,`PreTrainedModel`),Ch.set(e,X.EncoderOnly),wh.set(e,Z);var xO=new Set(bO.keys());Ch.set(`PreTrainedModel`,X.EncoderOnly),Th.set(Z,`PreTrainedModel`);var Q={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:UD,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:WD,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:VD,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:HD,MODEL_FOR_MASKED_LM_MAPPING_NAMES:JD,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:YD,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:eO,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:rO,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:iO,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:aO,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:tO,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:nO,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:oO,MODEL_FOR_CTC_MAPPING_NAMES:sO,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:cO,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:lO,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:uO,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:$D,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:dO,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:pO,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:mO,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:hO,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:gO,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:_O,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:ZD,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:QD,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:GD,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:BD,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:KD,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:XD};vh(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 Tm.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 Hh[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return xO.has(p)||P.warn(`Unknown model class "${p}", attempting to construct from base class.`),await Z.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},SO=class extends ${static MODEL_CLASS_MAPPINGS=vO.map(e=>e[0]);static BASE_IF_FAIL=!0},CO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},wO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},TO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},EO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},DO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},OO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},kO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},AO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},jO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},MO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},NO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},PO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},FO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},IO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},LO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},RO=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 zO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_CTC_MAPPING_NAMES]},BO=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 VO=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 HO=class extends ${static MODEL_CLASS_MAPPINGS=[Q.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},UO=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 WO=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 GO(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>Bd.read(e)))}async function KO(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?Wu(e,t):e instanceof Float64Array?new Float32Array(e):e))}function qO(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 JO=class extends $r{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()}},YO=class extends JO{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 W(`float32`,rc(e.data),e.dims),s=[];for(let e of r.logits){let n=await nl(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]}},XO=class extends JO{async _call(e,{ignore_labels:t=[`O`]}={}){let n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(r)).logits,a=this.model.config.id2label,o=[];for(let e=0;ee==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;ne==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=rc(i).map((e,t)=>[e,t]),m=rc(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=oi(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;ee==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await nl(new W(`float32`,rc(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]}},$O=class extends JO{_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,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},ek=class extends $O{_key=`summary_text`},tk=class extends $O{_key=`translation_text`};function nk(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var rk=class extends JO{async _call(e,t={}){let n=!1,r=!1,i=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=t.tokenizer_encode_kwargs,o;if(typeof e==`string`)o=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))n=!0,o=e;else{if(nk(e))e=[e];else if(Array.isArray(e)&&e.every(nk))n=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);r=!0,o=e.map(e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,...a})),i=!1,a=void 0}let s=r?!1:t.return_full_text??!0;this.tokenizer.padding_side=`left`;let c=this.tokenizer(o,{add_special_tokens:i,padding:!0,truncation:!0,...a}),l=await this.model.generate({...c,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}),d;!s&&c.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let f=Array.from({length:e.length},e=>[]);for(let t=0;t[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(P.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&&(P.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=>rc(e)[1]):rc(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]}},ak=class extends JO{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await KO(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await nl(new W(`float32`,rc(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},ok=class extends JO{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 KO(e,o),c=[];for(let e of s){let n=await this.processor(e),r=rc((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}},sk=class extends JO{async _call(e,t={}){switch(this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);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&&P.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&P.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await KO(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(oc(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}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 KO(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=>fc(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 KO(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.processor.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=i.config.sampling_rate,o=await KO(r,a),s=t.language??`en`,c=this.processor.get_decoder_prompt_ids(s),l=[];for(let e of o){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:c,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,s);l.push({text:a})}return n?l[0]:l}},ck=class extends JO{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 N.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new W(`float32`,e,[e.length]);else if(!(e instanceof W))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({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},uk=class extends JO{async _call(e,{top_k:t=5}={}){let n=await GO(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 nl(new W(`float32`,rc(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]}},dk={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},fk=class extends JO{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 GO(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=dk[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(dk))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=1e-5,t=f[d[0]];for(let n=0;nt<-e||t>1+e)&&i.sigmoid_();let a=await Bd.fromTensor(i.mul_(255).to(`uint8`)).resize(r[1],r[0]);h.push({label:null,score:null,mask:a})}}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{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},mk=class extends JO{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await GO(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type===`siglip`?`max_length`:!0,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=>rc(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]}},hk=class extends JO{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 GO(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:qO(t,!n)})));return r?d:d[0]}},gk=class extends JO{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await GO(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e({score:e.scores[n],label:e.labels[n],box:qO(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:qO(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]}},_k=class extends JO{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 GO(e))[0],{pixel_values:i}=await this.processor(r),a=`${t}`,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,...n}),c=this.tokenizer.batch_decode(s)[0].match(/(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},vk=class extends JO{async _call(e){let t=await GO(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(Bd.fromTensor(t))}return Array.isArray(e)?i:i[0]}},yk=class extends JO{async _call(e){let t=await GO(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;ee>=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,Ck=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}},wk=M.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),Tk=class extends Ck{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,skip_special_tokens:i=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??wk,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:i,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error(`TextStreamer only supports batch size of 1`);let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let n=e[0];if(this.token_callback_function?.(n),n.length===1&&this.special_ids.has(n[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(e,!1),this.token_cache=[],this.print_len=0}let e=this.tokenizer.decode(n,this.decode_kwargs);this.on_finalized_text(e,!1);return}this.token_cache=ai(this.token_cache,n);let r=this.tokenizer.decode(this.token_cache,this.decode_kwargs),i;t||r.endsWith(` +`)?(i=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&Sk(r.charCodeAt(r.length-1))?(i=r.slice(this.print_len),this.print_len+=i.length):(i=r.slice(this.print_len,r.lastIndexOf(` `)+1),this.print_len+=i.length),this.on_finalized_text(i,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e=``,this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===wk&&M.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}};let Ek=`onnx-community/gemma-4-E2B-it-ONNX`;function Dk(e){return e.replace(/<\|?channel\|?>?\s*thought\s*/gi,`‹‹THINK››`).replace(/<\|?channell?\|?>/gi,`‹‹/THINK››`).replace(/<\|?[a-z_]+\|?>/gi,``).trim()}let Ok=null,kk=null,Ak=new oh;async function jk(){try{let e=await navigator.gpu?.requestAdapter();self.postMessage({type:`status`,status:e?`webgpu-available`:`webgpu-unavailable`})}catch{self.postMessage({type:`status`,status:`webgpu-unavailable`})}}async function Mk(){try{self.postMessage({type:`status`,status:`loading`});let e=e=>self.postMessage({type:`progress`,...e});Ok=await ym.from_pretrained(Ek,{progress_callback:e}),kk=await Py.from_pretrained(Ek,{dtype:`q4f16`,device:`webgpu`,progress_callback:e}),self.postMessage({type:`status`,status:`ready`})}catch(e){self.postMessage({type:`error`,message:e.message})}}async function Nk({messages:e,imageUrl:t,audioData:n,enableThinking:r}){if(!kk||!Ok){self.postMessage({type:`error`,message:`Model not loaded`});return}try{self.postMessage({type:`status`,status:`generating`}),Ak.reset();let i=Ok.apply_chat_template(e,{enable_thinking:r,add_generation_prompt:!0}),a=t?await Vd(t):null,o=await Ok(i,a,n??null,{add_special_tokens:!1}),s=``,c=new Tk(Ok.tokenizer,{skip_prompt:!0,skip_special_tokens:!1,callback_function:e=>{s+=e;let t=Dk(s);self.postMessage({type:`update`,text:t})}});await kk.generate({...o,max_new_tokens:512,do_sample:!1,streamer:c,stopping_criteria:[Ak]}),self.postMessage({type:`complete`,text:Dk(s)})}catch(e){self.postMessage({type:`error`,message:e.message})}}self.onmessage=e=>{switch(e.data.type){case`check`:jk();break;case`load`:Mk();break;case`generate`:Nk(e.data);break;case`interrupt`:Ak.interrupt();break}}})(); \ No newline at end of file