claude-code-session-manager 0.8.6 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +95 -65
  2. package/dist/assets/{cssMode-DBg6nxUL.js → cssMode-DWlBzlpW.js} +1 -1
  3. package/dist/assets/{freemarker2-CyjUGY3f.js → freemarker2-Cgg83m-Z.js} +1 -1
  4. package/dist/assets/{handlebars-lhtCWqlB.js → handlebars-C4r4LOI9.js} +1 -1
  5. package/dist/assets/{html-egptHwbZ.js → html-DaxRI5sW.js} +1 -1
  6. package/dist/assets/htmlMode-Bu_8jtXo.js +1 -0
  7. package/dist/assets/{index-DjeqNwqn.js → index-C_tgFedf.js} +1115 -1081
  8. package/dist/assets/{index-DnLtSCQS.css → index-Dj3Db4OA.css} +1 -1
  9. package/dist/assets/{javascript-tZbiID3O.js → javascript-D5Ztx-Ej.js} +1 -1
  10. package/dist/assets/{jsonMode-BGtPN-L-.js → jsonMode-tfsgezVc.js} +1 -1
  11. package/dist/assets/{liquid-DvTeXhev.js → liquid-F2cD9OL0.js} +1 -1
  12. package/dist/assets/{lspLanguageFeatures-D9xoxVlV.js → lspLanguageFeatures-Bz_Eih8F.js} +2 -2
  13. package/dist/assets/{mdx-BQ3Ja4wM.js → mdx-BPlD1clX.js} +1 -1
  14. package/dist/assets/{ort-wasm-simd-threaded.asyncify-CtKKja6V.wasm → ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm} +0 -0
  15. package/dist/assets/{python-C71RWXaP.js → python-B4gUOWNI.js} +1 -1
  16. package/dist/assets/{razor-w__Mkyns.js → razor-B6pMxVp1.js} +1 -1
  17. package/dist/assets/{tsMode-DOQLQDB3.js → tsMode-C9nq6cHi.js} +1 -1
  18. package/dist/assets/{typescript-DEiub2Jt.js → typescript-Do5Vtwxu.js} +1 -1
  19. package/dist/assets/{whisperWorker-QfIS0sPF.js → whisperWorker-CcsPqZUS.js} +19 -19
  20. package/dist/assets/{xml-RXkLQscS.js → xml-C0mTbVRp.js} +1 -1
  21. package/dist/assets/{yaml-C8HIpJku.js → yaml-D3sePJfA.js} +1 -1
  22. package/dist/index.html +2 -2
  23. package/package.json +18 -10
  24. package/screenshots/.gitkeep +0 -0
  25. package/screenshots/README-screenshots.md +13 -0
  26. package/src/main/config.cjs +47 -9
  27. package/src/main/historyAggregator.cjs +10 -5
  28. package/src/main/index.cjs +85 -14
  29. package/src/main/ipcSchemas.cjs +165 -3
  30. package/src/main/lib/claudeBin.cjs +39 -0
  31. package/src/main/lib/encodeCwd.cjs +19 -0
  32. package/src/main/lib/fileTail.cjs +35 -0
  33. package/src/main/lib/insideHome.cjs +38 -0
  34. package/src/main/lib/prdFrontmatter.cjs +51 -0
  35. package/src/main/lib/sendToRenderer.cjs +21 -0
  36. package/src/main/memoryTool.cjs +203 -0
  37. package/src/main/otelSettings.cjs +2 -7
  38. package/src/main/pluginInstall.cjs +129 -0
  39. package/src/main/pty.cjs +13 -29
  40. package/src/main/queueOps.cjs +404 -0
  41. package/src/main/scheduler/prdParser.cjs +135 -0
  42. package/src/main/scheduler.cjs +291 -250
  43. package/src/main/sessionsStore.cjs +2 -6
  44. package/src/main/supervisor.cjs +3 -35
  45. package/src/main/teams.cjs +95 -0
  46. package/src/main/transcripts.cjs +5 -7
  47. package/src/main/usage.cjs +8 -0
  48. package/src/main/voiceHotkey.cjs +13 -9
  49. package/src/main/voiceSettings.cjs +2 -9
  50. package/src/main/voiceWizard.cjs +4 -11
  51. package/src/main/watchers.cjs +18 -42
  52. package/src/preload/api.d.ts +153 -1
  53. package/src/preload/index.cjs +29 -0
  54. package/dist/assets/htmlMode-tPDeHGOB.js +0 -1
@@ -1,24 +1,24 @@
1
- var aD=Object.defineProperty;var Cv=Oe=>{throw TypeError(Oe)};var oD=(Oe,Ge,tt)=>Ge in Oe?aD(Oe,Ge,{enumerable:!0,configurable:!0,writable:!0,value:tt}):Oe[Ge]=tt;var k=(Oe,Ge,tt)=>oD(Oe,typeof Ge!="symbol"?Ge+"":Ge,tt),Sv=(Oe,Ge,tt)=>Ge.has(Oe)||Cv("Cannot "+tt);var _t=(Oe,Ge,tt)=>(Sv(Oe,Ge,"read from private field"),tt?tt.call(Oe):Ge.get(Oe)),yo=(Oe,Ge,tt)=>Ge.has(Oe)?Cv("Cannot add the same private member more than once"):Ge instanceof WeakSet?Ge.add(Oe):Ge.set(Oe,tt),bo=(Oe,Ge,tt,Rn)=>(Sv(Oe,Ge,"write to private field"),Rn?Rn.call(Oe,tt):Ge.set(Oe,tt),tt);(function(){"use strict";/*!
2
- * ONNX Runtime Web v1.26.0-dev.20260410-5e55544225
1
+ var dD=Object.defineProperty;var Pv=Oe=>{throw TypeError(Oe)};var hD=(Oe,Ge,rt)=>Ge in Oe?dD(Oe,Ge,{enumerable:!0,configurable:!0,writable:!0,value:rt}):Oe[Ge]=rt;var k=(Oe,Ge,rt)=>hD(Oe,typeof Ge!="symbol"?Ge+"":Ge,rt),Fv=(Oe,Ge,rt)=>Ge.has(Oe)||Pv("Cannot "+rt);var _t=(Oe,Ge,rt)=>(Fv(Oe,Ge,"read from private field"),rt?rt.call(Oe):Ge.get(Oe)),yo=(Oe,Ge,rt)=>Ge.has(Oe)?Pv("Cannot add the same private member more than once"):Ge instanceof WeakSet?Ge.add(Oe):Ge.set(Oe,rt),bo=(Oe,Ge,rt,Rn)=>(Fv(Oe,Ge,"write to private field"),Rn?Rn.call(Oe,rt):Ge.set(Oe,rt),rt);(function(){"use strict";/*!
2
+ * ONNX Runtime Web v1.26.0-dev.20260416-b7804b056c
3
3
  * Copyright (c) Microsoft Corporation. All rights reserved.
4
4
  * Licensed under the MIT License.
5
- */var wg,vg,vn,cu,yn,ft,yg,bg,uu,bn,Wa,Mn,Ha,Ds,Zr,Qa,xn,du,kn,Xa,Tn,En,Ya,Ja,An,Ka,Za,eo,Cn,to,Sn,hu,fu,ro,Pn,Fn,Ln,so,no,ao,oo,io,_u,pu,mu,gu,wu,vu,yu,bu,Mu,xu,ku,Tu,Eu,Au,Cu,Su,Pu,Fu,Lu,Iu,Ou,Nu,Du,zu,Bu,Ru,Gu,$u,Vu,Uu;var Oe=Object.defineProperty,Ge=Object.getOwnPropertyDescriptor,tt=Object.getOwnPropertyNames,Rn=Object.prototype.hasOwnProperty,Nv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),me=(e,t)=>()=>(e&&(t=e(e=0)),t),Vs=(e,t)=>{for(var r in t)Oe(e,r,{get:t[r],enumerable:!0})},Dv=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tt(t))!Rn.call(e,n)&&n!==r&&Oe(e,n,{get:()=>t[n],enumerable:!(s=Ge(t,n))||s.enumerable});return e},Gn=e=>Dv(Oe({},"__esModule",{value:!0}),e),Us,kr,Br,yd,bd,Md=me(()=>{Us=new Map,kr=[],Br=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=Us.get(e);if(s===void 0)Us.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=kr.indexOf(e);n!==-1&&kr.splice(n,1);for(let a=0;a<kr.length;a++)if(Us.get(kr[a]).priority<=r){kr.splice(a,0,e);return}kr.push(e)}return}throw new TypeError("not a valid backend")},yd=async e=>{let t=Us.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},bd=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),s=r.length===0?kr:r,n,a=[],o=new Set;for(let l of s){let c=await yd(l);typeof c=="string"?a.push({name:l,err:c}):(n||(n=c),n===c&&o.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),zv=me(()=>{Md()}),xd,Bv=me(()=>{xd="1.24.0-dev.20251116-b39e144322"}),Mo,Ke,kd=me(()=>{Bv(),Mo="warning",Ke={wasm:{},webgl:{},webgpu:{},versions:{common:xd},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Mo=e}},get logLevel(){return Mo}},Object.defineProperty(Ke,"logLevel",{enumerable:!0})}),Be,Rv=me(()=>{kd(),Be=Ke}),Td,Ed,Gv=me(()=>{Td=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let n,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*n,h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<n;y++){let M=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],C=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+M+","+T+","+A+","+C+")",s.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Ed=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,p=0,w=1,v=2,y=3,M=0,T=h,A=h*2,C=-1;i==="RGBA"?(M=0,T=h,A=h*2,C=h*3):i==="RGB"?(M=0,T=h,A=h*2):i==="RBG"&&(M=0,A=h,T=h*2),s=r.createImageData(n,a);for(let S=0;S<a*n;p+=_,w+=_,v+=_,y+=_,S++)s.data[p]=(e.data[M++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[y]=C===-1?255:(e.data[C++]-d[3])*c[3]}else throw new Error("Can not access image data");return s}}),$n,Ad,Cd,Sd,Pd,Fd,$v=me(()=>{ko(),$n=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,v=3,y=0,M=c,T=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,y=c*2);for(let C=0;C<c;C++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[M++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new Mt("float32",d,[1,4,r,s]):new Mt("float32",d,[1,3,r,s])},Ad=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let _=l();_.width=h,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,$n(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{let _=l(),p=c(_);if(!e||!p)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);let v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d($n(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return $n(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Cd=(e,t)=>{let{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new Mt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Sd=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Mt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},Pd=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Mt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},Fd=(e,t,r)=>new Mt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Rr,js,xo,Ld,Vv=me(()=>{Rr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),js=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xo=!1,Ld=()=>{if(!xo){xo=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Rr.set("int64",BigInt64Array),js.set(BigInt64Array,"int64")),t&&(Rr.set("uint64",BigUint64Array),js.set(BigUint64Array,"uint64")),s?(Rr.set("float16",r),js.set(r,"float16")):Rr.set("float16",Uint16Array)}}}),Id,Od,Uv=me(()=>{ko(),Id=e=>{let t=1;for(let r=0;r<e.length;r++){let s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},Od=(e,t)=>{switch(e.location){case"cpu":return new Mt(e.type,e.data,t);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Mt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Mt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Mt,ko=me(()=>{Gv(),$v(),Vv(),Uv(),Mt=class{constructor(e,t,r){Ld();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=Rr.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e=="string")if(s=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Rr.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=js.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=o,this.dataLocation="cpu"}let a=Id(n);if(this.cpuData&&a!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=a}static async fromImage(e,t){return Ad(e,t)}static fromTexture(e,t){return Cd(e,t)}static fromGpuBuffer(e,t){return Sd(e,t)}static fromMLTensor(e,t){return Pd(e,t)}static fromPinnedBuffer(e,t,r){return Fd(e,t,r)}toDataURL(e){return Td(this,e)}toImageData(e){return Ed(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Od(this,e)}}}),zt,Nd=me(()=>{ko(),zt=Mt}),Vn,To,Gr,$r,Tr,Er,Dd=me(()=>{kd(),Vn=(e,t)=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.timeStamp(`${e}::ORT::${t}`)},To=(e,t)=>{var n;let r=((n=new Error().stack)==null?void 0:n.split(/\r\n|\r|\n/g))||[],s=!1;for(let a=0;a<r.length;a++){if(s&&!r[a].includes("TRACE_FUNC")){let o=`FUNC_${e}::${r[a].trim().split(" ")[1]}`;t&&(o+=`::${t}`),Vn("CPU",o);return}r[a].includes("TRACE_FUNC")&&(s=!0)}},Gr=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||To("BEGIN",e)},$r=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||To("END",e)},Tr=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.time(`ORT::${e}`)},Er=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.timeEnd(`ORT::${e}`)}}),zd,jv=me(()=>{Md(),Nd(),Dd(),zd=class Pv{constructor(t){this.handler=t}async run(t,r,s){Gr(),Tr("InferenceSession.run");let n={},a={};if(typeof t!="object"||t===null||t instanceof zt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof zt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let _=r[h];(_===null||_ instanceof zt)&&(c=!0,o=!1,n[h]=_)}if(c){if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(t,n,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof zt?l[c]=d:l[c]=new zt(d.type,d.data,d.dims)}return Er("InferenceSession.run"),$r(),l}async release(){return this.handler.dispose()}static async create(t,r,s,n){Gr(),Tr("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,h=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-h,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(d,h,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await bd(o),c=await i.createInferenceSessionHandler(a,l);return Er("InferenceSession.create"),$r(),new Pv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Eo,qv=me(()=>{jv(),Eo=zd}),Wv=me(()=>{}),Hv=me(()=>{}),Qv=me(()=>{}),Xv=me(()=>{}),Bd={};Vs(Bd,{InferenceSession:()=>Eo,TRACE:()=>Vn,TRACE_EVENT_BEGIN:()=>Tr,TRACE_EVENT_END:()=>Er,TRACE_FUNC_BEGIN:()=>Gr,TRACE_FUNC_END:()=>$r,Tensor:()=>zt,env:()=>Be,registerBackend:()=>Br});var Vr=me(()=>{zv(),Rv(),qv(),Nd(),Wv(),Hv(),Dd(),Qv(),Xv()}),Ao=me(()=>{}),Rd={};Vs(Rd,{default:()=>Gd});var Co,So,Gd,Yv=me(()=>{var e;Th(),Ur(),No(),Co="ort-wasm-proxy-worker",So=((e=globalThis.self)==null?void 0:e.name)===Co,So&&(self.onmessage=t=>{let{type:r,in:s}=t.data;try{switch(r){case"init-wasm":Bo(s.wasm).then(()=>{Jo(s).then(()=>{postMessage({type:r})},n=>{postMessage({type:r,err:n})})},n=>{postMessage({type:r,err:n})});break;case"init-ep":{let{epName:n,env:a}=s;Ko(a,n).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:n}=s,a=Xn(n);postMessage({type:r,out:a});break}case"create":{let{model:n,options:a}=s;ei(n,a).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":ti(s),postMessage({type:r});break;case"run":{let{sessionId:n,inputIndices:a,inputs:o,outputIndices:i,options:l}=s;si(n,a,o,i,new Array(i.length).fill(null),l).then(c=>{c.some(d=>d[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:c},ai([...o,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":ni(s),postMessage({type:r});break;default:}}catch(n){postMessage({type:r,err:n})}}),Gd=So?null:t=>new Worker(t??xt,{type:"module",name:Co})}),$d={};Vs($d,{default:()=>Ud});async function Vd(e={}){var Ev,Av;var t=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&((Ev=self.name)==null?void 0:Ev.startsWith("em-pthread"));t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,f)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let u=f=>(...m)=>{let g=or;return m=f(...m),or!=g?new Promise((b,E)=>{Zu={resolve:b,reject:E}}):m};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=u(t[f])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a==null||a()};var o,i,l=(u,f)=>{throw f},c=self.location.href,d="";if(r||s){try{d=new URL(".",c).href}catch{}s&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async u=>{if(N(u))return new Promise((m,g)=>{var b=new XMLHttpRequest;b.open("GET",u,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?m(b.response):g(b.status)},b.onerror=g,b.send(null)});var f=await fetch(u,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}var h,_,p,w,v,y,M=console.log.bind(console),T=console.error.bind(console),A=M,C=T,S=!1,N=u=>u.startsWith("file://");function x(){Dr.buffer!=z.buffer&&X()}if(n){let u=function(f){try{var m=f.data,g=m.Oc;if(g==="load"){let b=[];self.onmessage=E=>b.push(E),y=()=>{postMessage({Oc:"loaded"});for(let E of b)u(E);self.onmessage=u};for(let E of m.ce)t[E]&&!t[E].proxy||(t[E]=(...F)=>{postMessage({Oc:"callHandler",be:E,args:F})},E=="print"&&(A=t[E]),E=="printErr"&&(C=t[E]));Dr=m.ie,X(),_=m.je,Fe(),vo()}else if(g==="run"){(function(b){var E=(x(),I)[b+52>>>2>>>0];b=(x(),I)[b+56>>>2>>>0],zw(E,E-b),ne(E)})(m.Nc),dd(m.Nc,0,0,1,0,0),kg(),Yu(m.Nc),R||(vw(),R=!0);try{lO(m.ge,m.Wc)}catch(b){if(b!="unwind")throw b}}else m.target!=="setimmediate"&&(g==="checkMailbox"?R&&uo():g&&(C(`worker: received unknown command ${g}`),C(m)))}catch(b){throw Lw(),b}};var R=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var z,$,Q,H,D,I,te,W,ee,G,L,V=!1;function X(){var u=Dr.buffer;t.HEAP8=z=new Int8Array(u),Q=new Int16Array(u),t.HEAPU8=$=new Uint8Array(u),H=new Uint16Array(u),t.HEAP32=D=new Int32Array(u),t.HEAPU32=I=new Uint32Array(u),te=new Float32Array(u),W=new Float64Array(u),ee=new BigInt64Array(u),G=new BigUint64Array(u)}function J(){V=!0,n?y():xr._b()}function we(u){throw C(u="Aborted("+u+")"),S=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v==null||v(u),u}function re(){return{a:{f:cO,J:uO,k:dO,p:hO,l:fO,sa:_O,b:pO,ca:mO,Ja:Pg,q:gO,da:Og,Za:Ng,Fa:Dg,Ha:zg,_a:Bg,Xa:Rg,Qa:Gg,Wa:$g,oa:Vg,Ga:Ug,Xb:jg,Ya:qg,Yb:Wg,db:wO,Da:vO,Sb:yO,Qb:MO,Ca:kO,M:TO,I:EO,Rb:AO,ja:OO,Tb:NO,Ta:DO,Vb:BO,Ka:RO,Ob:GO,ka:$O,Sa:Yu,ab:VO,U:WO,n:JO,c:Qu,rb:KO,w:ZO,L:eN,z:tN,j:rN,o:ew,sb:sN,G:nN,T:aN,h:oN,u:iN,m:lN,i:cN,Na:uN,Oa:dN,Pa:hN,La:nw,Ma:aw,Pb:ow,eb:_N,cb:mN,Y:gN,qb:wN,la:vN,bb:pN,fb:yN,$a:bN,Wb:MN,N:fN,gb:xN,X:kN,Ub:TN,nb:ON,C:NN,ra:DN,qa:zN,pb:BN,W:RN,v:GN,mb:$N,lb:VN,kb:UN,ob:jN,jb:qN,ib:WN,hb:HN,Ua:hw,Va:fw,Ia:nr,V:_w,na:pw,Ra:mw,ma:gw,Cb:sD,xa:J3,Db:rD,ya:Y3,F:R3,e:E3,s:k3,x:x3,B:D3,Fb:H3,ba:W3,D:S3,za:Q3,$:K3,ga:q3,Gb:j3,Hb:U3,Ba:G3,Aa:V3,Ib:$3,wa:tD,aa:X3,d:T3,A:C3,r:A3,Bb:nD,t:F3,y:z3,H:P3,E:L3,K:B3,R:Z3,ia:N3,_:eD,Jb:O3,Kb:I3,g:XN,a:Dr,Nb:Pe,Eb:YN,ha:JN,O:KN,pa:ZN,Lb:e3,ta:t3,Q:r3,yb:s3,zb:n3,ua:a3,ea:o3,P:i3,Ea:l3,va:c3,Z:u3,wb:d3,Zb:h3,S:f3,Ab:_3,tb:p3,ub:g3,vb:w3,fa:v3,xb:y3,Mb:b3}}}async function Fe(){function u(g,b){var E=xr=g.exports;g={};for(let[F,O]of Object.entries(E))typeof O=="function"?(E=UO(O),g[F]=E):g[F]=O;return xr=g,xr=(function(){var F=xr,O=Y=>ye=>Y(ye)>>>0,j=Y=>()=>Y()>>>0;return(F=Object.assign({},F)).$b=O(F.$b),F.Cc=j(F.Cc),F.Ec=O(F.Ec),F.rd=(Y=>(ye,K)=>Y(ye,K)>>>0)(F.rd),F.wd=O(F.wd),F.xd=j(F.xd),F.Bd=O(F.Bd),F})(),Mg.push(xr.id),ww=(g=xr).$b,vw=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,ad=t._OrtGetWebGpuDevice=g.Bc,go=g.Cc,Xt=t._free=g.Dc,$s=t._malloc=g.Ec,yw=t._wgpuBufferRelease=g.Fc,bw=t._wgpuCreateInstance=g.Gc,Mw=g.Hc,xw=g.Ic,kw=g.Jc,Tw=g.Kc,Ew=g.Lc,Aw=g.Pc,Cw=g.Zc,Sw=g._c,Pw=g.$c,od=g.bd,id=g.cd,ld=g.dd,cd=g.ed,Dn=g.fd,ud=g.gd,Fw=g.hd,dd=g.kd,Lw=g.ld,Iw=g.md,Ow=g.nd,hd=g.od,Nw=g.pd,Dw=g.qd,fd=g.rd,pe=g.sd,zn=g.td,zw=g.ud,ne=g.vd,wo=g.wd,ae=g.xd,Bw=g.yd,_d=g.zd,Rw=g.Ad,Gw=g.Bd,$w=g.Cd,pd=g.Dd,Vw=g.Ed,Uw=g.Fd,jw=g.Gd,qw=g.Hd,Ww=g.Id,Hw=g.Jd,Qw=g.Kd,Xw=g.Ld,Yw=g.Md,Jw=g.Nd,Kw=g.Od,Zw=g.Pd,ev=g.Qd,tv=g.Rd,rv=g.Td,sv=g.Ud,nv=g.Vd,av=g.Wd,ov=g.Yd,iv=g.Zd,lv=g._d,cv=g.$d,uv=g.ae,dv=g.oe,hv=g.pe,fv=g.qe,_v=g.re,pv=g.se,mv=g.te,gv=g.ue,wv=g.ve,vv=g.we,yv=g.xe,bv=g.ye,Mv=g.Ye,xv=g.Ze,kv=g._e,Tv=g.$e,_=b,xr}var f,m=re();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(m,(b,E)=>{g(u(b,E))})}):n?u(new WebAssembly.Instance(_,re()),_):(L??(L=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL(""+new URL("ort-wasm-simd-threaded.asyncify-CtKKja6V.wasm",self.location.href).href,self.location.href).href),f=await(async function(g){var b=L;if(!h&&!N(b))try{var E=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(E,g)}catch(F){C(`wasm streaming compile failed: ${F}`),C("falling back to ArrayBuffer instantiation")}return(async function(F,O){try{var j=await(async function(Y){if(!h)try{var ye=await o(Y);return new Uint8Array(ye)}catch{}if(Y==L&&h)Y=new Uint8Array(h);else{if(!i)throw"both async and sync fetching of the wasm failed";Y=i(Y)}return Y})(F);return await WebAssembly.instantiate(j,O)}catch(Y){C(`failed to asynchronously prepare wasm: ${Y}`),we(Y)}})(b,g)})(m),u(f.instance,f.module))}class qe{constructor(f){k(this,"name","ExitStatus");this.message=`Program terminated with exit(${f})`,this.status=f}}var bt=u=>{u.terminate(),u.onmessage=()=>{}},It=[],Ot=0,Qe=null,pt=u=>{Nt.length==0&&(Eg(),Tg(Nt[0]));var f=Nt.pop();if(!f)return 6;In.push(f),es[u.Nc]=f,f.Nc=u.Nc;var m={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return f.postMessage(m,u.Yc),0},Me=0,ce=(u,f,...m)=>{var g,b=16*m.length,E=ae(),F=wo(b),O=F>>>3;for(g of m)typeof g=="bigint"?((x(),ee)[O++>>>0]=1n,(x(),ee)[O++>>>0]=g):((x(),ee)[O++>>>0]=0n,(x(),W)[O++>>>0]=g);return u=Iw(u,0,b,F,f),ne(E),u};function Pe(u){if(n)return ce(0,1,u);if(p=u,!(0<Me)){for(var f of In)bt(f);for(f of Nt)bt(f);Nt=[],In=[],es={},S=!0}l(0,new qe(u))}function mt(u){if(n)return ce(1,0,u);nr(u)}var nr=u=>{if(p=u,n)throw mt(u),"unwind";Pe(u)},Nt=[],In=[],Mg=[],es={},xg=u=>{var f=u.Nc;delete es[f],Nt.push(u),In.splice(In.indexOf(u),1),u.Nc=0,Ow(f)};function kg(){Mg.forEach(u=>u())}var Tg=u=>new Promise(f=>{u.onmessage=b=>{var E=b.data;if(b=E.Oc,E.Vc&&E.Vc!=go()){var F=es[E.Vc];F?F.postMessage(E,E.Yc):C(`Internal error! Worker sent a message "${b}" to target pthread ${E.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?uo():b==="spawnThread"?pt(E):b==="cleanupThread"?gt(()=>{xg(es[E.he])}):b==="loaded"?(u.loaded=!0,f(u)):E.target==="setimmediate"?u.postMessage(E):b==="uncaughtException"?u.onerror(E.error):b==="callHandler"?t[E.be](...E.args):b&&C(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw C(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var m,g=[];for(m of[])t.propertyIsEnumerable(m)&&g.push(m);u.postMessage({Oc:"load",ce:g,ie:Dr,je:_})});function Eg(){var u=new Worker((()=>{let f=URL;return self.location.href>"file:"&&self.location.href<"file;"?new f("ort.webgpu.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Nt.push(u)}var Dr,lO=(u,f)=>{Me=0,u=pd(u,f),0<Me?p=u:hd(u)},lo=[],co=0,ot=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function cO(u){var f=new ju(u>>>=0);return(x(),z)[f.Qc+12>>>0]==0&&(Ag(f,!0),co--),Cg(f,!1),lo.push(f),Gw(u)}var zs=0,uO=()=>{pe(0,0);var u=lo.pop();Bw(u.Xc),zs=0};function Ag(u,f){f=f?1:0,(x(),z)[u.Qc+12>>>0]=f}function Cg(u,f){f=f?1:0,(x(),z)[u.Qc+13>>>0]=f}class ju{constructor(f){this.Xc=f,this.Qc=f-24}}var qu=u=>{var f=zs;if(!f)return zn(0),0;var m=new ju(f);(x(),I)[m.Qc+16>>>2>>>0]=f;var g=(x(),I)[m.Qc+4>>>2>>>0];if(!g)return zn(0),f;for(var b of u){if(b===0||b===g)break;if(Rw(b,g,m.Qc+16))return zn(b),f}return zn(g),f};function dO(){return qu([])}function hO(u){return qu([u>>>0])}function fO(u,f,m,g){return qu([u>>>0,f>>>0,m>>>0,g>>>0])}var _O=()=>{var u=lo.pop();u||we("no exception to throw");var f=u.Xc;throw(x(),z)[u.Qc+13>>>0]==0&&(lo.push(u),Cg(u,!0),Ag(u,!1),co++),_d(f),zs=f};function pO(u,f,m){var g=new ju(u>>>=0);throw f>>>=0,m>>>=0,(x(),I)[g.Qc+16>>>2>>>0]=0,(x(),I)[g.Qc+4>>>2>>>0]=f,(x(),I)[g.Qc+8>>>2>>>0]=m,_d(u),co++,zs=u}var mO=()=>co;function Sg(u,f,m,g){return n?ce(2,1,u,f,m,g):Pg(u,f,m,g)}function Pg(u,f,m,g){if(u>>>=0,f>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Sg(u,f,m,g):(u={fe:m,Nc:u,Wc:g,Yc:b},n?(u.Oc="spawnThread",postMessage(u,b),0):pt(u))}function gO(u){throw zs||(zs=u>>>0),zs}var Fg=globalThis.TextDecoder&&new TextDecoder,Lg=(u,f,m,g)=>{if(m=f+m,g)return m;for(;u[f]&&!(f>=m);)++f;return f},Ig=(u,f=0,m,g)=>{if(16<(m=Lg(u,f>>>=0,m,g))-f&&u.buffer&&Fg)return Fg.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,m):u.slice(f,m));for(g="";f<m;){var b=u[f++];if(128&b){var E=63&u[f++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|E);else{var F=63&u[f++];65536>(b=(240&b)==224?(15&b)<<12|E<<6|F:(7&b)<<18|E<<12|F<<6|63&u[f++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Bs=(u,f,m)=>(u>>>=0)?Ig((x(),$),u,f,m):"";function Og(u,f,m){return n?ce(3,1,u,f,m):0}function Ng(u,f){if(n)return ce(4,1,u,f)}function Dg(u,f){if(n)return ce(5,1,u,f)}function zg(u,f,m){if(n)return ce(6,1,u,f,m)}function Bg(u,f,m){return n?ce(7,1,u,f,m):0}function Rg(u,f){if(n)return ce(8,1,u,f)}function Gg(u,f,m){if(n)return ce(9,1,u,f,m)}function $g(u,f,m,g){if(n)return ce(10,1,u,f,m,g)}function Vg(u,f,m,g){if(n)return ce(11,1,u,f,m,g)}function Ug(u,f,m,g){if(n)return ce(12,1,u,f,m,g)}function jg(u){if(n)return ce(13,1,u)}function qg(u,f){if(n)return ce(14,1,u,f)}function Wg(u,f,m){if(n)return ce(15,1,u,f,m)}var wO=()=>we(""),ar=u=>{u>>>=0;for(var f="";;){var m=(x(),$)[u++>>>0];if(!m)return f;f+=String.fromCharCode(m)}},Wu={},Hu={},Rs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function wr(u,f,m={}){return(function(g,b,E={}){var F=b.name;if(!g)throw new Rs(`type "${F}" must have a positive integer typeid pointer`);if(Hu.hasOwnProperty(g)){if(E.de)return;throw new Rs(`Cannot register type '${F}' twice`)}Hu[g]=b,Wu.hasOwnProperty(g)&&(b=Wu[g],delete Wu[g],b.forEach(O=>O()))})(u,f,m)}var Hg=(u,f,m)=>{switch(f){case 1:return m?g=>(x(),z)[g>>>0]:g=>(x(),$)[g>>>0];case 2:return m?g=>(x(),Q)[g>>>1>>>0]:g=>(x(),H)[g>>>1>>>0];case 4:return m?g=>(x(),D)[g>>>2>>>0]:g=>(x(),I)[g>>>2>>>0];case 8:return m?g=>(x(),ee)[g>>>3>>>0]:g=>(x(),G)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function vO(u,f,m,g,b){u>>>=0,m>>>=0,f=ar(f>>>0);let E=F=>F;if(g=g===0n){let F=8*m;E=O=>BigInt.asUintN(F,O),b=E(b)}wr(u,{name:f,Mc:E,Sc:(F,O)=>(typeof O=="number"&&(O=BigInt(O)),O),Rc:Hg(f,m,!g),Tc:null})}function yO(u,f,m,g){wr(u>>>=0,{name:f=ar(f>>>0),Mc:function(b){return!!b},Sc:function(b,E){return E?m:g},Rc:function(b){return this.Mc((x(),$)[b>>>0])},Tc:null})}var Qg=[],ts=[0,1,,1,null,1,!0,1,!1,1];function Qu(u){9<(u>>>=0)&&--ts[u+1]==0&&(ts[u]=void 0,Qg.push(u))}var Dt=u=>{if(!u)throw new Rs(`Cannot use deleted val. handle = ${u}`);return ts[u]},Qt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Qg.pop()||ts.length;return ts[f]=u,ts[f+1]=1,f}};function Xu(u){return this.Mc((x(),I)[u>>>2>>>0])}var bO={name:"emscripten::val",Mc:u=>{var f=Dt(u);return Qu(u),f},Sc:(u,f)=>Qt(f),Rc:Xu,Tc:null};function MO(u){return wr(u>>>0,bO)}var xO=(u,f)=>{switch(f){case 4:return function(m){return this.Mc((x(),te)[m>>>2>>>0])};case 8:return function(m){return this.Mc((x(),W)[m>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function kO(u,f,m){m>>>=0,wr(u>>>=0,{name:f=ar(f>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:xO(f,m),Tc:null})}function TO(u,f,m,g,b){u>>>=0,m>>>=0,f=ar(f>>>0);let E=O=>O;if(g===0){var F=32-8*m;E=O=>O<<F>>>F,b=E(b)}wr(u,{name:f,Mc:E,Sc:(O,j)=>j,Rc:Hg(f,m,g!==0),Tc:null})}function EO(u,f,m){function g(E){var F=(x(),I)[E>>>2>>>0];return E=(x(),I)[E+4>>>2>>>0],new b((x(),z).buffer,E,F)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];wr(u>>>=0,{name:m=ar(m>>>0),Mc:g,Rc:g},{de:!0})}var vr=(u,f,m)=>{var g=(x(),$);if(f>>>=0,0<m){var b=f;m=f+m-1;for(var E=0;E<u.length;++E){var F=u.codePointAt(E);if(127>=F){if(f>=m)break;g[f++>>>0]=F}else if(2047>=F){if(f+1>=m)break;g[f++>>>0]=192|F>>6,g[f++>>>0]=128|63&F}else if(65535>=F){if(f+2>=m)break;g[f++>>>0]=224|F>>12,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F}else{if(f+3>=m)break;g[f++>>>0]=240|F>>18,g[f++>>>0]=128|F>>12&63,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F,E++}}g[f>>>0]=0,u=f-b}else u=0;return u},yr=u=>{for(var f=0,m=0;m<u.length;++m){var g=u.charCodeAt(m);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++m):f+=3}return f};function AO(u,f){wr(u>>>=0,{name:f=ar(f>>>0),Mc(m){var g=(x(),I)[m>>>2>>>0];return g=Bs(m+4,g,!0),Xt(m),g},Sc(m,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Rs("Cannot pass non-string to std::string");var E=b?yr(g):g.length,F=$s(4+E+1),O=F+4;return(x(),I)[F>>>2>>>0]=E,b?vr(g,O,E+1):(x(),$).set(g,O>>>0),m!==null&&m.push(Xt,F),F},Rc:Xu,Tc(m){Xt(m)}})}var Xg=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,CO=(u,f,m)=>{if(u>>>=1,16<(f=Lg((x(),H),u,f/2,m))-u&&Xg)return Xg.decode((x(),H).slice(u,f));for(m="";u<f;++u){var g=(x(),H)[u>>>0];m+=String.fromCharCode(g)}return m},SO=(u,f,m)=>{if(m??(m=2147483647),2>m)return 0;var g=f;m=(m-=2)<2*u.length?m/2:u.length;for(var b=0;b<m;++b){var E=u.charCodeAt(b);(x(),Q)[f>>>1>>>0]=E,f+=2}return(x(),Q)[f>>>1>>>0]=0,f-g},PO=u=>2*u.length,FO=(u,f,m)=>{var g="";u>>>=2;for(var b=0;!(b>=f/4);b++){var E=(x(),I)[u+b>>>0];if(!E&&!m)break;g+=String.fromCodePoint(E)}return g},LO=(u,f,m)=>{if(f>>>=0,m??(m=2147483647),4>m)return 0;var g=f;m=g+m-4;for(var b=0;b<u.length;++b){var E=u.codePointAt(b);if(65535<E&&b++,(x(),D)[f>>>2>>>0]=E,(f+=4)+4>m)break}return(x(),D)[f>>>2>>>0]=0,f-g},IO=u=>{for(var f=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,f+=4;return f};function OO(u,f,m){if(u>>>=0,f>>>=0,m=ar(m>>>=0),f===2)var g=CO,b=SO,E=PO;else g=FO,b=LO,E=IO;wr(u,{name:m,Mc:F=>{var O=(x(),I)[F>>>2>>>0];return O=g(F+4,O*f,!0),Xt(F),O},Sc:(F,O)=>{if(typeof O!="string")throw new Rs(`Cannot pass non-string to C++ string type ${m}`);var j=E(O),Y=$s(4+j+f);return(x(),I)[Y>>>2>>>0]=j/f,b(O,Y+4,j+f),F!==null&&F.push(Xt,Y),Y},Rc:Xu,Tc(F){Xt(F)}})}function NO(u,f){wr(u>>>=0,{ee:!0,name:f=ar(f>>>0),Mc:()=>{},Sc:()=>{}})}function DO(u){dd(u>>>0,!s,1,!r,131072,!1),kg()}var gt=u=>{if(!S)try{if(u(),!(0<Me))try{n?go()&&hd(p):nr(p)}catch(f){f instanceof qe||f=="unwind"||l(0,f)}}catch(f){f instanceof qe||f=="unwind"||l(0,f)}},zO=!Atomics.waitAsync||((Av=globalThis.navigator)==null?void 0:Av.userAgent)&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Yu(u){u>>>=0,zO||(Atomics.waitAsync((x(),D),u>>>2,u).value.then(uo),u+=128,Atomics.store((x(),D),u>>>2,1))}var uo=()=>gt(()=>{var u=go();u&&(Yu(u),Dw())});function BO(u,f){(u>>>=0)==f>>>0?setTimeout(uo):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=es[u])&&u.postMessage({Oc:"checkMailbox"})}var Ju=[];function RO(u,f,m,g,b){for(f>>>=0,b>>>=0,Ju.length=0,m=b>>>3,g=b+g>>>3;m<g;){var E;E=(x(),ee)[m++>>>0]?(x(),ee)[m++>>>0]:(x(),W)[m++>>>0],Ju.push(E)}return(f?md[f]:M3[u])(...Ju)}var GO=()=>{Me=0};function $O(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):xg(es[u])}function VO(u){}var ho=u=>{try{u()}catch(f){we(f)}};function UO(u){var f=(...m)=>{fo.push(u);try{return u(...m)}finally{S||(fo.pop(),or&&zr===1&&fo.length===0&&(zr=0,Me+=1,ho(xv),typeof Fibers<"u"&&Fibers.Be()))}};return Kg.set(u,f),f}var zr=0,or=null,Yg=0,fo=[],Ku=new Map,Jg=new Map,Kg=new Map,jO=0,Zu=null,qO=[],Zg=u=>(function(f){if(!S){if(zr===0){var m=!1,g=!1;f((b=0)=>{if(!S&&(Yg=b,m=!0,g)){zr=2,ho(()=>kv(or)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var E=(function(){var j=(x(),D)[or+8>>>2>>>0];return j=Jg.get(j),j=Kg.get(j),--Me,j()})()}catch(j){E=j,b=!0}var F=!1;if(!or){var O=Zu;O&&(Zu=null,(b?O.reject:O.resolve)(E),F=!0)}if(b&&!F)throw E}}),g=!0,m||(zr=1,or=(function(){var b=$s(65548),E=b+12;if((x(),I)[b>>>2>>>0]=E,(x(),I)[b+4>>>2>>>0]=E+65536,E=fo[0],!Ku.has(E)){var F=jO++;Ku.set(E,F),Jg.set(F,E)}return E=Ku.get(E),(x(),D)[b+8>>>2>>>0]=E,b})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),ho(()=>Mv(or)))}else zr===2?(zr=0,ho(Tv),Xt(or),or=null,qO.forEach(gt)):we(`invalid state: ${zr}`);return Yg}})(f=>{u().then(f)});function WO(u){return u>>>=0,Zg(async()=>{var f=await Dt(u);return Qt(f)})}var ed=[],HO=u=>{var f=ed.length;return ed.push(u),f},QO=(u,f)=>{for(var m=Array(u),g=0;g<u;++g){var b=g,E=(x(),I)[f+4*g>>>2>>>0],F=Hu[E];if(F===void 0)throw u=`parameter ${g}`,E=ww(E),f=ar(E),Xt(E),new Rs(`${u} has unknown type ${f}`);m[b]=F}return m},XO=(u,f,m)=>{var g=[];return u=u(g,m),g.length&&((x(),I)[f>>>2>>>0]=Qt(g)),u},YO={},_o=u=>{var f=YO[u];return f===void 0?ar(u):f};function JO(u,f,m){var[g,...b]=QO(u,f>>>0);f=g.Sc.bind(g);var E=b.map(j=>j.Rc.bind(j));u--;var F={toValue:Dt};switch(u=E.map((j,Y)=>{var ye=`argFromPtr${Y}`;return F[ye]=j,`${ye}(args${Y?"+"+8*Y:""})`}),m){case 0:var O="toValue(handle)";break;case 2:O="new (toValue(handle))";break;case 3:O="";break;case 1:F.getStringOrSymbol=_o,O="toValue(handle)[getStringOrSymbol(methodName)]"}return O+=`(${u})`,g.ee||(F.toReturnWire=f,F.emval_returnValue=XO,O=`return emval_returnValue(toReturnWire, destructorsRef, ${O})`),O=`return function (handle, methodName, destructorsRef, args) {
6
- ${O}
7
- }`,m=new Function(Object.keys(F),O)(...Object.values(F)),O=`methodCaller<(${b.map(j=>j.name)}) => ${g.name}>`,HO(Object.defineProperty(m,"name",{value:O}))}function KO(u,f){return f>>>=0,(u=Dt(u>>>0))==Dt(f)}function ZO(u){return(u>>>=0)?(u=_o(u),Qt(globalThis[u])):Qt(globalThis)}function eN(u){return u=_o(u>>>0),Qt(t[u])}function tN(u,f){return f>>>=0,u=Dt(u>>>0),f=Dt(f),Qt(u[f])}function rN(u){9<(u>>>=0)&&(ts[u+1]+=1)}function ew(u,f,m,g,b){return ed[u>>>0](f>>>0,m>>>0,g>>>0,b>>>0)}function sN(u,f,m,g,b){return ew(u>>>0,f>>>0,m>>>0,g>>>0,b>>>0)}function nN(){return Qt([])}function aN(u){u=Dt(u>>>0);for(var f=Array(u.length),m=0;m<u.length;m++)f[m]=u[m];return Qt(f)}function oN(u){return Qt(_o(u>>>0))}function iN(){return Qt({})}function lN(u){for(var f=Dt(u>>>=0);f.length;){var m=f.pop();f.pop()(m)}Qu(u)}function cN(u,f,m){f>>>=0,m>>>=0,u=Dt(u>>>0),f=Dt(f),m=Dt(m),u[f]=m}function uN(u,f){u=ot(u),f>>>=0,u=new Date(1e3*u),(x(),D)[f>>>2>>>0]=u.getUTCSeconds(),(x(),D)[f+4>>>2>>>0]=u.getUTCMinutes(),(x(),D)[f+8>>>2>>>0]=u.getUTCHours(),(x(),D)[f+12>>>2>>>0]=u.getUTCDate(),(x(),D)[f+16>>>2>>>0]=u.getUTCMonth(),(x(),D)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(x(),D)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),D)[f+28>>>2>>>0]=u}var tw=u=>u%4==0&&(u%100!=0||u%400==0),rw=[0,31,60,91,121,152,182,213,244,274,305,335],sw=[0,31,59,90,120,151,181,212,243,273,304,334];function dN(u,f){u=ot(u),f>>>=0,u=new Date(1e3*u),(x(),D)[f>>>2>>>0]=u.getSeconds(),(x(),D)[f+4>>>2>>>0]=u.getMinutes(),(x(),D)[f+8>>>2>>>0]=u.getHours(),(x(),D)[f+12>>>2>>>0]=u.getDate(),(x(),D)[f+16>>>2>>>0]=u.getMonth(),(x(),D)[f+20>>>2>>>0]=u.getFullYear()-1900,(x(),D)[f+24>>>2>>>0]=u.getDay();var m=(tw(u.getFullYear())?rw:sw)[u.getMonth()]+u.getDate()-1|0;(x(),D)[f+28>>>2>>>0]=m,(x(),D)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),m=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(m!=g&&u.getTimezoneOffset()==Math.min(g,m)),(x(),D)[f+32>>>2>>>0]=u}function hN(u){u>>>=0;var f=new Date((x(),D)[u+20>>>2>>>0]+1900,(x(),D)[u+16>>>2>>>0],(x(),D)[u+12>>>2>>>0],(x(),D)[u+8>>>2>>>0],(x(),D)[u+4>>>2>>>0],(x(),D)[u>>>2>>>0],0),m=(x(),D)[u+32>>>2>>>0],g=f.getTimezoneOffset(),b=new Date(f.getFullYear(),6,1).getTimezoneOffset(),E=new Date(f.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(E,b);return 0>m?(x(),D)[u+32>>>2>>>0]=+(b!=E&&F==g):0<m!=(F==g)&&(b=Math.max(E,b),f.setTime(f.getTime()+6e4*((0<m?F:b)-g))),(x(),D)[u+24>>>2>>>0]=f.getDay(),m=(tw(f.getFullYear())?rw:sw)[f.getMonth()]+f.getDate()-1|0,(x(),D)[u+28>>>2>>>0]=m,(x(),D)[u>>>2>>>0]=f.getSeconds(),(x(),D)[u+4>>>2>>>0]=f.getMinutes(),(x(),D)[u+8>>>2>>>0]=f.getHours(),(x(),D)[u+12>>>2>>>0]=f.getDate(),(x(),D)[u+16>>>2>>>0]=f.getMonth(),(x(),D)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function nw(u,f,m,g,b,E,F){return n?ce(16,1,u,f,m,g,b,E,F):-52}function aw(u,f,m,g,b,E){if(n)return ce(17,1,u,f,m,g,b,E)}var On={},fN=()=>performance.timeOrigin+performance.now();function ow(u,f){if(n)return ce(18,1,u,f);if(On[u]&&(clearTimeout(On[u].id),delete On[u]),!f)return 0;var m=setTimeout(()=>{delete On[u],gt(()=>Nw(u,performance.timeOrigin+performance.now()))},f);return On[u]={id:m,Ae:f},0}function _N(u,f,m,g){u>>>=0,f>>>=0,m>>>=0,g>>>=0;var b=new Date().getFullYear(),E=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var F=Math.max(E,b);(x(),I)[u>>>2>>>0]=60*F,(x(),D)[f>>>2>>>0]=+(E!=b),u=(f=O=>{var j=Math.abs(O);return`UTC${0<=O?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(E),f=f(b),b<E?(vr(u,m,17),vr(f,g,17)):(vr(u,g,17),vr(f,m,17))}var pN=()=>Date.now();function mN(u,f,m){return m>>>=0,0<=u&&3>=u?(u===0?u=Date.now():u=performance.timeOrigin+performance.now(),u=Math.round(1e6*u),(x(),ee)[m>>>3>>>0]=BigInt(u),0):28}var td=[],iw=(u,f)=>{td.length=0;for(var m;m=(x(),$)[u++>>>0];){var g=m!=105;f+=(g&=m!=112)&&f%8?4:0,td.push(m==112?(x(),I)[f>>>2>>>0]:m==106?(x(),ee)[f>>>3>>>0]:m==105?(x(),D)[f>>>2>>>0]:(x(),W)[f>>>3>>>0]),f+=g?8:4}return td};function gN(u,f,m){return u>>>=0,f=iw(f>>>0,m>>>0),md[u](...f)}function wN(u,f,m){return u>>>=0,f=iw(f>>>0,m>>>0),md[u](...f)}var vN=()=>{};function yN(u,f){return C(Bs(u>>>0,f>>>0))}var bN=()=>{throw Me+=1,"unwind"};function MN(){return 4294901760}var xN=()=>1,kN=()=>navigator.hardwareConcurrency;function TN(u){u>>>=0;var f=(x(),$).length;if(u<=f||4294901760<u)return!1;for(var m=1;4>=m;m*=2){var g=f*(1+.2/m);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Dr.buffer.byteLength+65535)/65536|0;try{Dr.grow(g),X();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var ir=u=>{var f=yr(u)+1,m=wo(f);return vr(u,m,f),m},rd=(u,f)=>{(x(),I)[u>>>2>>>0]=f;var m=(x(),I)[u>>>2>>>0];(x(),I)[u+4>>>2>>>0]=(f-m)/4294967296},Nn=u=>(x(),I)[u>>>2>>>0]+4294967296*(x(),D)[u+4>>>2>>>0],it=[],EN=(u,f)=>{it[u>>>0]=f},br=[],po=[],Gs=(u,f)=>{po[u]=new Promise(m=>f.finally(()=>m(u)))},se=u=>{if(u)return it[u>>>0]},AN=(u,f)=>{for(u=(x(),I)[u>>>2>>>0];u;u=(x(),I)[u>>>2>>>0])f[(x(),D)[u+4>>>2>>>0]](u)},mo=(u,f,m)=>{(x(),I)[u>>>2>>>0]=f,(x(),I)[u+4>>>2>>>0]=m},lw=u=>{var f=(x(),I)[u>>>2>>>0];return u=(x(),I)[u+4>>>2>>>0],Bs(f,u)},Mr=u=>{var f=(x(),I)[u>>>2>>>0];return u=(x(),I)[u+4>>>2>>>0],f?Bs(f,u):u===0?"":void 0},CN=u=>{var f=Mr(u+4),m=(m=(x(),I)[u+12>>>2>>>0])?se(m):"auto";if(u+=16){var g=se((x(),I)[u+4>>>2>>>0]),b=(x(),I)[u+16>>>2>>>0],E=(x(),I)[u+20>>>2>>>0];if(b){for(var F={},O=0;O<b;++O){var j=E+24*O;F[lw(j+4)]=(x(),W)[j+16>>>3>>>0]}b=F}else b=void 0;u={module:g,constants:b,entryPoint:Mr(u+8)}}else u=void 0;return{label:f,layout:m,compute:u}},cw=(u,f)=>{function m(g,b){g=u[g],(x(),I)[f+b>>>2>>>0]=g}m("maxTextureDimension1D",4),m("maxTextureDimension2D",8),m("maxTextureDimension3D",12),m("maxTextureArrayLayers",16),m("maxBindGroups",20),m("maxBindGroupsPlusVertexBuffers",24),m("maxBindingsPerBindGroup",28),m("maxDynamicUniformBuffersPerPipelineLayout",32),m("maxDynamicStorageBuffersPerPipelineLayout",36),m("maxSampledTexturesPerShaderStage",40),m("maxSamplersPerShaderStage",44),m("maxStorageBuffersPerShaderStage",48),m("maxStorageTexturesPerShaderStage",52),m("maxUniformBuffersPerShaderStage",56),m("minUniformBufferOffsetAlignment",80),m("minStorageBufferOffsetAlignment",84),rd(f+64,u.maxUniformBufferBindingSize),rd(f+72,u.maxStorageBufferBindingSize),m("maxVertexBuffers",88),rd(f+96,u.maxBufferSize),m("maxVertexAttributes",104),m("maxVertexBufferArrayStride",108),m("maxInterStageShaderVariables",112),m("maxColorAttachments",116),m("maxColorAttachmentBytesPerSample",120),m("maxComputeWorkgroupStorageSize",124),m("maxComputeInvocationsPerWorkgroup",128),m("maxComputeWorkgroupSizeX",132),m("maxComputeWorkgroupSizeY",136),m("maxComputeWorkgroupSizeZ",140),m("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&m("maxImmediateSize",148)},SN=[,"validation","out-of-memory","internal"],PN=[,"compatibility","core"],uw={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"},FN=[,"low-power","high-performance"],LN=[,"occlusion","timestamp"],IN={undefined:1,unknown:1,destroyed:2};function ON(u,f,m,g,b,E){f=ot(f),m=ot(m),g>>>=0,b>>>=0,E>>>=0;var F=se(u>>>0);if(u={},E){var O=(x(),I)[E+12>>>2>>>0];if(O){var j=(x(),I)[E+16>>>2>>>0];u.requiredFeatures=Array.from((x(),I).subarray(j>>>2>>>0,j+4*O>>>2>>>0),K=>uw[K])}var Y=(x(),I)[E+20>>>2>>>0];if(Y){let K=function(Le,et,Bn=!1){et=Y+et,(et=(x(),I)[et>>>2>>>0])==4294967295||Bn&&et==0||(ye[Le]=et)},_e=function(Le,et){et=Y+et;var Bn=(x(),I)[et>>>2>>>0],gd=(x(),I)[et+4>>>2>>>0];Bn==4294967295&&gd==4294967295||(ye[Le]=Nn(et))};var ye={};K("maxTextureDimension1D",4),K("maxTextureDimension2D",8),K("maxTextureDimension3D",12),K("maxTextureArrayLayers",16),K("maxBindGroups",20),K("maxBindGroupsPlusVertexBuffers",24),K("maxDynamicUniformBuffersPerPipelineLayout",32),K("maxDynamicStorageBuffersPerPipelineLayout",36),K("maxSampledTexturesPerShaderStage",40),K("maxSamplersPerShaderStage",44),K("maxStorageBuffersPerShaderStage",48),K("maxStorageTexturesPerShaderStage",52),K("maxUniformBuffersPerShaderStage",56),K("minUniformBufferOffsetAlignment",80),K("minStorageBufferOffsetAlignment",84),_e("maxUniformBufferBindingSize",64),_e("maxStorageBufferBindingSize",72),K("maxVertexBuffers",88),_e("maxBufferSize",96),K("maxVertexAttributes",104),K("maxVertexBufferArrayStride",108),K("maxInterStageShaderVariables",112),K("maxColorAttachments",116),K("maxColorAttachmentBytesPerSample",120),K("maxComputeWorkgroupStorageSize",124),K("maxComputeInvocationsPerWorkgroup",128),K("maxComputeWorkgroupSizeX",132),K("maxComputeWorkgroupSizeY",136),K("maxComputeWorkgroupSizeZ",140),K("maxComputeWorkgroupsPerDimension",144),K("maxImmediateSize",148,!0),u.requiredLimits=ye}(O=(x(),I)[E+24>>>2>>>0])&&(O={label:Mr(O+4)},u.defaultQueue=O),u.label=Mr(E+4)}Me+=1,Gs(f,F.requestDevice(u).then(K=>{--Me,gt(()=>{it[b>>>0]=K.queue,it[g>>>0]=K,Me+=1,Gs(m,K.lost.then(_e=>{gt(()=>{K.onuncapturederror=()=>{};var Le=ae(),et=ir(_e.message);id(m,IN[_e.reason],et),ne(Le)}),--Me})),K.onuncapturederror=_e=>{var Le=5;_e.error instanceof GPUValidationError?Le=2:_e.error instanceof GPUOutOfMemoryError?Le=3:_e.error instanceof GPUInternalError&&(Le=4);var et=ae();_e=ir(_e.error.message),Fw(g,Le,_e),ne(et)},"adapterInfo"in K||(K.adapterInfo=F.info),ud(f,1,g,0)})},K=>{--Me,gt(()=>{var _e=ae(),Le=ir(K.message);ud(f,3,g,Le),m&&id(m,4,Le),ne(_e)})}))}function NN(u){var f=se(u>>>=0),m=br[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete br[u]}f.destroy()}function DN(u,f,m){m>>>=0;var g=se(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=fd(16,b.byteLength);return(x(),$).set(new Uint8Array(b),E>>>0),br[u].push(()=>Xt(E)),E}function zN(u,f,m){m>>>=0;var g=se(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=fd(16,b.byteLength);return(x(),$).fill(0,E,b.byteLength),br[u].push(()=>{new Uint8Array(b).set((x(),$).subarray(E>>>0,E+b.byteLength>>>0)),Xt(E)}),E}function BN(u,f,m,g,b){u>>>=0,f=ot(f),m=ot(m),b>>>=0;var E=se(u);br[u]=[],b==4294967295&&(b=void 0),Me+=1,Gs(f,E.mapAsync(m,g>>>0,b).then(()=>{--Me,gt(()=>{ld(f,1,0)})},F=>{--Me,gt(()=>{ae();var O=ir(F.message);ld(f,F.name==="AbortError"?4:F.name==="OperationError"?3:0,O),delete br[u]})}))}function RN(u){var f=se(u>>>=0),m=br[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete br[u],f.unmap()}}function GN(u){delete it[u>>>0]}function $N(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=!!(x(),I)[f+32>>>2>>>0];f={label:Mr(f+4),usage:(x(),I)[f+16>>>2>>>0],size:Nn(f+24),mappedAtCreation:g},u=se(u);try{var b=u.createBuffer(f)}catch{return!1}return it[m>>>0]=b,g&&(br[m]=[]),!0}function VN(u,f,m,g){u>>>=0,f=ot(f),g>>>=0,m=CN(m>>>0),u=se(u),Me+=1,Gs(f,u.createComputePipelineAsync(m).then(b=>{--Me,gt(()=>{it[g>>>0]=b,od(f,1,g,0)})},b=>{--Me,gt(()=>{var E=ae(),F=ir(b.message);od(f,b.reason==="validation"?3:b.reason==="internal"?4:0,g,F),ne(E)})}))}function UN(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=(x(),I)[f>>>2>>>0],b=(x(),D)[g+4>>>2>>>0];f={label:Mr(f+4),code:""},b===2&&(f.code=lw(g+8)),u=se(u).createShaderModule(f),it[m>>>0]=u}var jN=u=>{(u=se(u)).onuncapturederror=null,u.destroy()};function qN(u,f){f=ot(f),u=se(u>>>0),Me+=1,Gs(f,u.popErrorScope().then(m=>{--Me,gt(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var b=ae(),E=m?ir(m.message):0;cd(f,1,g,E),ne(b)})},m=>{--Me,gt(()=>{var g=ae(),b=ir(m.message);cd(f,1,5,b),ne(g)})}))}function WN(u,f,m,g){if(f=ot(f),g>>>=0,m>>>=0){var b={featureLevel:PN[(x(),D)[m+4>>>2>>>0]],powerPreference:FN[(x(),D)[m+8>>>2>>>0]],forceFallbackAdapter:!!(x(),I)[m+12>>>2>>>0]};(u=(x(),I)[m>>>2>>>0])!==0&&(x(),b.De=!!(x(),I)[u+8>>>2>>>0])}"gpu"in navigator?(Me+=1,Gs(f,navigator.gpu.requestAdapter(b).then(E=>{--Me,gt(()=>{if(E)it[g>>>0]=E,Dn(f,1,g,0);else{var F=ae(),O=ir("WebGPU not available on this browser (requestAdapter returned null)");Dn(f,3,g,O),ne(F)}})},E=>{--Me,gt(()=>{var F=ae(),O=ir(E.message);Dn(f,4,g,O),ne(F)})}))):(b=ae(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),Dn(f,3,g,u),ne(b))}function HN(u,f,m){return u>>>=0,f>>>=0,m>>>=0,Zg(async()=>{var g=[];if(m){var b=(x(),D)[m>>>2>>>0];g.length=f+1,g[f]=new Promise(O=>setTimeout(O,b,0))}else g.length=f;for(var E=0;E<f;++E){var F=Nn(u+8*E);if(!(F in po))return F;g[E]=po[F]}return g=await Promise.race(g),delete po[g],g})}var sd,nd={},dw=()=>{var g;if(!sd){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(((g=globalThis.navigator)==null?void 0:g.language)??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in nd)nd[u]===void 0?delete f[u]:f[u]=nd[u];var m=[];for(u in f)m.push(`${u}=${f[u]}`);sd=m}return sd};function hw(u,f){if(n)return ce(19,1,u,f);u>>>=0,f>>>=0;var m,g=0,b=0;for(m of dw()){var E=f+g;(x(),I)[u+b>>>2>>>0]=E,g+=vr(m,E,1/0)+1,b+=4}return 0}function fw(u,f){if(n)return ce(20,1,u,f);u>>>=0,f>>>=0;var m=dw();for(var g of((x(),I)[u>>>2>>>0]=m.length,u=0,m))u+=yr(g)+1;return(x(),I)[f>>>2>>>0]=u,0}function _w(u){return n?ce(21,1,u):52}function pw(u,f,m,g){return n?ce(22,1,u,f,m,g):52}function mw(u,f,m,g){return n?ce(23,1,u,f,m,g):70}var QN=[null,[],[]];function gw(u,f,m,g){if(n)return ce(24,1,u,f,m,g);f>>>=0,m>>>=0,g>>>=0;for(var b=0,E=0;E<m;E++){var F=(x(),I)[f>>>2>>>0],O=(x(),I)[f+4>>>2>>>0];f+=8;for(var j=0;j<O;j++){var Y=u,ye=(x(),$)[F+j>>>0],K=QN[Y];ye===0||ye===10?((Y===1?A:C)(Ig(K)),K.length=0):K.push(ye)}b+=O}return(x(),I)[g>>>2>>>0]=b,0}function XN(u){return u>>>0}function YN(u,f){return cw(se(u>>>0).limits,f>>>0),1}function JN(u,f){return se(u>>>0).features.has(uw[f])}function KN(u){return BigInt(se(u>>>0).size)}function ZN(u){return BigInt(se(u>>>0).usage)}function e3(u,f){if(u>>>=0,f>>>=0){var m=Mr(f+4);m={label:m,timestampWrites:f=(f=(x(),I)[f+12>>>2>>>0])!==0?{querySet:se((x(),I)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(x(),I)[f+8>>>2>>>0],endOfPassWriteIndex:(x(),I)[f+12>>>2>>>0]}:void 0}}return f=se(u),u=Ew(0),m=f.beginComputePass(m),it[u>>>0]=m,u}function t3(u,f,m,g){m=ot(m),(g=ot(g))==-1&&(g=void 0),(u=se(u>>>0)).clearBuffer(se(f>>>0),m,g)}function r3(u,f,m,g,b,E){m=ot(m),b=ot(b),E=ot(E),se(u>>>0).copyBufferToBuffer(se(f>>>0),m,se(g>>>0),b,E)}function s3(u){var f=se(u>>>0);return u=kw(0),f=f.finish(),it[u>>>0]=f,u}function n3(u,f,m,g,b,E){E=ot(E),se(u>>>0).resolveQuerySet(se(f>>>0),m,g,se(b>>>0),E)}function a3(u,f,m,g){se(u>>>0).dispatchWorkgroups(f,m,g)}function o3(u,f,m){m=ot(m),se(u>>>0).dispatchWorkgroupsIndirect(se(f>>>0),m)}function i3(u){se(u>>>0).end()}function l3(u,f,m,g,b){g>>>=0,b>>>=0,u=se(u>>>0),m=se(m>>>0),g==0?u.setBindGroup(f,m):u.setBindGroup(f,m,(x(),I),b>>>2,g)}function c3(u,f){se(u>>>0).setPipeline(se(f>>>0))}function u3(u,f,m){se(u>>>0).Ce(se(f>>>0),m)}function d3(u,f){var m=se(u>>>0);return u=xw(0),f=m.getBindGroupLayout(f),it[u>>>0]=f,u}function h3(u,f){function m(b){var E=(x(),I)[b+8>>>2>>>0],F=(x(),I)[b+32>>>2>>>0],O=(x(),I)[b+36>>>2>>>0],j=0;return AN(b,{327681:Y=>{j=(x(),I)[Y+8>>>2>>>0]}}),E?((F=Nn(b+24))==-1&&(F=void 0),E={buffer:se(E),offset:Nn(b+16),size:F}):E=se(F||O||j),{binding:(x(),I)[b+4>>>2>>>0],resource:E}}u>>>=0,f={label:Mr(4+(f>>>=0)),layout:se((x(),I)[f+12>>>2>>>0]),entries:(function(b,E){for(var F=[],O=0;O<b;++O)F.push(m(E+40*O));return F})((x(),I)[f+16>>>2>>>0],(x(),I)[f+20>>>2>>>0])},u=se(u);var g=Mw(0);return EN(g,u.createBindGroup(f)),g}function f3(u,f){var m;return u>>>=0,(f>>>=0)&&(m={label:Mr(f+4)}),f=se(u),u=Tw(0),m=f.createCommandEncoder(m),it[u>>>0]=m,u}function _3(u,f){u>>>=0,f>>>=0,f={type:LN[(x(),D)[f+12>>>2>>>0]],count:(x(),I)[f+16>>>2>>>0]};var m=se(u);return u=Aw(0),f=m.createQuerySet(f),it[u>>>0]=f,u}function p3(u,f){u=se(u>>>0).adapterInfo,f>>>=0,(x(),I)[f+52>>>2>>>0]=u.subgroupMinSize,(x(),I)[f+56>>>2>>>0]=u.subgroupMaxSize;var m=u.vendor+u.architecture+u.device+u.description,g=yr(m)+1,b=$s(g);return b&&vr(m,b,g),m=b,g=yr(u.vendor),mo(f+4,m,g),m+=g,g=yr(u.architecture),mo(f+12,m,g),m+=g,g=yr(u.device),mo(f+20,m,g),mo(f+28,m+g,yr(u.description)),(x(),D)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(x(),D)[f+40>>>2>>>0]=u,(x(),I)[f+44>>>2>>>0]=0,(x(),I)[f+48>>>2>>>0]=0,1}var m3={"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 g3(u,f){f>>>=0;var m=se(u>>>0);u=$s(4*m.features.size);var g=0,b=0;for(let E of m.features)0<=(m=m3[E])&&((x(),D)[u+g>>>2>>>0]=m,g+=4,b++);(x(),I)[f+4>>>2>>>0]=u,(x(),I)[f>>>2>>>0]=b}function w3(u,f){return cw(se(u>>>0).limits,f>>>0),1}function v3(u,f){se(u>>>0).pushErrorScope(SN[f])}function y3(u,f,m){f>>>=0,m>>>=0,u=se(u>>>0),f=Array.from((x(),D).subarray(m>>>2>>>0,m+4*f>>>2>>>0),g=>se(g)),u.submit(f)}function b3(u,f,m,g,b){m=ot(m),g>>>=0,b>>>=0,u=se(u>>>0),f=se(f>>>0),g=(x(),$).subarray(g>>>0,g+b>>>0),u.writeBuffer(f,m,g,0,b)}n||(function(){for(var u=t.numThreads-1;u--;)Eg();It.push(async()=>{var f=(async function(){if(!n)return Promise.all(Nt.map(Tg))})();Ot++,await f,--Ot==0&&Qe&&(f=Qe,Qe=null,f())})})(),n||(Dr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),X()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>ae(),t.stackRestore=u=>ne(u),t.stackAlloc=u=>wo(u),t.setValue=function(u,f,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":(x(),z)[u>>>0]=f;break;case"i16":(x(),Q)[u>>>1>>>0]=f;break;case"i32":(x(),D)[u>>>2>>>0]=f;break;case"i64":(x(),ee)[u>>>3>>>0]=BigInt(f);break;case"float":(x(),te)[u>>>2>>>0]=f;break;case"double":(x(),W)[u>>>3>>>0]=f;break;case"*":(x(),I)[u>>>2>>>0]=f;break;default:we(`invalid type for setValue: ${m}`)}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(x(),z)[u>>>0];case"i16":return(x(),Q)[u>>>1>>>0];case"i32":return(x(),D)[u>>>2>>>0];case"i64":return(x(),ee)[u>>>3>>>0];case"float":return(x(),te)[u>>>2>>>0];case"double":return(x(),W)[u>>>3>>>0];case"*":return(x(),I)[u>>>2>>>0];default:we(`invalid type for getValue: ${f}`)}},t.UTF8ToString=Bs,t.stringToUTF8=vr,t.lengthBytesUTF8=yr;var ww,vw,ad,go,Xt,$s,yw,bw,Mw,xw,kw,Tw,Ew,Aw,Cw,Sw,Pw,od,id,ld,cd,Dn,ud,Fw,dd,Lw,Iw,Ow,hd,Nw,Dw,fd,pe,zn,zw,ne,wo,ae,Bw,_d,Rw,Gw,$w,pd,Vw,Uw,jw,qw,Ww,Hw,Qw,Xw,Yw,Jw,Kw,Zw,ev,tv,rv,sv,nv,av,ov,iv,lv,cv,uv,dv,hv,fv,_v,pv,mv,gv,wv,vv,yv,bv,Mv,xv,kv,Tv,xr,M3=[Pe,mt,Sg,Og,Ng,Dg,zg,Bg,Rg,Gg,$g,Vg,Ug,jg,qg,Wg,nw,aw,ow,hw,fw,_w,pw,mw,gw],md={969132:(u,f,m,g,b)=>{if(t===void 0||!t.Uc)return 1;if((u=Bs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.get(u)))return 2;if(f=Number(f>>>0),m=Number(m>>>0),g=Number(g>>>0),f+m>u.byteLength)return 3;try{let E=u.subarray(f,f+m);switch(b){case 0:(x(),$).set(E,g>>>0);break;case 1:t.ad?t.ad(g,E):t.ne(g,E);break;default:return 4}return 0}catch{return 4}},969956:(u,f,m)=>{t.Sd(u,(x(),$).subarray(f>>>0,f+m>>>0))},970020:()=>t.le(),970062:u=>{t.jd(u)},970099:()=>typeof wasmOffsetConverter<"u"};function x3(u,f,m,g){var b=ae();try{return Xw(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function k3(u,f,m){var g=ae();try{return Ww(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;pe(1,0)}}function T3(u){var f=ae();try{Vw(u)}catch(m){if(ne(f),m!==m+0)throw m;pe(1,0)}}function E3(u,f){var m=ae();try{return pd(u,f)}catch(g){if(ne(m),g!==g+0)throw g;pe(1,0)}}function A3(u,f,m){var g=ae();try{$w(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;pe(1,0)}}function C3(u,f){var m=ae();try{Yw(u,f)}catch(g){if(ne(m),g!==g+0)throw g;pe(1,0)}}function S3(u,f,m,g,b,E,F){var O=ae();try{return qw(u,f,m,g,b,E,F)}catch(j){if(ne(O),j!==j+0)throw j;pe(1,0)}}function P3(u,f,m,g,b,E){var F=ae();try{Uw(u,f,m,g,b,E)}catch(O){if(ne(F),O!==O+0)throw O;pe(1,0)}}function F3(u,f,m,g){var b=ae();try{Qw(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function L3(u,f,m,g,b,E,F){var O=ae();try{Kw(u,f,m,g,b,E,F)}catch(j){if(ne(O),j!==j+0)throw j;pe(1,0)}}function I3(u,f,m,g,b,E,F){var O=ae();try{Zw(u,f,m,g,b,E,F)}catch(j){if(ne(O),j!==j+0)throw j;pe(1,0)}}function O3(u,f,m,g,b,E,F,O){var j=ae();try{lv(u,f,m,g,b,E,F,O)}catch(Y){if(ne(j),Y!==Y+0)throw Y;pe(1,0)}}function N3(u,f,m,g,b,E,F,O,j,Y,ye,K){var _e=ae();try{ev(u,f,m,g,b,E,F,O,j,Y,ye,K)}catch(Le){if(ne(_e),Le!==Le+0)throw Le;pe(1,0)}}function D3(u,f,m,g,b){var E=ae();try{return Jw(u,f,m,g,b)}catch(F){if(ne(E),F!==F+0)throw F;pe(1,0)}}function z3(u,f,m,g,b){var E=ae();try{jw(u,f,m,g,b)}catch(F){if(ne(E),F!==F+0)throw F;pe(1,0)}}function B3(u,f,m,g,b,E,F,O){var j=ae();try{Hw(u,f,m,g,b,E,F,O)}catch(Y){if(ne(j),Y!==Y+0)throw Y;pe(1,0)}}function R3(u){var f=ae();try{return cv(u)}catch(m){if(ne(f),m!==m+0)throw m;pe(1,0)}}function G3(u,f,m){var g=ae();try{return uv(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;pe(1,0)}}function $3(u,f){var m=ae();try{return bv(u,f)}catch(g){if(ne(m),g!==g+0)throw g;return pe(1,0),0n}}function V3(u){var f=ae();try{return tv(u)}catch(m){if(ne(f),m!==m+0)throw m;return pe(1,0),0n}}function U3(u,f,m,g){var b=ae();try{return dv(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function j3(u,f,m,g,b){var E=ae();try{return hv(u,f,m,g,b)}catch(F){if(ne(E),F!==F+0)throw F;pe(1,0)}}function q3(u,f,m,g,b,E){var F=ae();try{return fv(u,f,m,g,b,E)}catch(O){if(ne(F),O!==O+0)throw O;pe(1,0)}}function W3(u,f,m,g,b,E){var F=ae();try{return ov(u,f,m,g,b,E)}catch(O){if(ne(F),O!==O+0)throw O;pe(1,0)}}function H3(u,f,m,g,b,E){var F=ae();try{return _v(u,f,m,g,b,E)}catch(O){if(ne(F),O!==O+0)throw O;pe(1,0)}}function Q3(u,f,m,g,b,E,F,O){var j=ae();try{return iv(u,f,m,g,b,E,F,O)}catch(Y){if(ne(j),Y!==Y+0)throw Y;pe(1,0)}}function X3(u,f,m,g,b){var E=ae();try{return pv(u,f,m,g,b)}catch(F){if(ne(E),F!==F+0)throw F;return pe(1,0),0n}}function Y3(u,f,m,g){var b=ae();try{return mv(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function J3(u,f,m,g){var b=ae();try{return gv(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function K3(u,f,m,g,b,E,F,O,j,Y,ye,K){var _e=ae();try{return wv(u,f,m,g,b,E,F,O,j,Y,ye,K)}catch(Le){if(ne(_e),Le!==Le+0)throw Le;pe(1,0)}}function Z3(u,f,m,g,b,E,F,O,j,Y,ye){var K=ae();try{vv(u,f,m,g,b,E,F,O,j,Y,ye)}catch(_e){if(ne(K),_e!==_e+0)throw _e;pe(1,0)}}function eD(u,f,m,g,b,E,F,O,j,Y,ye,K,_e,Le,et,Bn){var gd=ae();try{yv(u,f,m,g,b,E,F,O,j,Y,ye,K,_e,Le,et,Bn)}catch(wd){if(ne(gd),wd!==wd+0)throw wd;pe(1,0)}}function tD(u,f,m){var g=ae();try{return sv(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;return pe(1,0),0n}}function rD(u,f,m){var g=ae();try{return rv(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;pe(1,0)}}function sD(u,f,m){var g=ae();try{return nv(u,f,m)}catch(b){if(ne(g),b!==b+0)throw b;pe(1,0)}}function nD(u,f,m,g){var b=ae();try{av(u,f,m,g)}catch(E){if(ne(b),E!==E+0)throw E;pe(1,0)}}function vo(){if(0<Ot)Qe=vo;else if(n)w==null||w(t),J();else{for(var u=It;0<u.length;)u.shift()(t);0<Ot?Qe=vo:(t.calledRun=!0,S||(J(),w==null||w(t)))}}return n||(xr=await Fe(),vo()),t.PTR_SIZE=4,t.webgpuInit=u=>{let f=new WeakMap,m,g,b=1;t.webgpuRegisterDevice=O=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(O){var j=f.get(O);if(!j){let Y=((ye,K=0)=>{var _e=Pw(K);return K=Sw(K,_e),it[_e>>>0]=ye.queue,it[K>>>0]=ye,K})(O,j=bw(0));j=[b++,j,Y],f.set(O,j)}return m=O,g=j[0],j}m=void 0,g=0};let E=new Map;t.webgpuOnCreateSession=O=>{if(g!==void 0){var j=g;if(g=void 0,O){let Y=ad(j);E.set(O,Y),j===0&&u(m??se(Y))}m=void 0}},t.webgpuOnReleaseSession=O=>{E.delete(O)};let F=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(O,j,Y)=>{if(Y)return O[F]=[Y,NaN],Y;if(Y=O[F])return Y[1]++,Y[0];if((j=E.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((ye,K=0)=>(ye.mapState==="unmapped"||we(),K=Cw(K),it[K>>>0]=ye,K))(O,j),O[F]=[j,1],j},t.webgpuUnregisterBuffer=O=>{let j=O[F];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(yw(j[0]),delete O[F])},t.webgpuGetBuffer=O=>se(O),t.webgpuCreateDownloader=(O,j,Y)=>{if((Y=E.get(Y))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ye=se(Y),K=16*Math.ceil(Number(j)/16);return async()=>{let _e=ye.createBuffer({size:K,usage:9});try{let Le=ye.createCommandEncoder();return Le.copyBufferToBuffer(O,0,_e,0,K),ye.queue.submit([Le.finish()]),await _e.mapAsync(GPUMapMode.READ),_e.getMappedRange().slice(0,j)}finally{_e.destroy()}}},t.ad=(O,j)=>{var Y=j.buffer;let ye=j.byteOffset,K=j.byteLength;if(j=16*Math.ceil(Number(K)/16),O=se(O),!m){var _e=ad(g);m=se(_e)}let Le=(_e=m.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(Le).set(new Uint8Array(Y,ye,K)),_e.unmap(),(Y=m.createCommandEncoder()).copyBufferToBuffer(_e,0,O,0,j),m.queue.submit([Y.finish()]),_e.destroy()}},t.webnnInit=u=>{let f=u[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=m=>f.onRunStart(m),t.webnnOnRunEnd=f.onRunEnd.bind(f),t.webnnOnReleaseSession=m=>{f.onReleaseSession(m)},t.webnnCreateMLTensorDownloader=(m,g)=>f.createMLTensorDownloader(m,g),t.webnnRegisterMLTensor=(m,g,b,E)=>f.registerMLTensor(m,g,b,E),t.webnnCreateMLContext=m=>f.createMLContext(m),t.webnnRegisterMLConstant=(m,g,b,E,F,O)=>f.registerMLConstant(m,g,b,E,F,t.Uc,O),t.webnnRegisterGraphInput=f.registerGraphInput.bind(f),t.webnnIsGraphInput=f.isGraphInput.bind(f),t.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),t.webnnIsGraphOutput=f.isGraphOutput.bind(f),t.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),t.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f)},V?t:new Promise((u,f)=>{w=u,v=f})}var Ud,jd,Jv=me(()=>{var e,t;Ud=Vd,jd=(t=(e=globalThis.self)==null?void 0:e.name)==null?void 0:t.startsWith("em-pthread"),jd&&Vd()}),Po,Fo,qd,xt,Wd,Un,Hd,Qd,Lo,Xd,Io,Yd,Oo,Jd,No=me(()=>{Ao(),Po=typeof location>"u"?void 0:location.origin,Fo=self.location.href>"file:"&&self.location.href<"file;",qd=()=>{{if(Fo){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",self.location.href).href,Po).href}return self.location.href}},xt=qd(),Wd=()=>{if(xt&&!xt.startsWith("blob:"))return xt.substring(0,xt.lastIndexOf("/")+1)},Un=(e,t)=>{try{let r=t??xt;return(r?new URL(e,r):new URL(e)).origin===Po}catch{return!1}},Hd=(e,t)=>{let r=t??xt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Qd=(e,t)=>`${t??"./"}${e}`,Lo=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Xd=async e=>(await import(e)).default,Io=(Yv(),Gn(Rd)).default,Yd=async()=>{if(!xt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Un(xt))return[void 0,Io()];let e=await Lo(xt);return[e,Io(e)]},Oo=(Jv(),Gn($d)).default,Jd=async(e,t,r,s)=>{let n=Oo&&!(e||t);if(n)if(xt)n=Un(xt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Oo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Hd(a,t),i=r&&o&&!Un(o,t),l=i?await Lo(o):o??Qd(a,t);return[i?l:void 0,await Xd(l)]}}}),Do,jn,qs,zo,Kd,Zd,eh,Bo,Se,Ur=me(()=>{No(),jn=!1,qs=!1,zo=!1,Kd=()=>{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}},Zd=()=>{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}},eh=()=>{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}},Bo=async e=>{if(jn)return Promise.resolve();if(qs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zo)throw new Error("previous call to 'initializeWebAssembly()' failed.");qs=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!eh())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Kd();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let n=e.wasmPaths,a=typeof n=="string"?n:void 0,o=n==null?void 0:n.mjs,i=(o==null?void 0:o.href)??o,l=n==null?void 0:n.wasm,c=(l==null?void 0:l.href)??l,d=e.wasmBinary,[h,_]=await Jd(i,a,r>1,!!d||!!c),p=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{p=!0,v()},t)})),w.push(new Promise((v,y)=>{let M={numThreads:r};if(d)M.wasmBinary=d,M.locateFile=T=>T;else if(c||a)M.locateFile=T=>c??a+T;else if(i&&i.indexOf("blob:")!==0)M.locateFile=T=>new URL(T,i).href;else if(h){let T=Wd();T&&(M.locateFile=A=>T+A)}_(M).then(T=>{qs=!1,jn=!0,Do=T,v(),h&&URL.revokeObjectURL(h)},T=>{qs=!1,zo=!0,y(T)})})),await Promise.race(w),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Se=()=>{if(jn&&Do)return Do;throw new Error("WebAssembly is not initialized yet.")}}),kt,qn,ke,Ro=me(()=>{Ur(),kt=(e,t)=>{let r=Se(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},qn=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,a])=>{let o=t?t+n:n;if(typeof a=="object")qn(a,o+".",r,s);else if(typeof a=="string"||typeof a=="number")s(o,a.toString());else if(typeof a=="boolean")s(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ke=e=>{let t=Se(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetLastError(n,n+s);let a=Number(t.getValue(n,s===4?"i32":"i64")),o=t.getValue(n+s,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),th,Kv=me(()=>{Ur(),Ro(),th=e=>{let t=Se(),r=0,s=[],n=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(n.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=kt(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,a),r===0&&ke("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&qn(e.extra,"",new WeakSet,(o,i)=>{let l=kt(o,s),c=kt(i,s);t._OrtAddRunConfigEntry(r,l,c)!==0&&ke(`Can't set a run config entry: ${o} - ${i}.`)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),a}}}),rh,sh,nh,Wn,Ar,ah,oh,Zv=me(()=>{Ur(),Ro(),rh=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},sh=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},nh=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Wn=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);Se()._OrtAddSessionConfigEntry(e,n,a)!==0&&ke(`Can't set a session config entry: ${t} - ${r}.`)},Ar=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);e.push([n,a])},ah=async(e,t,r)=>{let s=t.executionProviders;for(let n of s){let a=typeof n=="string"?n:n.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let h=n==null?void 0:n.deviceType;h&&Wn(e,"deviceType",h,r)}break;case"webgpu":{a="WebGPU";let h;if(typeof n!="string"){let p=n;if(p.device)if(typeof GPUDevice<"u"&&p.device instanceof GPUDevice)h=p.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&Ar(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&Ar(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let v=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];Ar(o,"forceCpuNodeNames",v.join(`
8
- `),r)}p.validationMode&&Ar(o,"validationMode",p.validationMode,r)}let _=Se().webgpuRegisterDevice(h);if(_){let[p,w,v]=_;Ar(o,"deviceId",p.toString(),r),Ar(o,"webgpuInstance",w.toString(),r),Ar(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=kt(a,r),l=o.length,c=0,d=0;if(l>0){c=Se()._malloc(l*Se().PTR_SIZE),r.push(c),d=Se()._malloc(l*Se().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Se().setValue(c+h*Se().PTR_SIZE,o[h][0],"*"),Se().setValue(d+h*Se().PTR_SIZE,o[h][1],"*")}await Se()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&ke(`Can't append execution provider: ${a}.`)}},oh=async e=>{let t=Se(),r=0,s=[],n=e||{};nh(n);try{let a=rh(n.graphOptimizationLevel??"all"),o=sh(n.executionMode??"sequential"),i=typeof n.logId=="string"?kt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof n.optimizedModelFilePath=="string"?kt(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(a,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,i,l,c,d),r===0&&ke("Can't create session options."),n.executionProviders&&await ah(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Wn(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[h,_]of Object.entries(n.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let p=kt(h,s);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&ke(`Can't set a free dimension override: ${h} - ${_}.`)}return n.extra!==void 0&&qn(n.extra,"",new WeakSet,(h,_)=>{Wn(r,h,_,s)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&ke("Can't release session options."),s.forEach(o=>t._free(o)),a}}}),jr,Hn,rs,Ws,Qn,Go,$o,Vo,ss=me(()=>{jr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Hn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},rs=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof t=="number"?t:t.reduce((n,a)=>n*a,1);return r>0?Math.ceil(s*r):void 0},Ws=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Qn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Go=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",$o=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Uo,ih=me(()=>{Ao(),Uo=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),a;try{a=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),lh,ey=me(()=>{ss(),lh=(e,t)=>new(Ws(t))(e)}),ch,uh,dh,hh,fh,_h,lt,ph=me(()=>{ss(),ch=["V","I","W","E","F"],uh=(e,t)=>{console.log(`[${ch[e]},${new Date().toISOString()}]${t}`)},fh=(e,t)=>{dh=e,hh=t},_h=(e,t)=>{let r=Qn(e),s=Qn(dh);r>=s&&uh(r,typeof t=="function"?t():t)},lt=(...e)=>{hh&&_h(...e)}}),jo,qo,Wo,mh,Ho,gh,Qo,Xo,Yo,wh,vh,ty=me(()=>{ss(),ph(),jo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qo=(e,t)=>{if(t==="int32")return e;let r=jo.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let s=r/8;if(e.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=e.byteLength/s,a=new(Ws(t))(e.buffer,e.byteOffset,n);switch(t){case"int64":case"uint64":{let o=new Int32Array(n);for(let i=0;i<n;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Wo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},mh=1,Ho=()=>mh++,gh=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Qo=(e,t)=>{let r=jo.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((s,n)=>s*n)*r/8):0},Xo=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:s,dataType:n,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qo(this.dataType,this.tensorShape)}destroy(){lt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Wo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(e){this.isDataConverted=e}},Yo=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,s){let n=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!(a!=null&&a.input.dataTypes.includes(t))){if(o=gh.get(t),!o||(a==null?void 0:a.input.dataTypes.includes(o)))throw new Error(`WebNN backend does not support data type: ${t}`);lt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Qo(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),s&&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=qo(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else lt("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){var t,r;if(this.activeUpload){let s=(t=this.wrapper)!=null&&t.isDataConverted?Wo(this.activeUpload,(r=this.wrapper)==null?void 0:r.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(s):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s);return}else return s.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},wh=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Ho();return this.tensorTrackersById.set(e,new Yo(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,s,n){lt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,s,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){lt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,s){let n=this.getMLContext(e),a=Ho(),o=new Xo({sessionId:e,context:n,tensor:t,dataType:r,shape:s});return this.tensorTrackersById.set(a,new Yo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,s,n,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){lt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(c,1)[0];return h.sessionId=e,h}lt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:s,writable:n,readable:a});return new Xo({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},vh=(...e)=>new wh(...e)}),yh={};Vs(yh,{WebNNBackend:()=>Mh});var Hs,bh,Mh,ry=me(()=>{ss(),Ur(),ey(),ty(),ph(),Hs=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),bh=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),s=Object.keys(t).sort();return r.length===s.length&&r.every((n,a)=>n===s[a]&&e[n]===t[n])},Mh=class{constructor(e){this.tensorManager=vh(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,fh(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){lt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){lt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)lt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let t=this.mlContextCache.findIndex(r=>bh(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let s=this.mlContextCache.findIndex(n=>n.mlContext===t);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){lt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s,n){let a=Hs.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,s,n)}async createTemporaryTensor(e,t,r){lt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let s=Hs.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!Se().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");lt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return lh(r,t)}}registerMLTensor(e,t,r,s){let n=Hs.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,n,s);return lt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,s,n,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(t,t+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(c);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":d=new Int32Array(c);break;case"uint32":d=new Uint32Array(c);break;case"int64":if(o){let h=qo(new Uint8Array(c),"int64");d=new Int32Array(h.buffer),n.dataType="int32"}else d=new BigInt64Array(c);break;case"uint64":d=new BigUint64Array(c);break;case"int8":d=new Int8Array(c);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return lt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let s=Hs.get(jr(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?!1:r?!!(n!=null&&n.input.dataTypes.includes(s)):!!(n!=null&&n.output.dataTypes.includes(s))}flush(){}}}),xh,Jo,Ko,Cr,kh,Zo,Xn,ei,ti,ri,si,ni,ai,Th=me(()=>{Vr(),Kv(),Zv(),ss(),Ur(),Ro(),ih(),xh=(e,t)=>{Se()._OrtInit(e,t)!==0&&ke("Can't initialize onnxruntime.")},Jo=async e=>{xh(e.wasm.numThreads,Qn(e.logLevel))},Ko=async(e,t)=>{var s,n;(n=(s=Se()).asyncInit)==null||n.call(s);let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=e.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:o}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Se().webgpuInit(a=>{e.webgpu.device=a}),t==="webnn"){let a=new(ry(),Gn(yh)).WebNNBackend(e);Se().webnnInit([a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,i,l,c,d)=>a.ensureTensor(o,i,l,c,d),(o,i)=>{a.uploadTensor(o,i)},async(o,i)=>a.downloadTensor(o,i),(o,i)=>a.registerMLContext(o,i),!!e.trace])}},Cr=new Map,kh=e=>{let t=Se(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetInputOutputCount(e,n,n+s)!==0&&ke("Can't get session input/output count.");let a=s===4?"i32":"i64";return[Number(t.getValue(n,a)),Number(t.getValue(n+s,a))]}finally{t.stackRestore(r)}},Zo=(e,t)=>{let r=Se(),s=r.stackSave(),n=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&ke("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));n=Number(r.getValue(o+a,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],d=[];for(let h=0;h<c;h++){let _=Number(r.getValue(n+8+h*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(n+8+(h+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},Xn=e=>{let t=Se(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},ei=async(e,t)=>{var h,_,p,w;let r,s,n=Se();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=Xn(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await oh(t),(t==null?void 0:t.externalData)&&n.mountExternalData){let R=[];for(let z of t.externalData){let $=typeof z=="string"?z:z.path;R.push(Uo(typeof z=="string"?z:z.data).then(Q=>{n.mountExternalData($,Q)}))}await Promise.all(R)}for(let R of(t==null?void 0:t.executionProviders)??[])if((typeof R=="string"?R:R.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof R!="string"){let z=R,$=z==null?void 0:z.context,Q=z==null?void 0:z.gpuDevice,H=z==null?void 0:z.deviceType,D=z==null?void 0:z.powerPreference;$?n.currentContext=$:Q?n.currentContext=await n.webnnCreateMLContext(Q):n.currentContext=await n.webnnCreateMLContext({deviceType:H,powerPreference:D})}else n.currentContext=await n.webnnCreateMLContext();break}a=await n._OrtCreateSession(r,s,o),(h=n.webgpuOnCreateSession)==null||h.call(n,a),a===0&&ke("Can't create a session."),(_=n.jsepOnCreateSession)==null||_.call(n),n.currentContext&&(n.webnnRegisterMLContext(a,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[v,y]=kh(a),M=!!(t!=null&&t.enableGraphCapture),T=[],A=[],C=[],S=[],N=[];for(let R=0;R<v;R++){let[z,$,Q]=Zo(a,R);z===0&&ke("Can't get an input name."),c.push(z);let H=n.UTF8ToString(z);T.push(H),C.push($===0?{name:H,isTensor:!1}:{name:H,isTensor:!0,type:Hn($),shape:Q})}for(let R=0;R<y;R++){let[z,$,Q]=Zo(a,R+v);z===0&&ke("Can't get an output name."),d.push(z);let H=n.UTF8ToString(z);A.push(H),S.push($===0?{name:H,isTensor:!1}:{name:H,isTensor:!0,type:Hn($),shape:Q});{if(M&&(t==null?void 0:t.preferredOutputLocation)===void 0){N.push("gpu-buffer");continue}let D=typeof(t==null?void 0:t.preferredOutputLocation)=="string"?t.preferredOutputLocation:((p=t==null?void 0:t.preferredOutputLocation)==null?void 0:p[H])??"cpu",I=n.webnnIsGraphOutput;if(D==="cpu"&&I&&I(a,H)){N.push("ml-tensor-cpu-output");continue}if(D!=="cpu"&&D!=="cpu-pinned"&&D!=="gpu-buffer"&&D!=="ml-tensor")throw new Error(`Not supported preferred output location: ${D}.`);if(M&&D!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);N.push(D)}}let x=null;return N.some(R=>R==="gpu-buffer"||R==="ml-tensor"||R==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(a),i===0&&ke("Can't create IO binding."),x={handle:i,outputPreferredLocations:N,outputPreferredLocationsEncoded:N.map(R=>R==="ml-tensor-cpu-output"?"ml-tensor":R).map(R=>Vo(R))}),Cr.set(a,[a,c,d,x,M,!1]),[a,T,A,C,S]}catch(v){throw c.forEach(y=>n._OrtFree(y)),d.forEach(y=>n._OrtFree(y)),i!==0&&n._OrtReleaseBinding(i)!==0&&ke("Can't release IO binding."),a!==0&&n._OrtReleaseSession(a)!==0&&ke("Can't release session."),v}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&ke("Can't release session options."),l.forEach(v=>n._free(v)),(w=n.unmountExternalData)==null||w.call(n)}},ti=e=>{var l,c,d;let t=Se(),r=Cr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&ke("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ke("Can't release IO binding.")),(l=t.jsepOnReleaseSession)==null||l.call(t,e),(c=t.webnnOnReleaseSession)==null||c.call(t,e),(d=t.webgpuOnReleaseSession)==null||d.call(t,e),n.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(s)!==0&&ke("Can't release session."),Cr.delete(e)},ri=async(e,t,r,s,n,a,o=!1)=>{if(!e){t.push(0);return}let i=Se(),l=i.PTR_SIZE,c=e[0],d=e[1],h=e[3],_=h,p,w;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let M=e[2].gpuBuffer;w=rs(jr(c),d);{let T=i.webgpuRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=T(M,s)}}else if(h==="ml-tensor"){let M=e[2].mlTensor;w=rs(jr(c),d);let T=i.webnnRegisterMLTensor;if(!T)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=T(s,M,jr(c),d)}else{let M=e[2];if(Array.isArray(M)){w=l*M.length,p=i._malloc(w),r.push(p);for(let T=0;T<M.length;T++){if(typeof M[T]!="string")throw new TypeError(`tensor data at index ${T} is not a string`);i.setValue(p+T*l,kt(M[T],r),"*")}}else{let T=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(c!=="string"&&T&&A){let C=i.UTF8ToString(n);if(T(s,C)||A(s,C)){let S=jr(c);w=rs(S,d),_="ml-tensor";let N=i.webnnCreateTemporaryTensor,x=i.webnnUploadTensor;if(!N||!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let R=await N(s,S,d);x(R,new Uint8Array(M.buffer,M.byteOffset,M.byteLength)),p=R}else w=M.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),p)}else w=M.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),p)}}let v=i.stackSave(),y=i.stackAlloc(4*d.length);try{d.forEach((T,A)=>i.setValue(y+A*l,T,l===4?"i32":"i64"));let M=i._OrtCreateTensor(jr(c),p,w,y,d.length,Vo(_));M===0&&ke(`Can't create tensor for input/output. session=${s}, index=${a}.`),t.push(M)}finally{i.stackRestore(v)}},si=async(e,t,r,s,n,a)=>{var H,D,I,te;let o=Se(),i=o.PTR_SIZE,l=Cr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],h=l[2],_=l[3],p=l[4],w=l[5],v=t.length,y=s.length,M=0,T=[],A=[],C=[],S=[],N=[],x=o.stackSave(),R=o.stackAlloc(v*i),z=o.stackAlloc(v*i),$=o.stackAlloc(y*i),Q=o.stackAlloc(y*i);try{[M,T]=th(a),Tr("wasm prepareInputOutputTensor");for(let L=0;L<v;L++)await ri(r[L],A,S,e,d[t[L]],t[L],p);for(let L=0;L<y;L++)await ri(n[L],C,S,e,h[s[L]],v+s[L],p);Er("wasm prepareInputOutputTensor");for(let L=0;L<v;L++)o.setValue(R+L*i,A[L],"*"),o.setValue(z+L*i,d[t[L]],"*");for(let L=0;L<y;L++)o.setValue($+L*i,C[L],"*"),o.setValue(Q+L*i,h[s[L]],"*");if(_&&!w){let{handle:L,outputPreferredLocations:V,outputPreferredLocationsEncoded:X}=_;if(d.length!==v)throw new Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${d.length}).`);Tr("wasm bindInputsOutputs");for(let J=0;J<v;J++){let we=t[J];await o._OrtBindInput(L,d[we],A[J])!==0&&ke(`Can't bind input[${J}] for session=${e}.`)}for(let J=0;J<y;J++){let we=s[J];(H=n[J])!=null&&H[3]?(N.push(C[J]),o._OrtBindOutput(L,h[we],C[J],0)!==0&&ke(`Can't bind pre-allocated output[${J}] for session=${e}.`)):o._OrtBindOutput(L,h[we],0,X[we])!==0&&ke(`Can't bind output[${J}] to ${V[J]} for session=${e}.`)}Er("wasm bindInputsOutputs"),Cr.set(e,[c,d,h,_,p,!0])}(D=o.jsepOnRunStart)==null||D.call(o,c),(I=o.webnnOnRunStart)==null||I.call(o,c);let W;_?W=await o._OrtRunWithBinding(c,_.handle,y,$,M):W=await o._OrtRun(c,z,R,v,Q,y,$,M),W!==0&&ke("failed to call OrtRun().");let ee=[],G=[];Tr("wasm ProcessOutputTensor");for(let L=0;L<y;L++){let V=Number(o.getValue($+L*i,"*"));if(V===C[L]||N.includes(C[L])){ee.push(n[L]),V!==C[L]&&o._OrtReleaseTensor(V)!==0&&ke("Can't release tensor.");continue}let X=o.stackSave(),J=o.stackAlloc(4*i),we=!1,re,Fe=0;try{o._OrtGetTensorData(V,J,J+i,J+2*i,J+3*i)!==0&&ke(`Can't access output tensor data on index ${L}.`);let qe=i===4?"i32":"i64",bt=Number(o.getValue(J,qe));Fe=o.getValue(J+i,"*");let It=o.getValue(J+i*2,"*"),Ot=Number(o.getValue(J+i*3,qe)),Qe=[];for(let ce=0;ce<Ot;ce++)Qe.push(Number(o.getValue(It+ce*i,qe)));o._OrtFree(It)!==0&&ke("Can't free memory for tensor dims.");let pt=Qe.reduce((ce,Pe)=>ce*Pe,1);re=Hn(bt);let Me=_==null?void 0:_.outputPreferredLocations[s[L]];if(re==="string"){if(Me==="gpu-buffer"||Me==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let Pe=0;Pe<pt;Pe++){let mt=o.getValue(Fe+Pe*i,"*"),nr=o.getValue(Fe+(Pe+1)*i,"*"),Nt=Pe===pt-1?void 0:nr-mt;ce.push(o.UTF8ToString(mt,Nt))}ee.push([re,Qe,ce,"cpu"])}else if(Me==="gpu-buffer"&&pt>0){let ce=o.webgpuGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Pe=ce(Fe),mt=rs(bt,pt);if(mt===void 0||!Go(re))throw new Error(`Unsupported data type: ${re}`);we=!0;{o.webgpuRegisterBuffer(Pe,e,Fe);let nr=o.webgpuCreateDownloader(Pe,mt,e);ee.push([re,Qe,{gpuBuffer:Pe,download:async()=>{let Nt=await nr();return new(Ws(re))(Nt)},dispose:()=>{o._OrtReleaseTensor(V)!==0&&ke("Can't release tensor.")}},"gpu-buffer"])}}else if(Me==="ml-tensor"&&pt>0){let ce=o.webnnEnsureTensor,Pe=o.webnnIsGraphInputOutputTypeSupported;if(!ce||!Pe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rs(bt,pt)===void 0||!$o(re))throw new Error(`Unsupported data type: ${re}`);if(!Pe(e,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let mt=await ce(e,Fe,bt,Qe,!1);we=!0,ee.push([re,Qe,{mlTensor:mt,download:o.webnnCreateMLTensorDownloader(Fe,re),dispose:()=>{o.webnnReleaseTensorId(Fe),o._OrtReleaseTensor(V)}},"ml-tensor"])}else if(Me==="ml-tensor-cpu-output"&&pt>0){let ce=o.webnnCreateMLTensorDownloader(Fe,re)(),Pe=ee.length;we=!0,G.push((async()=>{let mt=[Pe,await ce];return o.webnnReleaseTensorId(Fe),o._OrtReleaseTensor(V),mt})()),ee.push([re,Qe,[],"cpu"])}else{let ce=Ws(re),Pe=new ce(pt);new Uint8Array(Pe.buffer,Pe.byteOffset,Pe.byteLength).set(o.HEAPU8.subarray(Fe,Fe+Pe.byteLength)),ee.push([re,Qe,Pe,"cpu"])}}finally{o.stackRestore(X),re==="string"&&Fe&&o._free(Fe),we||o._OrtReleaseTensor(V)}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&ke("Can't clear bound outputs."),Cr.set(e,[c,d,h,_,p,!1]));for(let[L,V]of await Promise.all(G))ee[L][2]=V;return Er("wasm ProcessOutputTensor"),ee}finally{(te=o.webnnOnRunEnd)==null||te.call(o,c),o.stackRestore(x),r.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),n.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),A.forEach(W=>o._OrtReleaseTensor(W)),C.forEach(W=>o._OrtReleaseTensor(W)),S.forEach(W=>o._free(W)),M!==0&&o._OrtReleaseRunOptions(M),T.forEach(W=>o._free(W))}},ni=e=>{let t=Se(),r=Cr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&ke("Can't get an profile file name."),t._OrtFree(n)},ai=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),Sr,wt,ns,Qs,Xs,Yn,oi,Jn,qr,Wr,Eh,Ah,Ch,Sh,Ph,Fh,Lh,Ih,Oh=me(()=>{Vr(),Th(),Ur(),No(),Sr=()=>!!Be.wasm.proxy&&typeof document<"u",ns=!1,Qs=!1,Xs=!1,Jn=new Map,qr=(e,t)=>{let r=Jn.get(e);r?r.push(t):Jn.set(e,[t])},Wr=()=>{if(ns||!Qs||Xs||!wt)throw new Error("worker not ready")},Eh=e=>{switch(e.data.type){case"init-wasm":ns=!1,e.data.err?(Xs=!0,oi[1](e.data.err)):(Qs=!0,oi[0]()),Yn&&(URL.revokeObjectURL(Yn),Yn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Jn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Ah=async()=>{if(!Qs){if(ns)throw new Error("multiple calls to 'initWasm()' detected.");if(Xs)throw new Error("previous call to 'initWasm()' failed.");if(ns=!0,Sr())return new Promise((e,t)=>{wt==null||wt.terminate(),Yd().then(([r,s])=>{try{wt=s,wt.onerror=a=>t(a),wt.onmessage=Eh,oi=[e,t];let n={type:"init-wasm",in:Be};!n.in.wasm.wasmPaths&&(r||Fo)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.asyncify-CtKKja6V.wasm",self.location.href).href,self.location.href).href}),wt.postMessage(n),Yn=r}catch(n){t(n)}},t)});try{await Bo(Be.wasm),await Jo(Be),Qs=!0}catch(e){throw Xs=!0,e}finally{ns=!1}}},Ch=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:Be}};wt.postMessage(s)});await Ko(Be,e)},Sh=async e=>Sr()?(Wr(),new Promise((t,r)=>{qr("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};wt.postMessage(s,[e.buffer])})):Xn(e),Ph=async(e,t)=>{if(Sr()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wr(),new Promise((r,s)=>{qr("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),wt.postMessage(n,a)})}else return ei(e,t)},Fh=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("release",[t,r]);let s={type:"release",in:e};wt.postMessage(s)});ti(e)},Lh=async(e,t,r,s,n,a)=>{if(Sr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wr(),new Promise((o,i)=>{qr("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:s,options:a}};wt.postMessage(c,ai(l))})}else return si(e,t,r,s,n,a)},Ih=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("end-profiling",[t,r]);let s={type:"end-profiling",in:e};wt.postMessage(s)});ni(e)}}),ii,Nh,Dh,sy=me(()=>{Vr(),Oh(),ss(),Ao(),ih(),ii=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Nh=e=>{switch(e[3]){case"cpu":return new zt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Go(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return zt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let t=e[0];if(!$o(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=e[2];return zt.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},Dh=class{async fetchModelAndCopyToWasmMemory(e){return Sh(await Uo(e))}async loadModel(e,t){Gr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Ph(r,t),$r()}async dispose(){return Fh(this.sessionId)}async run(e,t,r){Gr();let s=[],n=[];Object.entries(e).forEach(h=>{let _=h[0],p=h[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(p),n.push(w)});let a=[],o=[];Object.entries(t).forEach(h=>{let _=h[0],p=h[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(p),o.push(w)});let i=s.map((h,_)=>ii(h,()=>`input "${this.inputNames[n[_]]}"`)),l=a.map((h,_)=>h?ii(h,()=>`output "${this.outputNames[o[_]]}"`):null),c=await Lh(this.sessionId,n,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??Nh(c[h]);return $r(),d}startProfiling(){}endProfiling(){Ih(this.sessionId)}}}),zh={};Vs(zh,{OnnxruntimeWebAssemblyBackend:()=>ci,initializeFlags:()=>li,wasmBackend:()=>Bh});var li,ci,Bh,ny=me(()=>{Vr(),Oh(),sy(),li=()=>{(typeof Be.wasm.initTimeout!="number"||Be.wasm.initTimeout<0)&&(Be.wasm.initTimeout=0);let e=Be.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Be.wasm.simd=!1),typeof Be.wasm.proxy!="boolean"&&(Be.wasm.proxy=!1),typeof Be.wasm.trace!="boolean"&&(Be.wasm.trace=!1),typeof Be.wasm.numThreads!="number"||!Number.isInteger(Be.wasm.numThreads)||Be.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Be.wasm.numThreads=1;else{let t=typeof navigator>"u"?Nv("node:os").cpus().length:navigator.hardwareConcurrency;Be.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ci=class{async init(e){li(),await Ah(),await Ch(e)}async createInferenceSessionHandler(e,t){let r=new Dh;return await r.loadModel(e,t),r}},Bh=new ci});Vr(),Vr(),Vr();var ay="1.26.0-dev.20260410-5e55544225",oy=Bd;{let e=(ny(),Gn(zh)).wasmBackend;Br("webgpu",e,5),Br("webnn",e,5),Br("cpu",e,10),Br("wasm",e,10)}Object.defineProperty(Be.versions,"web",{value:ay,enumerable:!0});var iy=Object.freeze({__proto__:null,get InferenceSession(){return Eo},get TRACE(){return Vn},get TRACE_EVENT_BEGIN(){return Tr},get TRACE_EVENT_END(){return Er},get TRACE_FUNC_BEGIN(){return Gr},get TRACE_FUNC_END(){return $r},get Tensor(){return zt},default:oy,get env(){return Be},get registerBackend(){return Br}});const ly=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];const s=r.getContext("2d");if(s!=null){let n,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);const o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm;let l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));const d=a*n;let h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<n;y++){const M=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],C=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+M+","+T+","+A+","+C+")",s.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},cy=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(r!=null){let n,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm;let c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let p=0,w=1,v=2,y=3,M=0,T=h,A=h*2,C=-1;i==="RGBA"?(M=0,T=h,A=h*2,C=h*3):i==="RGB"?(M=0,T=h,A=h*2):i==="RBG"&&(M=0,A=h,T=h*2),s=r.createImageData(n,a);for(let S=0;S<a*n;p+=_,w+=_,v+=_,y+=_,S++)s.data[p]=(e.data[M++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[y]=C===-1?255:(e.data[C++]-d[3])*c[3]}else throw new Error("Can not access image data");return s},ui=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:s}=t,n=t.norm??{mean:255,bias:0};let a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let h=4,_=0,p=1,w=2,v=3,y=0,M=c,T=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,y=c*2);for(let S=0;S<c;S++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[M++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new St("float32",d,[1,4,r,s]):new St("float32",d,[1,3,r,s])},uy=async(e,t)=>{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let o,i=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){const d=l();d.width=e.width,d.height=e.height;const h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){const _=l();_.width=h,_.height=d;const p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const d=l();d.width=e.width,d.height=e.height;const h=c(d);if(h!=null){const _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,ui(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{const _=l(),p=c(_);if(!e||!p)return h();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);const v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(ui(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ui(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},dy=(e,t)=>{const{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new St({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},hy=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new St({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},fy=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new St({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},_y=(e,t,r)=>new St({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),as=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Kn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Rh=!1;const py=()=>{if(!Rh){Rh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(as.set("int64",BigInt64Array),Kn.set(BigInt64Array,"int64")),t&&(as.set("uint64",BigUint64Array),Kn.set(BigUint64Array,"uint64")),s?(as.set("float16",r),Kn.set(r,"float16")):as.set("float16",Uint16Array)}},my=e=>{let t=1;for(let r=0;r<e.length;r++){const s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},gy=(e,t)=>{switch(e.location){case"cpu":return new St(e.type,e.data,t);case"cpu-pinned":return new St({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new St({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new St({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new St({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let St=class{constructor(t,r,s){py();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=as.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof t=="string")if(n=t,l=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const c=as.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof t[0];if(c==="string")n="string",i=t;else if(c==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(t);else{const c=Kn.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=c,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}const o=my(a);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=o}static async fromImage(t,r){return uy(t,r)}static fromTexture(t,r){return dy(t,r)}static fromGpuBuffer(t,r){return hy(t,r)}static fromMLTensor(t,r){return fy(t,r)}static fromPinnedBuffer(t,r,s){return _y(t,r,s)}toDataURL(t){return ly(this,t)}toImageData(t){return cy(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return gy(this,t)}};const wy=St;var cr={},vy=Object.defineProperty,os=(e,t)=>{for(var r in t)vy(e,r,{get:t[r],enumerable:!0})},Tt={},Yt={},yy={},by="4.1.0",di=typeof self<"u",is=!qh(Tt),Gh=!qh(Yt),Zn=di&&"caches"in self,My=typeof globalThis.Deno<"u",ea=My&&Zn&&!is,$h=typeof process<"u",Vh=$h&&((wg=process==null?void 0:process.release)==null?void 0:wg.name)==="node"&&!ea,hi=typeof window<"u"&&typeof window.document<"u",fi=di&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((vg=self.constructor)==null?void 0:vg.name),xy=hi||fi||ea,ky=Vh||typeof navigator<"u"&&"gpu"in navigator,Ty=typeof navigator<"u"&&"ml"in navigator,Ey=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",Ay=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",Cy=typeof ServiceWorkerGlobalScope<"u"&&di&&self instanceof ServiceWorkerGlobalScope,Sy=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&s},Py=Sy(),fe=Object.freeze({IS_BROWSER_ENV:hi,IS_WEBWORKER_ENV:fi,IS_WEB_ENV:xy,IS_SERVICE_WORKER_ENV:Cy,IS_DENO_WEB_RUNTIME:ea,IS_WEB_CACHE_AVAILABLE:Zn,IS_WEBGPU_AVAILABLE:ky,IS_WEBNN_AVAILABLE:Ty,IS_SAFARI:Py,IS_PROCESS_AVAILABLE:$h,IS_NODE_ENV:Vh,IS_FS_AVAILABLE:is,IS_PATH_AVAILABLE:Gh,IS_CRYPTO_AVAILABLE:Ey,IS_CHROME_AVAILABLE:Ay}),_i=is&&Gh,ta="./";if(_i){const e=Object({url:self.location.href}).url;e?ta=Yt.dirname(Yt.dirname(yy.fileURLToPath(e))):typeof __dirname<"u"&&(ta=Yt.dirname(__dirname))}var Fy=_i?Yt.join(ta,"/.cache/"):null,Uh="/models/",Ly=_i?Yt.join(ta,Uh):Uh,Iy=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Bt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),jh=Bt.WARNING,be={version:by,backends:{onnx:{}},get logLevel(){return jh},set logLevel(e){var t,r;jh=e,(r=(t=be.backends.onnx)==null?void 0:t.setLogLevel)==null||r.call(t,e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(hi||fi||ea),localModelPath:Ly,useFS:is,useBrowserCache:Zn,useFSCache:is,cacheDir:Fy,useCustomCache:!1,customCache:null,useWasmCache:Zn||is,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:Iy};function qh(e){return Object.keys(e).length===0}var vt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Pr(e,t){e&&e(t)}var pi=class extends vt{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};const t=Object.values(this.files_loading).reduce((n,a)=>n+a.loaded,0),r=Object.values(this.files_loading).reduce((n,a)=>n+a.total,0),s=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:s,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function Oy(e){return Number.isInteger(e)||typeof e=="bigint"}function Wh(e){return e==null||e===-1}function Hh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Jt(...e){return Array.prototype.concat.apply([],e)}function Ny(...e){return e.reduce((t,r)=>t.flatMap(s=>r.map(n=>[s,n])))}function ra(e,t){return Math.abs((e+t)%(2*t)-t)}function rt(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function Dy(e,t){let r=0;for(const s of e)s===t&&++r;return r}var ue={error(...e){be.logLevel<=Bt.ERROR&&console.error(...e)},warn(...e){be.logLevel<=Bt.WARNING&&console.warn(...e)},info(...e){be.logLevel<=Bt.INFO&&console.log(...e)},debug(...e){be.logLevel<=Bt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},zy=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let s=t;for(let n=0;n<r.length;++n){const a=r[n];s=s[a]??(s[a]=Object.create(null))}s.end=r}return t}split(e){const t=[],r=e.length;let s=0,n=0;for(;n<r;){let a=this.trie,o=null,i=n;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(n>s&&t.push(e.slice(s,n)),t.push(o),n+=o.length,s=n):++n}return s<r&&t.push(e.slice(s)),t}},Qh=zy,By=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},Ry=By,Xh=(()=>{const e=[...Array.from({length:94},(n,a)=>a+33),...Array.from({length:12},(n,a)=>a+161),...Array.from({length:82},(n,a)=>a+174)],t=e.slice();let r=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);const s=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,a)=>[n,s[a]]))})(),Gy=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),$y=Gy(Xh),Yh=".,!?…。,、।۔،",Vy=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|[${Yh}])]+`,` ?[^\\s${Yh}]+`]]),sa="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",mi=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"),na=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[s,n]of Vy)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(a,"gu")}catch{throw s}}}else if(e.String!==void 0){const r=Uy(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},Uy=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),jy=(e,t,r)=>{const s=[];let n=0;for(;n<e.length;){if(s.push(e[n]),(t.get(e[n])??r)!==r){++n;continue}for(;++n<e.length&&(t.get(e[n])??r)===r;)t.get(s.at(-1))!==r&&(s[s.length-1]+=e[n])}return s},qy=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Wy=e=>Number.isInteger(e)||typeof e=="bigint",Hy=e=>{let t=0;for(const r of e)++t;return t},Qy=e=>Jh(e.toLowerCase()),Rt=(...e)=>Array.prototype.concat.apply([],e),gi=e=>new Map(Object.entries(e)),Xy=(e,t)=>{const r=[];let s=0;for(const n of e.matchAll(t)){const a=n[0];s<n.index&&r.push(e.slice(s,n.index)),a.length>0&&r.push(a),s=n.index+a.length}return s<e.length&&r.push(e.slice(s)),r},Jh=e=>e.replace(new RegExp("\\p{M}","gu"),""),Kh=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const s of r)if(!(s in e))return`${t} must contain a "${s}" property`;return null},Yy=e=>e.match(/\S+/g)||[],Jy=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Ys=Jy,Ky=class extends Ys{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},ur=Ky,Zy=class extends ur{tokenize_chinese_chars(e){const t=[];for(let r=0;r<e.length;++r){const s=e[r],n=s.charCodeAt(0);qy(n)?(t.push(" "),t.push(s),t.push(" ")):t.push(s)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
9
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){const t=[];for(const r of e){const s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},eb=Zy,tb=class extends ur{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("~")?e=e.split("~").map(r=>r.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},rb=tb,sb=class extends ur{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Zh(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},nb=sb,ab=class extends ur{normalize(e){const t=na(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},ob=ab,ib=class extends ur{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},aa=ib,lb=class extends aa{constructor(){super(...arguments),this.form="NFC"}},cb=lb,ub=class extends aa{constructor(){super(...arguments),this.form="NFD"}},db=ub,hb=class extends aa{constructor(){super(...arguments),this.form="NFKC"}},fb=hb,_b=class extends aa{constructor(){super(...arguments),this.form="NFKD"}},pb=_b,mb=class extends ur{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}},gb=mb,wb=class extends ur{normalize(e){return Jh(e)}},vb=wb,yb=class extends ur{normalize(e){return e.toLowerCase()}},bb=yb,Mb=class extends ur{normalize(e){return e=this.config.prepend+e,e}},xb=Mb;function kb(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new eb(e);case"Precompiled":return new rb(e);case"Sequence":return new nb(e);case"Replace":return new ob(e);case"NFC":return new cb(e);case"NFD":return new db(e);case"NFKC":return new fb(e);case"NFKD":return new pb(e);case"Strip":return new gb(e);case"StripAccents":return new vb(e);case"Lowercase":return new bb(e);case"Prepend":return new xb(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Zh=kb,Tb=class extends Ys{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Gt=Tb,Eb=class extends Gt{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Xh,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(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},Ab=Eb,Cb=class extends Gt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Sb=Cb,Pb=class extends Gt{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:r=void 0}=t??{};let s=e.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},Fb=Pb,Lb=class extends Gt{constructor(e){super(),this.config=e,this.pattern=na(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){var t;return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:((t=this.config.behavior)==null?void 0:t.toLowerCase())==="removed"?e.split(this.pattern).filter(r=>r):Xy(e,this.pattern)}},Ib=Lb,Ob=class extends Gt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${sa}]+|[${sa}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Nb=Ob,Db=class extends Gt{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},zb=Db,Bb=class extends Gt{constructor(){super(),this.pattern=new RegExp(`[^\\s${sa}]+|[${sa}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},Rb=Bb,Gb=class extends Gt{constructor(e){super(),this.config=e,this.pattern=na(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},$b=Gb,Vb=class extends Gt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>ef(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,t):r,[e])}},Ub=Vb,jb=class extends Gt{pre_tokenize_text(e){return Yy(e)}},qb=jb,Wb=class extends Gt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},Hb=Wb;function Qb(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new Rb;case"Sequence":return new Ub(e);case"Whitespace":return new Sb;case"WhitespaceSplit":return new qb;case"Metaspace":return new Fb(e);case"ByteLevel":return new Ab(e);case"Split":return new Ib(e);case"Punctuation":return new Nb(e);case"Digits":return new zb(e);case"Replace":return new $b(e);case"FixedLength":return new Hb(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var ef=Qb,Xb=class extends Ys{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=jy(t,this.tokens_to_ids,this.unk_token_id)),t}},oa=Xb,Yb=class extends oa{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=gi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){const t=[];for(const r of e){const s=[...r];if(s.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,a=0;const o=[];for(;a<s.length;){let i=s.length,l=null;for(;a<i;){let c=s.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}o.push(l),a=i}n?t.push(this.unk_token):t.push(...o)}return t}},tf=Yb,rf=class Fv{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new Fv(!1,new Map)}},Jb=class{constructor(){this.root=rf.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let s=t.children.get(r);s===void 0&&(s=rf.default(),t.children.set(r,s)),t=s}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const s of e){if(r+=s,t=t.children.get(s),t===void 0)return;t.is_leaf&&(yield r)}}},Kb=Jb,wi=class Lv{constructor(t,r,s,n,a){this.token_id=t,this.node_id=r,this.pos=s,this.length=n,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new Lv(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},Zb=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);const s=new wi(this.bos_token_id??0,0,0,0,0),n=new wi(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(e,t,r,s){const n=this.nodes.length,a=new wi(s,n,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let c of this.end_nodes[t]){const d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.clone(),i=d)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}const r=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let a=n.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},e0=Zb;function t0(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}var r0=class extends oa{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=e.vocab[s];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=t0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Kb,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let s=0;for(;s<t.length;){let n=!1;const a=t.slice(s).join(""),o=this.trie.common_prefix_search(a);for(const i of o){const l=this.tokens_to_ids.get(i),c=this.scores[l],d=Hy(i);e.insert(s,d,c,l),!n&&d===r&&(n=!0)}n||e.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(e){const t=new e0(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const r of e){const s=this.tokenize(r);t.push(...s)}return t}},sf=r0,s0=class{constructor(e=(r,s)=>r>s,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{const r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},n0=s0,a0=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},o0=a0,i0=class extends oa{constructor(e){super(e),this.tokens_to_ids=gi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,s]of this.tokens_to_ids)this.vocab[s]=r;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),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 o0(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){const n=new n0((i,l)=>i.score<l.score);let a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){const l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(n,o),o=l}for(;!n.is_empty();){const i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){const c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}const l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=a;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,s),s}add_node(e,t){const r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){const t=[];for(const r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}const s=this.bpe(r);for(const n of s)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(n)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},nf=i0,l0=class extends oa{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=gi(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(e){return e}},c0=l0;function u0(e,t){switch(e.type){case"WordPiece":return new tf(e);case"Unigram":return new sf(e,t.eos_token);case"BPE":return new nf(e);default:if(e.vocab)return Array.isArray(e.vocab)?new sf(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new nf(e):new tf(e):new c0(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e==null?void 0:e.type}`)}}var d0=u0,h0=class extends Ys{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Js=h0,f0=class extends Js{post_process(e,t=null,r=!0){const s=t===null?this.config.single:this.config.pair;let n=[],a=[];for(const o of s)"SpecialToken"in o?r&&(n.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(n=Rt(n,e),a=Rt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(n=Rt(n,t),a=Rt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:n,token_type_ids:a}}},_0=f0,p0=class extends Js{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},m0=p0,g0=class extends Js{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Rt([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=[],a=r?[this.sep[0]]:[];e=Rt(e,n,t,a),s=Rt(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},w0=g0,v0=class extends Js{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Rt([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Rt(e,n,t,a),s=Rt(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},y0=v0,b0=class extends Js{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>af(t))}post_process(e,t=null,r=!0){let s={tokens:e,tokens_pair:t};for(const n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},M0=b0;function x0(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new _0(e);case"ByteLevel":return new m0(e);case"BertProcessing":return new w0(e);case"RobertaProcessing":return new y0(e);case"Sequence":return new M0(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var af=x0,k0=class extends Ys{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("")}},$t=k0,T0=class extends $t{constructor(e){super(e),this.byte_decoder=$y,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const s of e)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},E0=T0,A0=class extends $t{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const s=this.config.prefix;s&&t.startsWith(s)?t=t.replace(s,""):t=" "+t}return this.cleanup&&(t=mi(t)),t})}},C0=A0,S0=class extends $t{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;r<e.length;++r){let s=e[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),t.push(s)}return t}},P0=S0,F0=class extends $t{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},L0=F0,I0=class extends $t{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let s=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=mi(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},O0=I0,N0=class extends $t{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>of(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},D0=N0,z0=class extends $t{decode_chain(e){const t=na(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(s=>s.replaceAll(t,r))}},B0=z0,R0=class extends $t{decode_chain(e){return[e.join("")]}},G0=R0,$0=class extends $t{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let n=0;n<this.start&&t[n]===this.content;++n){r=n+1;continue}let s=t.length;for(let n=0;n<this.stop;++n){const a=t.length-n-1;if(t[a]===this.content){s=a;continue}else break}return t.slice(r,s)})}},V0=$0,U0=class extends $t{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const s of e){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){const a=parseInt(s.slice(3,5),16);isNaN(a)||(n=a)}if(n!==null)r.push(n);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}return t}},j0=U0;function q0(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new E0(e);case"WordPiece":return new C0(e);case"Metaspace":return new P0(e);case"BPEDecoder":return new L0(e);case"CTC":return new O0(e);case"Sequence":return new D0(e);case"Replace":return new B0(e);case"Fuse":return new G0(e);case"Strip":return new V0(e);case"ByteFallback":return new j0(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var of=q0,W0=class{constructor(e,t){const r=Kh(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const s=Kh(t,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=t,this.normalizer=Zh(this.tokenizer.normalizer),this.pre_tokenizer=ef(this.tokenizer.pre_tokenizer),this.model=d0(this.tokenizer.model,this.config),this.post_processor=af(this.tokenizer.post_processor),this.decoder=of(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const n=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new Ry(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Qh(n),this.splitter_normalized=new Qh(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{tokens:n,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=n.map(l=>{var c;return((c=this.added_tokens_map.get(l))==null?void 0:c.id)??this.model.tokens_to_ids.get(l)??this.model.unk_token_id}),i={ids:o,tokens:n,attention_mask:new Array(o.length).fill(1)};return s&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Wy(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(s=s.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=mi(s)),s}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,s)=>{const n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(t[s-1]=t[s-1].trimEnd()),n.rstrip&&s<t.length-1&&(t[s+1]=t[s+1].trimStart()))}),t.flatMap((r,s)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=Qy(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const n=this.splitter_normalized.split(r);return n.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(n[o-1]=n[o-1].trimEnd()),i.rstrip&&o<n.length-1&&(n[o+1]=n[o+1].trimStart()))}),n.flatMap(a=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:s}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const s=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Rt(s??[],n??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let r=0;r<this.model.vocab.length;++r){const s=this.model.vocab[r];(e||!this.added_tokens_map.has(s))&&t.set(s,r)}return t}},H0=W0,B=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Pt=class{constructor(e,t){this.value=e,this.type=t}};function lf(e){return/\w/.test(e)}function Ks(e){return/[0-9]/.test(e)}function cf(e){return/\s/.test(e)}var Q0=[["{%",B.OpenStatement],["%}",B.CloseStatement],["{{",B.OpenExpression],["}}",B.CloseExpression],["(",B.OpenParen],[")",B.CloseParen],["{",B.OpenCurlyBracket],["}",B.CloseCurlyBracket],["[",B.OpenSquareBracket],["]",B.CloseSquareBracket],[",",B.Comma],[".",B.Dot],[":",B.Colon],["|",B.Pipe],["<=",B.ComparisonBinaryOperator],[">=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],X0=new Map([["n",`
10
- `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Y0(e,t={}){return e.endsWith(`
11
- `)&&(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 J0(e,t={}){var c,d;const r=[],s=Y0(e,t);let n=0,a=0;const o=h=>{let _="";for(;h(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");const p=s[n++],w=X0.get(p);if(w===void 0)throw new SyntaxError(`Unexpected escaped character: ${p}`);_+=w;continue}if(_+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return _},i=()=>{const h=r.at(-1);h&&h.type===B.Text&&(h.value=h.value.trimEnd(),h.value===""&&r.pop())},l=()=>{for(;n<s.length&&cf(s[n]);)++n};e:for(;n<s.length;){const h=(c=r.at(-1))==null?void 0:c.type;if(h===void 0||h===B.CloseStatement||h===B.CloseExpression||h===B.Comment){let p="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)p+=s[n++];if(p.length>0){r.push(new Pt(p,B.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;const p=s[n]==="-";p&&++n;let w="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");w+=s[n++]}const v=w.endsWith("-");v&&(w=w.slice(0,-1)),p&&i(),r.push(new Pt(w,B.Comment)),n+=2,v&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Pt("{%",B.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Pt("{{",B.OpenExpression)),a=0,n+=3;continue}if(o(cf),s.slice(n,n+3)==="-%}"){r.push(new Pt("%}",B.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Pt("}}",B.CloseExpression)),n+=3,l();continue}const _=s[n];if(_==="-"||_==="+"){const p=(d=r.at(-1))==null?void 0:d.type;if(p===B.Text||p===void 0)throw new SyntaxError(`Unexpected character: ${_}`);switch(p){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++n;const w=o(Ks);r.push(new Pt(`${_}${w}`,w.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(const[p,w]of Q0){if(p==="}}"&&a>0)continue;if(s.slice(n,n+p.length)===p){r.push(new Pt(p,w)),w===B.OpenExpression?a=0:w===B.OpenCurlyBracket?++a:w===B.CloseCurlyBracket&&--a,n+=p.length;continue e}}if(_==="'"||_==='"'){++n;const p=o(w=>w!==_);r.push(new Pt(p,B.StringLiteral)),++n;continue}if(Ks(_)){let p=o(Ks);if(s[n]==="."&&Ks(s[n+1])){++n;const w=o(Ks);p=`${p}.${w}`}r.push(new Pt(p,B.NumericLiteral));continue}if(lf(_)){const p=o(lf);r.push(new Pt(p,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${_}`)}return r}var Vt=class{constructor(){k(this,"type","Statement")}},K0=class extends Vt{constructor(t){super();k(this,"type","Program");this.body=t}},Z0=class extends Vt{constructor(t,r,s){super();k(this,"type","If");this.test=t,this.body=r,this.alternate=s}},eM=class extends Vt{constructor(t,r,s,n){super();k(this,"type","For");this.loopvar=t,this.iterable=r,this.body=s,this.defaultBlock=n}},tM=class extends Vt{constructor(){super(...arguments);k(this,"type","Break")}},rM=class extends Vt{constructor(){super(...arguments);k(this,"type","Continue")}},sM=class extends Vt{constructor(t,r,s){super();k(this,"type","Set");this.assignee=t,this.value=r,this.body=s}},nM=class extends Vt{constructor(t,r,s){super();k(this,"type","Macro");this.name=t,this.args=r,this.body=s}},aM=class extends Vt{constructor(t){super();k(this,"type","Comment");this.value=t}},Et=class extends Vt{constructor(){super(...arguments);k(this,"type","Expression")}},oM=class extends Et{constructor(t,r,s){super();k(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=s}},uf=class extends Et{constructor(t,r){super();k(this,"type","CallExpression");this.callee=t,this.args=r}},ls=class extends Et{constructor(t){super();k(this,"type","Identifier");this.value=t}},cs=class extends Et{constructor(t){super();k(this,"type","Literal");this.value=t}},iM=class extends cs{constructor(){super(...arguments);k(this,"type","IntegerLiteral")}},lM=class extends cs{constructor(){super(...arguments);k(this,"type","FloatLiteral")}},df=class extends cs{constructor(){super(...arguments);k(this,"type","StringLiteral")}},cM=class extends cs{constructor(){super(...arguments);k(this,"type","ArrayLiteral")}},hf=class extends cs{constructor(){super(...arguments);k(this,"type","TupleLiteral")}},uM=class extends cs{constructor(){super(...arguments);k(this,"type","ObjectLiteral")}},Zs=class extends Et{constructor(t,r,s){super();k(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=s}},dM=class extends Et{constructor(t,r){super();k(this,"type","FilterExpression");this.operand=t,this.filter=r}},hM=class extends Vt{constructor(t,r){super();k(this,"type","FilterStatement");this.filter=t,this.body=r}},fM=class extends Et{constructor(t,r){super();k(this,"type","SelectExpression");this.lhs=t,this.test=r}},_M=class extends Et{constructor(t,r,s){super();k(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=s}},pM=class extends Et{constructor(t,r){super();k(this,"type","UnaryExpression");this.operator=t,this.argument=r}},mM=class extends Et{constructor(t=void 0,r=void 0,s=void 0){super();k(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=s}},gM=class extends Et{constructor(t,r){super();k(this,"type","KeywordArgumentExpression");this.key=t,this.value=r}},wM=class extends Et{constructor(t){super();k(this,"type","SpreadExpression");this.argument=t}},vM=class extends Vt{constructor(t,r,s){super();k(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=s}},yM=class extends Et{constructor(t,r,s){super();k(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=s}};function bM(e){const t=new K0([]);let r=0;function s(G,L){const V=e[r++];if(!V||V.type!==G)throw new Error(`Parser Error: ${L}. ${V.type} !== ${G}.`);return V}function n(G){if(!l(G))throw new SyntaxError(`Expected ${G}`);++r}function a(){switch(e[r].type){case B.Comment:return new aM(e[r++].value);case B.Text:return c();case B.OpenStatement:return d();case B.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...G){return r+G.length<=e.length&&G.every((L,V)=>L===e[r+V].type)}function i(...G){var L,V,X;return((L=e[r])==null?void 0:L.type)===B.OpenStatement&&((V=e[r+1])==null?void 0:V.type)===B.Identifier&&G.includes((X=e[r+1])==null?void 0:X.value)}function l(...G){return r+G.length<=e.length&&G.every((L,V)=>e[r+V].type==="Identifier"&&L===e[r+V].value)}function c(){return new df(s(B.Text,"Expected text token").value)}function d(){if(s(B.OpenStatement,"Expected opening statement token"),e[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const G=e[r].value;let L;switch(G){case"set":++r,L=_();break;case"if":++r,L=p(),s(B.OpenStatement,"Expected {% token"),n("endif"),s(B.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),s(B.OpenStatement,"Expected {% token"),n("endmacro"),s(B.CloseStatement,"Expected %} token");break;case"for":++r,L=y(),s(B.OpenStatement,"Expected {% token"),n("endfor"),s(B.CloseStatement,"Expected %} token");break;case"call":{++r;let V=null;o(B.OpenParen)&&(V=$());const X=ee();if(X.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const J=$();s(B.CloseStatement,"Expected closing statement token");const we=[];for(;!i("endcall");)we.push(a());s(B.OpenStatement,"Expected '{%'"),n("endcall"),s(B.CloseStatement,"Expected closing statement token");const re=new uf(X,J);L=new vM(re,V,we);break}case"break":++r,s(B.CloseStatement,"Expected closing statement token"),L=new tM;break;case"continue":++r,s(B.CloseStatement,"Expected closing statement token"),L=new rM;break;case"filter":{++r;let V=ee();V instanceof ls&&o(B.OpenParen)&&(V=z(V)),s(B.CloseStatement,"Expected closing statement token");const X=[];for(;!i("endfilter");)X.push(a());s(B.OpenStatement,"Expected '{%'"),n("endfilter"),s(B.CloseStatement,"Expected '%}'"),L=new hM(V,X);break}default:throw new SyntaxError(`Unknown statement type: ${G}`)}return L}function h(){s(B.OpenExpression,"Expected opening expression token");const G=M();return s(B.CloseExpression,"Expected closing expression token"),G}function _(){const G=v();let L=null;const V=[];if(o(B.Equals))++r,L=v();else{for(s(B.CloseStatement,"Expected %} token");!i("endset");)V.push(a());s(B.OpenStatement,"Expected {% token"),n("endset")}return s(B.CloseStatement,"Expected closing statement token"),new sM(G,L,V)}function p(){const G=M();s(B.CloseStatement,"Expected closing statement token");const L=[],V=[];for(;!i("elif","else","endif");)L.push(a());if(i("elif")){++r,++r;const X=p();V.push(X)}else if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endif");)V.push(a());return new Z0(G,L,V)}function w(){const G=ee();if(G.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const L=$();s(B.CloseStatement,"Expected closing statement token");const V=[];for(;!i("endmacro");)V.push(a());return new nM(G,L,V)}function v(G=!1){const L=G?ee:M,V=[L()],X=o(B.Comma);for(;X&&(++r,V.push(L()),!!o(B.Comma)););return X?new hf(V):V[0]}function y(){const G=v(!0);if(!(G instanceof ls||G instanceof hf))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${G.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const L=M();s(B.CloseStatement,"Expected closing statement token");const V=[];for(;!i("endfor","else");)V.push(a());const X=[];if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endfor");)X.push(a());return new eM(G,L,V,X)}function M(){return T()}function T(){const G=A();if(l("if")){++r;const L=A();if(l("else")){++r;const V=T();return new yM(L,G,V)}else return new fM(G,L)}return G}function A(){let G=C();for(;l("or");){const L=e[r];++r;const V=C();G=new Zs(L,G,V)}return G}function C(){let G=S();for(;l("and");){const L=e[r];++r;const V=S();G=new Zs(L,G,V)}return G}function S(){let G;for(;l("not");){const L=e[r];++r;const V=S();G=new pM(L,V)}return G??N()}function N(){let G=x();for(;;){let L;if(l("not","in"))L=new Pt("not in",B.Identifier),r+=2;else if(l("in"))L=e[r++];else if(o(B.ComparisonBinaryOperator))L=e[r++];else break;const V=x();G=new Zs(L,G,V)}return G}function x(){let G=I();for(;o(B.AdditiveBinaryOperator);){const L=e[r];++r;const V=I();G=new Zs(L,G,V)}return G}function R(){const G=D(ee());return o(B.OpenParen)?z(G):G}function z(G){let L=new uf(G,$());return L=D(L),o(B.OpenParen)&&(L=z(L)),L}function $(){s(B.OpenParen,"Expected opening parenthesis for arguments list");const G=Q();return s(B.CloseParen,"Expected closing parenthesis for arguments list"),G}function Q(){const G=[];for(;!o(B.CloseParen);){let L;if(e[r].type===B.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const V=M();L=new wM(V)}else if(L=M(),o(B.Equals)){if(++r,!(L instanceof ls))throw new SyntaxError("Expected identifier for keyword argument");const V=M();L=new gM(L,V)}G.push(L),o(B.Comma)&&++r}return G}function H(){const G=[];let L=!1;for(;!o(B.CloseSquareBracket);)o(B.Colon)?(G.push(void 0),++r,L=!0):(G.push(M()),o(B.Colon)&&(++r,L=!0));if(G.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(G.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new mM(...G)}return G[0]}function D(G){for(;o(B.Dot)||o(B.OpenSquareBracket);){const L=e[r];++r;let V;const X=L.type===B.OpenSquareBracket;if(X)V=H(),s(B.CloseSquareBracket,"Expected closing square bracket");else if(V=ee(),V.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");G=new oM(G,V,X)}return G}function I(){let G=te();for(;o(B.MultiplicativeBinaryOperator);){const L=e[r++],V=te();G=new Zs(L,G,V)}return G}function te(){let G=W();for(;l("is");){++r;const L=l("not");L&&++r;const V=ee();if(!(V instanceof ls))throw new SyntaxError("Expected identifier for the test");G=new _M(G,L,V)}return G}function W(){let G=R();for(;o(B.Pipe);){++r;let L=ee();if(!(L instanceof ls))throw new SyntaxError("Expected identifier for the filter");o(B.OpenParen)&&(L=z(L)),G=new dM(G,L)}return G}function ee(){const G=e[r++];switch(G.type){case B.NumericLiteral:{const L=G.value;return L.includes(".")?new lM(Number(L)):new iM(Number(L))}case B.StringLiteral:{let L=G.value;for(;o(B.StringLiteral);)L+=e[r++].value;return new df(L)}case B.Identifier:return new ls(G.value);case B.OpenParen:{const L=v();return s(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case B.OpenSquareBracket:{const L=[];for(;!o(B.CloseSquareBracket);)L.push(M()),o(B.Comma)&&++r;return++r,new cM(L)}case B.OpenCurlyBracket:{const L=new Map;for(;!o(B.CloseCurlyBracket);){const V=M();s(B.Colon,"Expected colon between key and value in object literal");const X=M();L.set(V,X),o(B.Comma)&&++r}return++r,new uM(L)}default:throw new SyntaxError(`Unexpected token: ${G.type}`)}}for(;r<e.length;)t.body.push(a());return t}function MM(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const s=[];if(r>0)for(let n=e;n<t;n+=r)s.push(n);else for(let n=e;n>t;n+=r)s.push(n);return s}function ff(e,t,r,s=1){const n=Math.sign(s);n>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;n*o<n*r;o+=s)a.push(e[o]);return a}function xM(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function kM(e){return TM(new Date,e)}function TM(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return n(e.getMonth()+1);case"%d":return n(e.getDate());case"%b":return s.format(e);case"%B":return r.format(e);case"%H":return n(e.getHours());case"%M":return n(e.getMinutes());case"%%":return"%";default:return a}})}function EM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function AM(e,t,r,s){if(s===0)return e;let n=s==null||s<0?1/0:s;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(EM(t),"gu");return e.replaceAll(a,o=>n>0?(--n,r):o)}var _f=class extends Error{},pf=class extends Error{},Kt=class{constructor(e=void 0){k(this,"type","RuntimeValue");k(this,"value");k(this,"builtins",new Map);this.value=e}__bool__(){return new oe(!!this.value)}toString(){return String(this.value)}},he=class extends Kt{constructor(){super(...arguments);k(this,"type","IntegerValue")}},$e=class extends Kt{constructor(){super(...arguments);k(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends Kt{constructor(){super(...arguments);k(this,"type","StringValue");k(this,"builtins",new Map([["upper",new Ne(()=>new Z(this.value.toUpperCase()))],["lower",new Ne(()=>new Z(this.value.toLowerCase()))],["strip",new Ne(()=>new Z(this.value.trim()))],["title",new Ne(()=>new Z(xM(this.value)))],["capitalize",new Ne(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Ne(()=>new Z(this.value.trimEnd()))],["lstrip",new Ne(()=>new Z(this.value.trimStart()))],["startswith",new Ne(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");const r=t[0];if(r instanceof Z)return new oe(this.value.startsWith(r.value));if(r instanceof ge){for(const s of r.value){if(!(s instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new oe(!0)}return new oe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ne(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");const r=t[0];if(r instanceof Z)return new oe(this.value.endsWith(r.value));if(r instanceof ge){for(const s of r.value){if(!(s instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new oe(!0)}return new oe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ne(t=>{const r=t[0]??new Re;if(!(r instanceof Z||r instanceof Re))throw new Error("sep argument must be a string or null");const s=t[1]??new he(-1);if(!(s instanceof he))throw new Error("maxsplit argument must be a number");let n=[];if(r instanceof Re){const a=this.value.trimStart();for(const{0:o,index:i}of a.matchAll(/\S+/g)){if(s.value!==-1&&n.length>=s.value&&i!==void 0){n.push(o+a.slice(i+o.length));break}n.push(o)}}else{if(r.value==="")throw new Error("empty separator");n=this.value.split(r.value),s.value!==-1&&n.length>s.value&&n.push(n.splice(s.value).join(r.value))}return new ge(n.map(a=>new Z(a)))})],["replace",new Ne(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");const r=t[0],s=t[1];if(!(r instanceof Z&&s instanceof Z))throw new Error("replace() arguments must be strings");let n;if(t.length>2?t[2].type==="KeywordArgumentsValue"?n=t[2].value.get("count")??new Re:n=t[2]:n=new Re,!(n instanceof he||n instanceof Re))throw new Error("replace() count argument must be a number or null");return new Z(AM(this.value,r.value,s.value,n.value))})]]))}},oe=class extends Kt{constructor(){super(...arguments);k(this,"type","BooleanValue")}},CM=/[\x7f-\uffff]/g;function mf(e){return e.replace(CM,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Hr(e,t={},r=0,s=!0){const{indent:n=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,c;switch(o?[l,c]=o:n?(l=",",c=": "):(l=", ",c=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let d=JSON.stringify(e.value);return a&&(d=mf(d)),d}case"ArrayValue":case"ObjectValue":{const d=n?" ".repeat(n):"",h=`
12
- `+d.repeat(r),_=h+d;if(e.type==="ArrayValue"){const p=e.value.map(w=>Hr(w,t,r+1,s));return n?`[${_}${p.join(`${l}${_}`)}${h}]`:`[${p.join(l)}]`}else{let p=Array.from(e.value.entries());i&&(p=p.sort(([v],[y])=>v.localeCompare(y)));const w=p.map(([v,y])=>{let M=JSON.stringify(v);a&&(M=mf(M));const T=`${M}${c}${Hr(y,t,r+1,s)}`;return n?`${_}${T}`:T});return n?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var Ze=class extends Kt{constructor(){super(...arguments);k(this,"type","ObjectValue");k(this,"builtins",new Map([["get",new Ne(([t,r])=>{if(!(t instanceof Z))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new Re})],["items",new Ne(()=>this.items())],["keys",new Ne(()=>this.keys())],["values",new Ne(()=>this.values())],["dictsort",new Ne(t=>{let r=new Map;const s=t.filter(l=>l instanceof en?(r=l.value,!1):!0),n=s.at(0)??r.get("case_sensitive")??new oe(!1);if(!(n instanceof oe))throw new Error("case_sensitive must be a boolean");const a=s.at(1)??r.get("by")??new Z("key");if(!(a instanceof Z))throw new Error("by must be a string");if(!["key","value"].includes(a.value))throw new Error("by must be either 'key' or 'value'");const o=s.at(2)??r.get("reverse")??new oe(!1);if(!(o instanceof oe))throw new Error("reverse must be a boolean");const i=Array.from(this.value.entries()).map(([l,c])=>new ge([new Z(l),c])).sort((l,c)=>{const d=a.value==="key"?0:1,h=l.value[d],_=c.value[d],p=vi(h,_,n.value);return o.value?-p:p});return new ge(i)})]]))}__bool__(){return new oe(this.value.size>0)}items(){return new ge(Array.from(this.value.entries()).map(([t,r])=>new ge([new Z(t),r])))}keys(){return new ge(Array.from(this.value.keys()).map(t=>new Z(t)))}values(){return new ge(Array.from(this.value.values()))}toString(){return Hr(this,{},0,!1)}},en=class extends Ze{constructor(){super(...arguments);k(this,"type","KeywordArgumentsValue")}},ge=class extends Kt{constructor(){super(...arguments);k(this,"type","ArrayValue");k(this,"builtins",new Map([["length",new he(this.value.length)]]))}__bool__(){return new oe(this.value.length>0)}toString(){return Hr(this,{},0,!1)}},gf=class extends ge{constructor(){super(...arguments);k(this,"type","TupleValue")}},Ne=class extends Kt{constructor(){super(...arguments);k(this,"type","FunctionValue")}},Re=class extends Kt{constructor(){super(...arguments);k(this,"type","NullValue")}},De=class extends Kt{constructor(){super(...arguments);k(this,"type","UndefinedValue")}},Qr=class{constructor(e){k(this,"variables",new Map([["namespace",new Ne(e=>{if(e.length===0)return new Ze(new Map);if(e.length!==1||!(e[0]instanceof Ze))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));k(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Ne],["odd",e=>{if(!(e instanceof he))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof he))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof he||e instanceof $e],["integer",e=>e instanceof he],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof Ze],["sequence",e=>e instanceof ge||e instanceof Ze||e instanceof Z],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));this.parent=e}set(e,t){return this.declareVariable(e,ia(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new De}catch{return new De}}};function SM(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",MM),e.set("strftime_now",kM),e.set("True",!0),e.set("False",!1),e.set("None",null)}function wf(e,t){const r=t.split(".");let s=e;for(const n of r)if(s instanceof Ze)s=s.value.get(n)??new De;else if(s instanceof ge){const a=parseInt(n,10);if(!isNaN(a)&&a>=0&&a<s.value.length)s=s.value[a];else return new De}else return new De;return s}function vi(e,t,r=!1){if(e instanceof Re&&t instanceof Re)return 0;if(e instanceof Re||t instanceof Re)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof De&&t instanceof De)return 0;if(e instanceof De||t instanceof De)throw new Error(`Cannot compare ${e.type} with ${t.type}`);const s=a=>a instanceof he||a instanceof $e||a instanceof oe,n=a=>a instanceof oe?a.value?1:0:a.value;if(s(e)&&s(t)){const a=n(e),o=n(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var PM=class{constructor(e){k(this,"global");this.global=e??new Qr}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}const s=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new oe(r.value==s.value);case"!=":return new oe(r.value!=s.value)}if(r instanceof De||s instanceof De){if(s instanceof De&&["in","not in"].includes(e.operator.value))return new oe(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Re||s instanceof Re)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Z(r.value.toString()+s.value.toString());if((r instanceof he||r instanceof $e)&&(s instanceof he||s instanceof $e)){const n=r.value,a=s.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?n+a:e.operator.value==="-"?n-a:n*a;return r instanceof $e||s instanceof $e?new $e(o):new he(o)}case"/":return new $e(n/a);case"%":{const o=n%a;return r instanceof $e||s instanceof $e?new $e(o):new he(o)}case"<":return new oe(n<a);case">":return new oe(n>a);case">=":return new oe(n>=a);case"<=":return new oe(n<=a)}}else if(r instanceof ge&&s instanceof ge)switch(e.operator.value){case"+":return new ge(r.value.concat(s.value))}else if(s instanceof ge){const n=s.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new oe(n);case"not in":return new oe(!n)}}}if(r instanceof Z||s instanceof Z)switch(e.operator.value){case"+":return new Z(r.value.toString()+s.value.toString())}if(r instanceof Z&&s instanceof Z)switch(e.operator.value){case"in":return new oe(s.value.includes(r.value));case"not in":return new oe(!s.value.includes(r.value))}if(r instanceof Z&&s instanceof Ze)switch(e.operator.value){case"in":return new oe(s.value.has(r.value));case"not in":return new oe(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,t){const r=[],s=new Map;for(const n of e)if(n.type==="SpreadExpression"){const a=n,o=this.evaluate(a.argument,t);if(!(o instanceof ge))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){const a=n;s.set(a.key.value,this.evaluate(a.value,t))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,t))}return[r,s]}applyFilter(e,t,r){if(t.type==="Identifier"){const s=t;if(s.value==="safe")return e;if(s.value==="tojson")return new Z(Hr(e,{}));if(e instanceof ge)switch(s.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new he(e.value.length);case"reverse":return new ge(e.value.slice().reverse());case"sort":return new ge(e.value.slice().sort((n,a)=>vi(n,a,!1)));case"join":return new Z(e.value.map(n=>n.value).join(""));case"string":return new Z(Hr(e,{},0,!1));case"unique":{const n=new Set,a=[];for(const o of e.value)n.has(o.value)||(n.add(o.value),a.push(o));return new ge(a)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof Z)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const n=e.builtins.get(s.value);if(n instanceof Ne)return n.value([],r);if(n instanceof he)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new Z(e.value.trim());case"indent":return new Z(e.value.split(`
5
+ */var yg,bg,vn,uu,yn,ft,Mg,xg,du,bn,Wa,Mn,Ha,Ns,Zr,Qa,xn,hu,kn,Xa,Tn,En,Ya,Ja,An,Ka,Za,eo,Cn,to,Sn,fu,_u,ro,Pn,Fn,Ln,so,no,ao,oo,io,pu,mu,gu,wu,vu,yu,bu,Mu,xu,ku,Tu,Eu,Au,Cu,Su,Pu,Fu,Lu,Iu,Ou,Nu,Du,zu,Bu,Ru,Gu,$u,Vu,Uu,ju;var Oe=Object.defineProperty,Ge=Object.getOwnPropertyDescriptor,rt=Object.getOwnPropertyNames,Rn=Object.prototype.hasOwnProperty,zv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),me=(e,t)=>()=>(e&&(t=e(e=0)),t),$s=(e,t)=>{for(var r in t)Oe(e,r,{get:t[r],enumerable:!0})},Bv=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of rt(t))!Rn.call(e,n)&&n!==r&&Oe(e,n,{get:()=>t[n],enumerable:!(s=Ge(t,n))||s.enumerable});return e},Gn=e=>Bv(Oe({},"__esModule",{value:!0}),e),Vs,kr,Br,bd,Md,xd=me(()=>{Vs=new Map,kr=[],Br=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=Vs.get(e);if(s===void 0)Vs.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=kr.indexOf(e);n!==-1&&kr.splice(n,1);for(let a=0;a<kr.length;a++)if(Vs.get(kr[a]).priority<=r){kr.splice(a,0,e);return}kr.push(e)}return}throw new TypeError("not a valid backend")},bd=async e=>{let t=Vs.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Md=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),s=r.length===0?kr:r,n,a=[],o=new Set;for(let l of s){let c=await bd(l);typeof c=="string"?a.push({name:l,err:c}):(n||(n=c),n===c&&o.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Rv=me(()=>{xd()}),kd,Gv=me(()=>{kd="1.24.0-dev.20251116-b39e144322"}),Mo,Ke,Td=me(()=>{Gv(),Mo="warning",Ke={wasm:{},webgl:{},webgpu:{},versions:{common:kd},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Mo=e}},get logLevel(){return Mo}},Object.defineProperty(Ke,"logLevel",{enumerable:!0})}),Be,$v=me(()=>{Td(),Be=Ke}),Ed,Ad,Vv=me(()=>{Ed=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let n,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*n,h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<n;y++){let M=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],S=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+M+","+T+","+A+","+S+")",s.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Ad=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,p=0,w=1,v=2,y=3,M=0,T=h,A=h*2,S=-1;i==="RGBA"?(M=0,T=h,A=h*2,S=h*3):i==="RGB"?(M=0,T=h,A=h*2):i==="RBG"&&(M=0,A=h,T=h*2),s=r.createImageData(n,a);for(let C=0;C<a*n;p+=_,w+=_,v+=_,y+=_,C++)s.data[p]=(e.data[M++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[y]=S===-1?255:(e.data[S++]-d[3])*c[3]}else throw new Error("Can not access image data");return s}}),$n,Cd,Sd,Pd,Fd,Ld,Uv=me(()=>{ko(),$n=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,v=3,y=0,M=c,T=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,y=c*2);for(let S=0;S<c;S++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[M++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new Mt("float32",d,[1,4,r,s]):new Mt("float32",d,[1,3,r,s])},Cd=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let _=l();_.width=h,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,$n(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{let _=l(),p=c(_);if(!e||!p)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);let v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d($n(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return $n(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Sd=(e,t)=>{let{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new Mt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Pd=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Mt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},Fd=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Mt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},Ld=(e,t,r)=>new Mt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Rr,Us,xo,Id,jv=me(()=>{Rr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Us=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xo=!1,Id=()=>{if(!xo){xo=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Rr.set("int64",BigInt64Array),Us.set(BigInt64Array,"int64")),t&&(Rr.set("uint64",BigUint64Array),Us.set(BigUint64Array,"uint64")),s?(Rr.set("float16",r),Us.set(r,"float16")):Rr.set("float16",Uint16Array)}}}),Od,Nd,qv=me(()=>{ko(),Od=e=>{let t=1;for(let r=0;r<e.length;r++){let s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},Nd=(e,t)=>{switch(e.location){case"cpu":return new Mt(e.type,e.data,t);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Mt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Mt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Mt,ko=me(()=>{Vv(),Uv(),jv(),qv(),Mt=class{constructor(e,t,r){Id();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let o=Rr.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,i;if(typeof e=="string")if(s=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Rr.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=Us.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=o,this.dataLocation="cpu"}let a=Od(n);if(this.cpuData&&a!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=a}static async fromImage(e,t){return Cd(e,t)}static fromTexture(e,t){return Sd(e,t)}static fromGpuBuffer(e,t){return Pd(e,t)}static fromMLTensor(e,t){return Fd(e,t)}static fromPinnedBuffer(e,t,r){return Ld(e,t,r)}toDataURL(e){return Ed(this,e)}toImageData(e){return Ad(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Nd(this,e)}}}),zt,Dd=me(()=>{ko(),zt=Mt}),Vn,To,Gr,$r,Tr,Er,zd=me(()=>{Td(),Vn=(e,t)=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.timeStamp(`${e}::ORT::${t}`)},To=(e,t)=>{var n;let r=((n=new Error().stack)==null?void 0:n.split(/\r\n|\r|\n/g))||[],s=!1;for(let a=0;a<r.length;a++){if(s&&!r[a].includes("TRACE_FUNC")){let o=`FUNC_${e}::${r[a].trim().split(" ")[1]}`;t&&(o+=`::${t}`),Vn("CPU",o);return}r[a].includes("TRACE_FUNC")&&(s=!0)}},Gr=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||To("BEGIN",e)},$r=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||To("END",e)},Tr=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.time(`ORT::${e}`)},Er=e=>{(typeof Ke.trace>"u"?!Ke.wasm.trace:!Ke.trace)||console.timeEnd(`ORT::${e}`)}}),Bd,Wv=me(()=>{xd(),Dd(),zd(),Bd=class Lv{constructor(t){this.handler=t}async run(t,r,s){Gr(),Tr("InferenceSession.run");let n={},a={};if(typeof t!="object"||t===null||t instanceof zt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof zt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let _=r[h];(_===null||_ instanceof zt)&&(c=!0,o=!1,n[h]=_)}if(c){if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(t,n,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof zt?l[c]=d:l[c]=new zt(d.type,d.data,d.dims)}return Er("InferenceSession.run"),$r(),l}async release(){return this.handler.dispose()}static async create(t,r,s,n){Gr(),Tr("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,h=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-h,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(d,h,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Md(o),c=await i.createInferenceSessionHandler(a,l);return Er("InferenceSession.create"),$r(),new Lv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Eo,Hv=me(()=>{Wv(),Eo=Bd}),Qv=me(()=>{}),Xv=me(()=>{}),Yv=me(()=>{}),Jv=me(()=>{}),Rd={};$s(Rd,{InferenceSession:()=>Eo,TRACE:()=>Vn,TRACE_EVENT_BEGIN:()=>Tr,TRACE_EVENT_END:()=>Er,TRACE_FUNC_BEGIN:()=>Gr,TRACE_FUNC_END:()=>$r,Tensor:()=>zt,env:()=>Be,registerBackend:()=>Br});var Vr=me(()=>{Rv(),$v(),Hv(),Dd(),Qv(),Xv(),zd(),Yv(),Jv()}),Ao=me(()=>{}),Gd={};$s(Gd,{default:()=>$d});var Co,So,$d,Kv=me(()=>{var e;Eh(),Ur(),No(),Co="ort-wasm-proxy-worker",So=((e=globalThis.self)==null?void 0:e.name)===Co,So&&(self.onmessage=t=>{let{type:r,in:s}=t.data;try{switch(r){case"init-wasm":Bo(s.wasm).then(()=>{Jo(s).then(()=>{postMessage({type:r})},n=>{postMessage({type:r,err:n})})},n=>{postMessage({type:r,err:n})});break;case"init-ep":{let{epName:n,env:a}=s;Ko(a,n).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:n}=s,a=Xn(n);postMessage({type:r,out:a});break}case"create":{let{model:n,options:a}=s;ei(n,a).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":ti(s),postMessage({type:r});break;case"run":{let{sessionId:n,inputIndices:a,inputs:o,outputIndices:i,options:l}=s;si(n,a,o,i,new Array(i.length).fill(null),l).then(c=>{c.some(d=>d[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:c},ai([...o,...c]))},c=>{postMessage({type:r,err:c})});break}case"end-profiling":ni(s),postMessage({type:r});break;default:}}catch(n){postMessage({type:r,err:n})}}),$d=So?null:t=>new Worker(t??xt,{type:"module",name:Co})}),Vd={};$s(Vd,{default:()=>jd});async function Ud(e={}){var Cv,Sv;var t=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&((Cv=self.name)==null?void 0:Cv.startsWith("em-pthread"));t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,f)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let a=()=>{let u=f=>(...m)=>{let g=or;return m=f(...m),or!=g?new Promise((b,E)=>{ed={resolve:b,reject:E}}):m};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=u(t[f])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a==null||a()};var o,i,l=(u,f)=>{throw f},c=self.location.href,d="";if(r||s){try{d=new URL(".",c).href}catch{}s&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async u=>{if(I(u))return new Promise((m,g)=>{var b=new XMLHttpRequest;b.open("GET",u,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?m(b.response):g(b.status)},b.onerror=g,b.send(null)});var f=await fetch(u,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}var h,_,p,w,v,y,M=console.log.bind(console),T=console.error.bind(console),A=M,S=T,C=!1,I=u=>u.startsWith("file://");function x(){Dr.buffer!=z.buffer&&X()}if(n){let u=function(f){try{var m=f.data,g=m.Oc;if(g==="load"){let b=[];self.onmessage=E=>b.push(E),y=()=>{postMessage({Oc:"loaded"});for(let E of b)u(E);self.onmessage=u};for(let E of m.ce)t[E]&&!t[E].proxy||(t[E]=(...F)=>{postMessage({Oc:"callHandler",be:E,args:F})},E=="print"&&(A=t[E]),E=="printErr"&&(S=t[E]));Dr=m.ie,X(),_=m.je,Fe(),vo()}else if(g==="run"){(function(b){var E=(x(),O)[b+52>>>2>>>0];b=(x(),O)[b+56>>>2>>>0],Rw(E,E-b),ae(E)})(m.Nc),hd(m.Nc,0,0,1,0,0),Eg(),Ju(m.Nc),R||(bw(),R=!0);try{_O(m.ge,m.Wc)}catch(b){if(b!="unwind")throw b}}else m.target!=="setimmediate"&&(g==="checkMailbox"?R&&uo():g&&(S(`worker: received unknown command ${g}`),S(m)))}catch(b){throw Ow(),b}};var R=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var z,$,Q,H,D,O,te,W,ee,G,L,V=!1;function X(){var u=Dr.buffer;t.HEAP8=z=new Int8Array(u),Q=new Int16Array(u),t.HEAPU8=$=new Uint8Array(u),H=new Uint16Array(u),t.HEAP32=D=new Int32Array(u),t.HEAPU32=O=new Uint32Array(u),te=new Float32Array(u),W=new Float64Array(u),ee=new BigInt64Array(u),G=new BigUint64Array(u)}function J(){V=!0,n?y():xr._b()}function we(u){throw S(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v==null||v(u),u}function re(){return{a:{f:pO,J:mO,k:gO,p:wO,l:vO,sa:yO,b:bO,ca:MO,Ja:Lg,q:xO,da:Dg,Za:zg,Fa:Bg,Ha:Rg,_a:Gg,Xa:$g,Qa:Vg,Wa:Ug,oa:jg,Ga:qg,Xb:Wg,Ya:Hg,Yb:Qg,db:kO,Da:TO,Sb:EO,Qb:CO,Ca:PO,M:FO,I:LO,Rb:IO,ja:GO,Tb:$O,Ta:VO,Vb:jO,Ka:qO,Ob:WO,ka:HO,Sa:Ju,ab:QO,U:KO,n:sN,c:Xu,rb:nN,w:aN,L:oN,z:iN,j:lN,o:rw,sb:cN,G:uN,T:dN,h:hN,u:fN,m:_N,i:pN,Na:mN,Oa:gN,Pa:wN,La:ow,Ma:iw,Pb:lw,eb:yN,cb:MN,Y:xN,qb:kN,la:TN,bb:bN,fb:EN,$a:AN,Wb:CN,N:vN,gb:SN,X:PN,Ub:FN,nb:GN,C:$N,ra:VN,qa:UN,pb:jN,W:qN,v:WN,mb:HN,lb:QN,kb:XN,ob:YN,jb:JN,ib:KN,hb:ZN,Ua:_w,Va:pw,Ia:nr,V:mw,na:gw,Ra:ww,ma:vw,Cb:cD,xa:sD,Db:lD,ya:rD,F:q3,e:L3,s:P3,x:S3,B:V3,Fb:Z3,ba:K3,D:N3,za:eD,$:nD,ga:J3,Gb:Y3,Hb:X3,Ba:W3,Aa:Q3,Ib:H3,wa:iD,aa:tD,d:F3,A:O3,r:I3,Bb:uD,t:z3,y:U3,H:D3,E:B3,K:j3,R:aD,ia:$3,_:oD,Jb:G3,Kb:R3,g:t3,a:Dr,Nb:Pe,Eb:r3,ha:s3,O:n3,pa:a3,Lb:o3,ta:i3,Q:l3,yb:c3,zb:u3,ua:d3,ea:h3,P:f3,Ea:_3,va:p3,Z:m3,wb:g3,Zb:w3,S:v3,Ab:y3,tb:b3,ub:x3,vb:k3,fa:T3,xb:E3,Mb:A3}}}async function Fe(){function u(g,b){var E=xr=g.exports;g={};for(let[F,N]of Object.entries(E))typeof N=="function"?(E=XO(N),g[F]=E):g[F]=N;return xr=g,xr=(function(){var F=xr,N=Y=>ye=>Y(ye)>>>0,j=Y=>()=>Y()>>>0;return(F=Object.assign({},F)).$b=N(F.$b),F.Cc=j(F.Cc),F.Ec=N(F.Ec),F.rd=(Y=>(ye,K)=>Y(ye,K)>>>0)(F.rd),F.wd=N(F.wd),F.xd=j(F.xd),F.Bd=N(F.Bd),F})(),kg.push(xr.id),yw=(g=xr).$b,bw=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,od=t._OrtGetWebGpuDevice=g.Bc,go=g.Cc,Xt=t._free=g.Dc,Gs=t._malloc=g.Ec,Mw=t._wgpuBufferRelease=g.Fc,xw=t._wgpuCreateInstance=g.Gc,kw=g.Hc,Tw=g.Ic,Ew=g.Jc,Aw=g.Kc,Cw=g.Lc,Sw=g.Pc,Pw=g.Zc,Fw=g._c,Lw=g.$c,id=g.bd,ld=g.cd,cd=g.dd,ud=g.ed,Dn=g.fd,dd=g.gd,Iw=g.hd,hd=g.kd,Ow=g.ld,Nw=g.md,Dw=g.nd,fd=g.od,zw=g.pd,Bw=g.qd,_d=g.rd,pe=g.sd,zn=g.td,Rw=g.ud,ae=g.vd,wo=g.wd,oe=g.xd,Gw=g.yd,pd=g.zd,$w=g.Ad,Vw=g.Bd,Uw=g.Cd,md=g.Dd,jw=g.Ed,qw=g.Fd,Ww=g.Gd,Hw=g.Hd,Qw=g.Id,Xw=g.Jd,Yw=g.Kd,Jw=g.Ld,Kw=g.Md,Zw=g.Nd,ev=g.Od,tv=g.Pd,rv=g.Qd,sv=g.Rd,nv=g.Td,av=g.Ud,ov=g.Vd,iv=g.Wd,lv=g.Yd,cv=g.Zd,uv=g._d,dv=g.$d,hv=g.ae,fv=g.oe,_v=g.pe,pv=g.qe,mv=g.re,gv=g.se,wv=g.te,vv=g.ue,yv=g.ve,bv=g.we,Mv=g.xe,xv=g.ye,kv=g.Ye,Tv=g.Ze,Ev=g._e,Av=g.$e,_=b,xr}var f,m=re();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(m,(b,E)=>{g(u(b,E))})}):n?u(new WebAssembly.Instance(_,re()),_):(L??(L=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL(""+new URL("ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",self.location.href).href,self.location.href).href),f=await(async function(g){var b=L;if(!h&&!I(b))try{var E=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(E,g)}catch(F){S(`wasm streaming compile failed: ${F}`),S("falling back to ArrayBuffer instantiation")}return(async function(F,N){try{var j=await(async function(Y){if(!h)try{var ye=await o(Y);return new Uint8Array(ye)}catch{}if(Y==L&&h)Y=new Uint8Array(h);else{if(!i)throw"both async and sync fetching of the wasm failed";Y=i(Y)}return Y})(F);return await WebAssembly.instantiate(j,N)}catch(Y){S(`failed to asynchronously prepare wasm: ${Y}`),we(Y)}})(b,g)})(m),u(f.instance,f.module))}class qe{constructor(f){k(this,"name","ExitStatus");this.message=`Program terminated with exit(${f})`,this.status=f}}var bt=u=>{u.terminate(),u.onmessage=()=>{}},It=[],Ot=0,Qe=null,pt=u=>{Nt.length==0&&(Cg(),Ag(Nt[0]));var f=Nt.pop();if(!f)return 6;In.push(f),es[u.Nc]=f,f.Nc=u.Nc;var m={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return f.postMessage(m,u.Yc),0},Me=0,ce=(u,f,...m)=>{var g,b=16*m.length,E=oe(),F=wo(b),N=F>>>3;for(g of m)typeof g=="bigint"?((x(),ee)[N++>>>0]=1n,(x(),ee)[N++>>>0]=g):((x(),ee)[N++>>>0]=0n,(x(),W)[N++>>>0]=g);return u=Nw(u,0,b,F,f),ae(E),u};function Pe(u){if(n)return ce(0,1,u);if(p=u,!(0<Me)){for(var f of In)bt(f);for(f of Nt)bt(f);Nt=[],In=[],es={},C=!0}l(0,new qe(u))}function mt(u){if(n)return ce(1,0,u);nr(u)}var nr=u=>{if(p=u,n)throw mt(u),"unwind";Pe(u)},Nt=[],In=[],kg=[],es={},Tg=u=>{var f=u.Nc;delete es[f],Nt.push(u),In.splice(In.indexOf(u),1),u.Nc=0,Dw(f)};function Eg(){kg.forEach(u=>u())}var Ag=u=>new Promise(f=>{u.onmessage=b=>{var E=b.data;if(b=E.Oc,E.Vc&&E.Vc!=go()){var F=es[E.Vc];F?F.postMessage(E,E.Yc):S(`Internal error! Worker sent a message "${b}" to target pthread ${E.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?uo():b==="spawnThread"?pt(E):b==="cleanupThread"?gt(()=>{Tg(es[E.he])}):b==="loaded"?(u.loaded=!0,f(u)):E.target==="setimmediate"?u.postMessage(E):b==="uncaughtException"?u.onerror(E.error):b==="callHandler"?t[E.be](...E.args):b&&S(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw S(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var m,g=[];for(m of[])t.propertyIsEnumerable(m)&&g.push(m);u.postMessage({Oc:"load",ce:g,ie:Dr,je:_})});function Cg(){var u=new Worker((()=>{let f=URL;return self.location.href>"file:"&&self.location.href<"file;"?new f("ort.webgpu.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Nt.push(u)}var Dr,_O=(u,f)=>{Me=0,u=md(u,f),0<Me?p=u:fd(u)},lo=[],co=0,ot=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function pO(u){var f=new qu(u>>>=0);return(x(),z)[f.Qc+12>>>0]==0&&(Sg(f,!0),co--),Pg(f,!1),lo.push(f),Vw(u)}var Ds=0,mO=()=>{pe(0,0);var u=lo.pop();Gw(u.Xc),Ds=0};function Sg(u,f){f=f?1:0,(x(),z)[u.Qc+12>>>0]=f}function Pg(u,f){f=f?1:0,(x(),z)[u.Qc+13>>>0]=f}class qu{constructor(f){this.Xc=f,this.Qc=f-24}}var Wu=u=>{var f=Ds;if(!f)return zn(0),0;var m=new qu(f);(x(),O)[m.Qc+16>>>2>>>0]=f;var g=(x(),O)[m.Qc+4>>>2>>>0];if(!g)return zn(0),f;for(var b of u){if(b===0||b===g)break;if($w(b,g,m.Qc+16))return zn(b),f}return zn(g),f};function gO(){return Wu([])}function wO(u){return Wu([u>>>0])}function vO(u,f,m,g){return Wu([u>>>0,f>>>0,m>>>0,g>>>0])}var yO=()=>{var u=lo.pop();u||we("no exception to throw");var f=u.Xc;throw(x(),z)[u.Qc+13>>>0]==0&&(lo.push(u),Pg(u,!0),Sg(u,!1),co++),pd(f),Ds=f};function bO(u,f,m){var g=new qu(u>>>=0);throw f>>>=0,m>>>=0,(x(),O)[g.Qc+16>>>2>>>0]=0,(x(),O)[g.Qc+4>>>2>>>0]=f,(x(),O)[g.Qc+8>>>2>>>0]=m,pd(u),co++,Ds=u}var MO=()=>co;function Fg(u,f,m,g){return n?ce(2,1,u,f,m,g):Lg(u,f,m,g)}function Lg(u,f,m,g){if(u>>>=0,f>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Fg(u,f,m,g):(u={fe:m,Nc:u,Wc:g,Yc:b},n?(u.Oc="spawnThread",postMessage(u,b),0):pt(u))}function xO(u){throw Ds||(Ds=u>>>0),Ds}var Ig=globalThis.TextDecoder&&new TextDecoder,Og=(u,f,m,g)=>{if(m=f+m,g)return m;for(;u[f]&&!(f>=m);)++f;return f},Ng=(u,f=0,m,g)=>{if(16<(m=Og(u,f>>>=0,m,g))-f&&u.buffer&&Ig)return Ig.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,m):u.slice(f,m));for(g="";f<m;){var b=u[f++];if(128&b){var E=63&u[f++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|E);else{var F=63&u[f++];65536>(b=(240&b)==224?(15&b)<<12|E<<6|F:(7&b)<<18|E<<12|F<<6|63&u[f++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},zs=(u,f,m)=>(u>>>=0)?Ng((x(),$),u,f,m):"";function Dg(u,f,m){return n?ce(3,1,u,f,m):0}function zg(u,f){if(n)return ce(4,1,u,f)}function Bg(u,f){if(n)return ce(5,1,u,f)}function Rg(u,f,m){if(n)return ce(6,1,u,f,m)}function Gg(u,f,m){return n?ce(7,1,u,f,m):0}function $g(u,f){if(n)return ce(8,1,u,f)}function Vg(u,f,m){if(n)return ce(9,1,u,f,m)}function Ug(u,f,m,g){if(n)return ce(10,1,u,f,m,g)}function jg(u,f,m,g){if(n)return ce(11,1,u,f,m,g)}function qg(u,f,m,g){if(n)return ce(12,1,u,f,m,g)}function Wg(u){if(n)return ce(13,1,u)}function Hg(u,f){if(n)return ce(14,1,u,f)}function Qg(u,f,m){if(n)return ce(15,1,u,f,m)}var kO=()=>we(""),ar=u=>{u>>>=0;for(var f="";;){var m=(x(),$)[u++>>>0];if(!m)return f;f+=String.fromCharCode(m)}},Hu={},Qu={},Bs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function wr(u,f,m={}){return(function(g,b,E={}){var F=b.name;if(!g)throw new Bs(`type "${F}" must have a positive integer typeid pointer`);if(Qu.hasOwnProperty(g)){if(E.de)return;throw new Bs(`Cannot register type '${F}' twice`)}Qu[g]=b,Hu.hasOwnProperty(g)&&(b=Hu[g],delete Hu[g],b.forEach(N=>N()))})(u,f,m)}var Xg=(u,f,m)=>{switch(f){case 1:return m?g=>(x(),z)[g>>>0]:g=>(x(),$)[g>>>0];case 2:return m?g=>(x(),Q)[g>>>1>>>0]:g=>(x(),H)[g>>>1>>>0];case 4:return m?g=>(x(),D)[g>>>2>>>0]:g=>(x(),O)[g>>>2>>>0];case 8:return m?g=>(x(),ee)[g>>>3>>>0]:g=>(x(),G)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function TO(u,f,m,g,b){u>>>=0,m>>>=0,f=ar(f>>>0);let E=F=>F;if(g=g===0n){let F=8*m;E=N=>BigInt.asUintN(F,N),b=E(b)}wr(u,{name:f,Mc:E,Sc:(F,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Rc:Xg(f,m,!g),Tc:null})}function EO(u,f,m,g){wr(u>>>=0,{name:f=ar(f>>>0),Mc:function(b){return!!b},Sc:function(b,E){return E?m:g},Rc:function(b){return this.Mc((x(),$)[b>>>0])},Tc:null})}var Yg=[],ts=[0,1,,1,null,1,!0,1,!1,1];function Xu(u){9<(u>>>=0)&&--ts[u+1]==0&&(ts[u]=void 0,Yg.push(u))}var Dt=u=>{if(!u)throw new Bs(`Cannot use deleted val. handle = ${u}`);return ts[u]},Qt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Yg.pop()||ts.length;return ts[f]=u,ts[f+1]=1,f}};function Yu(u){return this.Mc((x(),O)[u>>>2>>>0])}var AO={name:"emscripten::val",Mc:u=>{var f=Dt(u);return Xu(u),f},Sc:(u,f)=>Qt(f),Rc:Yu,Tc:null};function CO(u){return wr(u>>>0,AO)}var SO=(u,f)=>{switch(f){case 4:return function(m){return this.Mc((x(),te)[m>>>2>>>0])};case 8:return function(m){return this.Mc((x(),W)[m>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function PO(u,f,m){m>>>=0,wr(u>>>=0,{name:f=ar(f>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:SO(f,m),Tc:null})}function FO(u,f,m,g,b){u>>>=0,m>>>=0,f=ar(f>>>0);let E=N=>N;if(g===0){var F=32-8*m;E=N=>N<<F>>>F,b=E(b)}wr(u,{name:f,Mc:E,Sc:(N,j)=>j,Rc:Xg(f,m,g!==0),Tc:null})}function LO(u,f,m){function g(E){var F=(x(),O)[E>>>2>>>0];return E=(x(),O)[E+4>>>2>>>0],new b((x(),z).buffer,E,F)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];wr(u>>>=0,{name:m=ar(m>>>0),Mc:g,Rc:g},{de:!0})}var vr=(u,f,m)=>{var g=(x(),$);if(f>>>=0,0<m){var b=f;m=f+m-1;for(var E=0;E<u.length;++E){var F=u.codePointAt(E);if(127>=F){if(f>=m)break;g[f++>>>0]=F}else if(2047>=F){if(f+1>=m)break;g[f++>>>0]=192|F>>6,g[f++>>>0]=128|63&F}else if(65535>=F){if(f+2>=m)break;g[f++>>>0]=224|F>>12,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F}else{if(f+3>=m)break;g[f++>>>0]=240|F>>18,g[f++>>>0]=128|F>>12&63,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F,E++}}g[f>>>0]=0,u=f-b}else u=0;return u},yr=u=>{for(var f=0,m=0;m<u.length;++m){var g=u.charCodeAt(m);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++m):f+=3}return f};function IO(u,f){wr(u>>>=0,{name:f=ar(f>>>0),Mc(m){var g=(x(),O)[m>>>2>>>0];return g=zs(m+4,g,!0),Xt(m),g},Sc(m,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Bs("Cannot pass non-string to std::string");var E=b?yr(g):g.length,F=Gs(4+E+1),N=F+4;return(x(),O)[F>>>2>>>0]=E,b?vr(g,N,E+1):(x(),$).set(g,N>>>0),m!==null&&m.push(Xt,F),F},Rc:Yu,Tc(m){Xt(m)}})}var Jg=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,OO=(u,f,m)=>{if(u>>>=1,16<(f=Og((x(),H),u,f/2,m))-u&&Jg)return Jg.decode((x(),H).slice(u,f));for(m="";u<f;++u){var g=(x(),H)[u>>>0];m+=String.fromCharCode(g)}return m},NO=(u,f,m)=>{if(m??(m=2147483647),2>m)return 0;var g=f;m=(m-=2)<2*u.length?m/2:u.length;for(var b=0;b<m;++b){var E=u.charCodeAt(b);(x(),Q)[f>>>1>>>0]=E,f+=2}return(x(),Q)[f>>>1>>>0]=0,f-g},DO=u=>2*u.length,zO=(u,f,m)=>{var g="";u>>>=2;for(var b=0;!(b>=f/4);b++){var E=(x(),O)[u+b>>>0];if(!E&&!m)break;g+=String.fromCodePoint(E)}return g},BO=(u,f,m)=>{if(f>>>=0,m??(m=2147483647),4>m)return 0;var g=f;m=g+m-4;for(var b=0;b<u.length;++b){var E=u.codePointAt(b);if(65535<E&&b++,(x(),D)[f>>>2>>>0]=E,(f+=4)+4>m)break}return(x(),D)[f>>>2>>>0]=0,f-g},RO=u=>{for(var f=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,f+=4;return f};function GO(u,f,m){if(u>>>=0,f>>>=0,m=ar(m>>>=0),f===2)var g=OO,b=NO,E=DO;else g=zO,b=BO,E=RO;wr(u,{name:m,Mc:F=>{var N=(x(),O)[F>>>2>>>0];return N=g(F+4,N*f,!0),Xt(F),N},Sc:(F,N)=>{if(typeof N!="string")throw new Bs(`Cannot pass non-string to C++ string type ${m}`);var j=E(N),Y=Gs(4+j+f);return(x(),O)[Y>>>2>>>0]=j/f,b(N,Y+4,j+f),F!==null&&F.push(Xt,Y),Y},Rc:Yu,Tc(F){Xt(F)}})}function $O(u,f){wr(u>>>=0,{ee:!0,name:f=ar(f>>>0),Mc:()=>{},Sc:()=>{}})}function VO(u){hd(u>>>0,!s,1,!r,131072,!1),Eg()}var gt=u=>{if(!C)try{if(u(),!(0<Me))try{n?go()&&fd(p):nr(p)}catch(f){f instanceof qe||f=="unwind"||l(0,f)}}catch(f){f instanceof qe||f=="unwind"||l(0,f)}},UO=!Atomics.waitAsync||((Sv=globalThis.navigator)==null?void 0:Sv.userAgent)&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ju(u){u>>>=0,UO||(Atomics.waitAsync((x(),D),u>>>2,u).value.then(uo),u+=128,Atomics.store((x(),D),u>>>2,1))}var uo=()=>gt(()=>{var u=go();u&&(Ju(u),Bw())});function jO(u,f){(u>>>=0)==f>>>0?setTimeout(uo):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=es[u])&&u.postMessage({Oc:"checkMailbox"})}var Ku=[];function qO(u,f,m,g,b){for(f>>>=0,b>>>=0,Ku.length=0,m=b>>>3,g=b+g>>>3;m<g;){var E;E=(x(),ee)[m++>>>0]?(x(),ee)[m++>>>0]:(x(),W)[m++>>>0],Ku.push(E)}return(f?gd[f]:C3[u])(...Ku)}var WO=()=>{Me=0};function HO(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):Tg(es[u])}function QO(u){}var ho=u=>{try{u()}catch(f){we(f)}};function XO(u){var f=(...m)=>{fo.push(u);try{return u(...m)}finally{C||(fo.pop(),or&&zr===1&&fo.length===0&&(zr=0,Me+=1,ho(Tv),typeof Fibers<"u"&&Fibers.Be()))}};return ew.set(u,f),f}var zr=0,or=null,Kg=0,fo=[],Zu=new Map,Zg=new Map,ew=new Map,YO=0,ed=null,JO=[],tw=u=>(function(f){if(!C){if(zr===0){var m=!1,g=!1;f((b=0)=>{if(!C&&(Kg=b,m=!0,g)){zr=2,ho(()=>Ev(or)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var E=(function(){var j=(x(),D)[or+8>>>2>>>0];return j=Zg.get(j),j=ew.get(j),--Me,j()})()}catch(j){E=j,b=!0}var F=!1;if(!or){var N=ed;N&&(ed=null,(b?N.reject:N.resolve)(E),F=!0)}if(b&&!F)throw E}}),g=!0,m||(zr=1,or=(function(){var b=Gs(65548),E=b+12;if((x(),O)[b>>>2>>>0]=E,(x(),O)[b+4>>>2>>>0]=E+65536,E=fo[0],!Zu.has(E)){var F=YO++;Zu.set(E,F),Zg.set(F,E)}return E=Zu.get(E),(x(),D)[b+8>>>2>>>0]=E,b})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),ho(()=>kv(or)))}else zr===2?(zr=0,ho(Av),Xt(or),or=null,JO.forEach(gt)):we(`invalid state: ${zr}`);return Kg}})(f=>{u().then(f)});function KO(u){return u>>>=0,tw(async()=>{var f=await Dt(u);return Qt(f)})}var td=[],ZO=u=>{var f=td.length;return td.push(u),f},eN=(u,f)=>{for(var m=Array(u),g=0;g<u;++g){var b=g,E=(x(),O)[f+4*g>>>2>>>0],F=Qu[E];if(F===void 0)throw u=`parameter ${g}`,E=yw(E),f=ar(E),Xt(E),new Bs(`${u} has unknown type ${f}`);m[b]=F}return m},tN=(u,f,m)=>{var g=[];return u=u(g,m),g.length&&((x(),O)[f>>>2>>>0]=Qt(g)),u},rN={},_o=u=>{var f=rN[u];return f===void 0?ar(u):f};function sN(u,f,m){var[g,...b]=eN(u,f>>>0);f=g.Sc.bind(g);var E=b.map(j=>j.Rc.bind(j));u--;var F={toValue:Dt};switch(u=E.map((j,Y)=>{var ye=`argFromPtr${Y}`;return F[ye]=j,`${ye}(args${Y?"+"+8*Y:""})`}),m){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:F.getStringOrSymbol=_o,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${u})`,g.ee||(F.toReturnWire=f,F.emval_returnValue=tN,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) {
6
+ ${N}
7
+ }`,m=new Function(Object.keys(F),N)(...Object.values(F)),N=`methodCaller<(${b.map(j=>j.name)}) => ${g.name}>`,ZO(Object.defineProperty(m,"name",{value:N}))}function nN(u,f){return f>>>=0,(u=Dt(u>>>0))==Dt(f)}function aN(u){return(u>>>=0)?(u=_o(u),Qt(globalThis[u])):Qt(globalThis)}function oN(u){return u=_o(u>>>0),Qt(t[u])}function iN(u,f){return f>>>=0,u=Dt(u>>>0),f=Dt(f),Qt(u[f])}function lN(u){9<(u>>>=0)&&(ts[u+1]+=1)}function rw(u,f,m,g,b){return td[u>>>0](f>>>0,m>>>0,g>>>0,b>>>0)}function cN(u,f,m,g,b){return rw(u>>>0,f>>>0,m>>>0,g>>>0,b>>>0)}function uN(){return Qt([])}function dN(u){u=Dt(u>>>0);for(var f=Array(u.length),m=0;m<u.length;m++)f[m]=u[m];return Qt(f)}function hN(u){return Qt(_o(u>>>0))}function fN(){return Qt({})}function _N(u){for(var f=Dt(u>>>=0);f.length;){var m=f.pop();f.pop()(m)}Xu(u)}function pN(u,f,m){f>>>=0,m>>>=0,u=Dt(u>>>0),f=Dt(f),m=Dt(m),u[f]=m}function mN(u,f){u=ot(u),f>>>=0,u=new Date(1e3*u),(x(),D)[f>>>2>>>0]=u.getUTCSeconds(),(x(),D)[f+4>>>2>>>0]=u.getUTCMinutes(),(x(),D)[f+8>>>2>>>0]=u.getUTCHours(),(x(),D)[f+12>>>2>>>0]=u.getUTCDate(),(x(),D)[f+16>>>2>>>0]=u.getUTCMonth(),(x(),D)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(x(),D)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),D)[f+28>>>2>>>0]=u}var sw=u=>u%4==0&&(u%100!=0||u%400==0),nw=[0,31,60,91,121,152,182,213,244,274,305,335],aw=[0,31,59,90,120,151,181,212,243,273,304,334];function gN(u,f){u=ot(u),f>>>=0,u=new Date(1e3*u),(x(),D)[f>>>2>>>0]=u.getSeconds(),(x(),D)[f+4>>>2>>>0]=u.getMinutes(),(x(),D)[f+8>>>2>>>0]=u.getHours(),(x(),D)[f+12>>>2>>>0]=u.getDate(),(x(),D)[f+16>>>2>>>0]=u.getMonth(),(x(),D)[f+20>>>2>>>0]=u.getFullYear()-1900,(x(),D)[f+24>>>2>>>0]=u.getDay();var m=(sw(u.getFullYear())?nw:aw)[u.getMonth()]+u.getDate()-1|0;(x(),D)[f+28>>>2>>>0]=m,(x(),D)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),m=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(m!=g&&u.getTimezoneOffset()==Math.min(g,m)),(x(),D)[f+32>>>2>>>0]=u}function wN(u){u>>>=0;var f=new Date((x(),D)[u+20>>>2>>>0]+1900,(x(),D)[u+16>>>2>>>0],(x(),D)[u+12>>>2>>>0],(x(),D)[u+8>>>2>>>0],(x(),D)[u+4>>>2>>>0],(x(),D)[u>>>2>>>0],0),m=(x(),D)[u+32>>>2>>>0],g=f.getTimezoneOffset(),b=new Date(f.getFullYear(),6,1).getTimezoneOffset(),E=new Date(f.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(E,b);return 0>m?(x(),D)[u+32>>>2>>>0]=+(b!=E&&F==g):0<m!=(F==g)&&(b=Math.max(E,b),f.setTime(f.getTime()+6e4*((0<m?F:b)-g))),(x(),D)[u+24>>>2>>>0]=f.getDay(),m=(sw(f.getFullYear())?nw:aw)[f.getMonth()]+f.getDate()-1|0,(x(),D)[u+28>>>2>>>0]=m,(x(),D)[u>>>2>>>0]=f.getSeconds(),(x(),D)[u+4>>>2>>>0]=f.getMinutes(),(x(),D)[u+8>>>2>>>0]=f.getHours(),(x(),D)[u+12>>>2>>>0]=f.getDate(),(x(),D)[u+16>>>2>>>0]=f.getMonth(),(x(),D)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function ow(u,f,m,g,b,E,F){return n?ce(16,1,u,f,m,g,b,E,F):-52}function iw(u,f,m,g,b,E){if(n)return ce(17,1,u,f,m,g,b,E)}var On={},vN=()=>performance.timeOrigin+performance.now();function lw(u,f){if(n)return ce(18,1,u,f);if(On[u]&&(clearTimeout(On[u].id),delete On[u]),!f)return 0;var m=setTimeout(()=>{delete On[u],gt(()=>zw(u,performance.timeOrigin+performance.now()))},f);return On[u]={id:m,Ae:f},0}function yN(u,f,m,g){u>>>=0,f>>>=0,m>>>=0,g>>>=0;var b=new Date().getFullYear(),E=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var F=Math.max(E,b);(x(),O)[u>>>2>>>0]=60*F,(x(),D)[f>>>2>>>0]=+(E!=b),u=(f=N=>{var j=Math.abs(N);return`UTC${0<=N?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(E),f=f(b),b<E?(vr(u,m,17),vr(f,g,17)):(vr(u,g,17),vr(f,m,17))}var bN=()=>Date.now();function MN(u,f,m){return m>>>=0,0<=u&&3>=u?(u===0?u=Date.now():u=performance.timeOrigin+performance.now(),u=Math.round(1e6*u),(x(),ee)[m>>>3>>>0]=BigInt(u),0):28}var rd=[],cw=(u,f)=>{rd.length=0;for(var m;m=(x(),$)[u++>>>0];){var g=m!=105;f+=(g&=m!=112)&&f%8?4:0,rd.push(m==112?(x(),O)[f>>>2>>>0]:m==106?(x(),ee)[f>>>3>>>0]:m==105?(x(),D)[f>>>2>>>0]:(x(),W)[f>>>3>>>0]),f+=g?8:4}return rd};function xN(u,f,m){return u>>>=0,f=cw(f>>>0,m>>>0),gd[u](...f)}function kN(u,f,m){return u>>>=0,f=cw(f>>>0,m>>>0),gd[u](...f)}var TN=()=>{};function EN(u,f){return S(zs(u>>>0,f>>>0))}var AN=()=>{throw Me+=1,"unwind"};function CN(){return 4294901760}var SN=()=>1,PN=()=>navigator.hardwareConcurrency;function FN(u){u>>>=0;var f=(x(),$).length;if(u<=f||4294901760<u)return!1;for(var m=1;4>=m;m*=2){var g=f*(1+.2/m);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Dr.buffer.byteLength+65535)/65536|0;try{Dr.grow(g),X();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var ir=u=>{var f=yr(u)+1,m=wo(f);return vr(u,m,f),m},sd=(u,f)=>{(x(),O)[u>>>2>>>0]=f;var m=(x(),O)[u>>>2>>>0];(x(),O)[u+4>>>2>>>0]=(f-m)/4294967296},Nn=u=>(x(),O)[u>>>2>>>0]+4294967296*(x(),D)[u+4>>>2>>>0],it=[],LN=(u,f)=>{it[u>>>0]=f},br=[],po=[],Rs=(u,f)=>{po[u]=new Promise(m=>f.finally(()=>m(u)))},se=u=>{if(u)return it[u>>>0]},IN=(u,f)=>{for(u=(x(),O)[u>>>2>>>0];u;u=(x(),O)[u>>>2>>>0])f[(x(),D)[u+4>>>2>>>0]](u)},mo=(u,f,m)=>{(x(),O)[u>>>2>>>0]=f,(x(),O)[u+4>>>2>>>0]=m},uw=u=>{var f=(x(),O)[u>>>2>>>0];return u=(x(),O)[u+4>>>2>>>0],zs(f,u)},Mr=u=>{var f=(x(),O)[u>>>2>>>0];return u=(x(),O)[u+4>>>2>>>0],f?zs(f,u):u===0?"":void 0},ON=u=>{var f=Mr(u+4),m=(m=(x(),O)[u+12>>>2>>>0])?se(m):"auto";if(u+=16){var g=se((x(),O)[u+4>>>2>>>0]),b=(x(),O)[u+16>>>2>>>0],E=(x(),O)[u+20>>>2>>>0];if(b){for(var F={},N=0;N<b;++N){var j=E+24*N;F[uw(j+4)]=(x(),W)[j+16>>>3>>>0]}b=F}else b=void 0;u={module:g,constants:b,entryPoint:Mr(u+8)}}else u=void 0;return{label:f,layout:m,compute:u}},dw=(u,f)=>{function m(g,b){g=u[g],(x(),O)[f+b>>>2>>>0]=g}m("maxTextureDimension1D",4),m("maxTextureDimension2D",8),m("maxTextureDimension3D",12),m("maxTextureArrayLayers",16),m("maxBindGroups",20),m("maxBindGroupsPlusVertexBuffers",24),m("maxBindingsPerBindGroup",28),m("maxDynamicUniformBuffersPerPipelineLayout",32),m("maxDynamicStorageBuffersPerPipelineLayout",36),m("maxSampledTexturesPerShaderStage",40),m("maxSamplersPerShaderStage",44),m("maxStorageBuffersPerShaderStage",48),m("maxStorageTexturesPerShaderStage",52),m("maxUniformBuffersPerShaderStage",56),m("minUniformBufferOffsetAlignment",80),m("minStorageBufferOffsetAlignment",84),sd(f+64,u.maxUniformBufferBindingSize),sd(f+72,u.maxStorageBufferBindingSize),m("maxVertexBuffers",88),sd(f+96,u.maxBufferSize),m("maxVertexAttributes",104),m("maxVertexBufferArrayStride",108),m("maxInterStageShaderVariables",112),m("maxColorAttachments",116),m("maxColorAttachmentBytesPerSample",120),m("maxComputeWorkgroupStorageSize",124),m("maxComputeInvocationsPerWorkgroup",128),m("maxComputeWorkgroupSizeX",132),m("maxComputeWorkgroupSizeY",136),m("maxComputeWorkgroupSizeZ",140),m("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&m("maxImmediateSize",148)},NN=[,"validation","out-of-memory","internal"],DN=[,"compatibility","core"],hw={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"},zN=[,"low-power","high-performance"],BN=[,"occlusion","timestamp"],RN={undefined:1,unknown:1,destroyed:2};function GN(u,f,m,g,b,E){f=ot(f),m=ot(m),g>>>=0,b>>>=0,E>>>=0;var F=se(u>>>0);if(u={},E){var N=(x(),O)[E+12>>>2>>>0];if(N){var j=(x(),O)[E+16>>>2>>>0];u.requiredFeatures=Array.from((x(),O).subarray(j>>>2>>>0,j+4*N>>>2>>>0),K=>hw[K])}var Y=(x(),O)[E+20>>>2>>>0];if(Y){let K=function(Le,tt,Bn=!1){tt=Y+tt,(tt=(x(),O)[tt>>>2>>>0])==4294967295||Bn&&tt==0||(ye[Le]=tt)},_e=function(Le,tt){tt=Y+tt;var Bn=(x(),O)[tt>>>2>>>0],wd=(x(),O)[tt+4>>>2>>>0];Bn==4294967295&&wd==4294967295||(ye[Le]=Nn(tt))};var ye={};K("maxTextureDimension1D",4),K("maxTextureDimension2D",8),K("maxTextureDimension3D",12),K("maxTextureArrayLayers",16),K("maxBindGroups",20),K("maxBindGroupsPlusVertexBuffers",24),K("maxDynamicUniformBuffersPerPipelineLayout",32),K("maxDynamicStorageBuffersPerPipelineLayout",36),K("maxSampledTexturesPerShaderStage",40),K("maxSamplersPerShaderStage",44),K("maxStorageBuffersPerShaderStage",48),K("maxStorageTexturesPerShaderStage",52),K("maxUniformBuffersPerShaderStage",56),K("minUniformBufferOffsetAlignment",80),K("minStorageBufferOffsetAlignment",84),_e("maxUniformBufferBindingSize",64),_e("maxStorageBufferBindingSize",72),K("maxVertexBuffers",88),_e("maxBufferSize",96),K("maxVertexAttributes",104),K("maxVertexBufferArrayStride",108),K("maxInterStageShaderVariables",112),K("maxColorAttachments",116),K("maxColorAttachmentBytesPerSample",120),K("maxComputeWorkgroupStorageSize",124),K("maxComputeInvocationsPerWorkgroup",128),K("maxComputeWorkgroupSizeX",132),K("maxComputeWorkgroupSizeY",136),K("maxComputeWorkgroupSizeZ",140),K("maxComputeWorkgroupsPerDimension",144),K("maxImmediateSize",148,!0),u.requiredLimits=ye}(N=(x(),O)[E+24>>>2>>>0])&&(N={label:Mr(N+4)},u.defaultQueue=N),u.label=Mr(E+4)}Me+=1,Rs(f,F.requestDevice(u).then(K=>{--Me,gt(()=>{it[b>>>0]=K.queue,it[g>>>0]=K,Me+=1,Rs(m,K.lost.then(_e=>{gt(()=>{K.onuncapturederror=()=>{};var Le=oe(),tt=ir(_e.message);ld(m,RN[_e.reason],tt),ae(Le)}),--Me})),K.onuncapturederror=_e=>{var Le=5;_e.error instanceof GPUValidationError?Le=2:_e.error instanceof GPUOutOfMemoryError?Le=3:_e.error instanceof GPUInternalError&&(Le=4);var tt=oe();_e=ir(_e.error.message),Iw(g,Le,_e),ae(tt)},"adapterInfo"in K||(K.adapterInfo=F.info),dd(f,1,g,0)})},K=>{--Me,gt(()=>{var _e=oe(),Le=ir(K.message);dd(f,3,g,Le),m&&ld(m,4,Le),ae(_e)})}))}function $N(u){var f=se(u>>>=0),m=br[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete br[u]}f.destroy()}function VN(u,f,m){m>>>=0;var g=se(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=_d(16,b.byteLength);return(x(),$).set(new Uint8Array(b),E>>>0),br[u].push(()=>Xt(E)),E}function UN(u,f,m){m>>>=0;var g=se(u>>>=0);m==4294967295&&(m=void 0);try{var b=g.getMappedRange(f>>>0,m)}catch{return 0}var E=_d(16,b.byteLength);return(x(),$).fill(0,E,b.byteLength),br[u].push(()=>{new Uint8Array(b).set((x(),$).subarray(E>>>0,E+b.byteLength>>>0)),Xt(E)}),E}function jN(u,f,m,g,b){u>>>=0,f=ot(f),m=ot(m),b>>>=0;var E=se(u);br[u]=[],b==4294967295&&(b=void 0),Me+=1,Rs(f,E.mapAsync(m,g>>>0,b).then(()=>{--Me,gt(()=>{cd(f,1,0)})},F=>{--Me,gt(()=>{oe();var N=ir(F.message);cd(f,F.name==="AbortError"?4:F.name==="OperationError"?3:0,N),delete br[u]})}))}function qN(u){var f=se(u>>>=0),m=br[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete br[u],f.unmap()}}function WN(u){delete it[u>>>0]}function HN(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=!!(x(),O)[f+32>>>2>>>0];f={label:Mr(f+4),usage:(x(),O)[f+16>>>2>>>0],size:Nn(f+24),mappedAtCreation:g},u=se(u);try{var b=u.createBuffer(f)}catch{return!1}return it[m>>>0]=b,g&&(br[m]=[]),!0}function QN(u,f,m,g){u>>>=0,f=ot(f),g>>>=0,m=ON(m>>>0),u=se(u),Me+=1,Rs(f,u.createComputePipelineAsync(m).then(b=>{--Me,gt(()=>{it[g>>>0]=b,id(f,1,g,0)})},b=>{--Me,gt(()=>{var E=oe(),F=ir(b.message);id(f,b.reason==="validation"?3:b.reason==="internal"?4:0,g,F),ae(E)})}))}function XN(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=(x(),O)[f>>>2>>>0],b=(x(),D)[g+4>>>2>>>0];f={label:Mr(f+4),code:""},b===2&&(f.code=uw(g+8)),u=se(u).createShaderModule(f),it[m>>>0]=u}var YN=u=>{(u=se(u)).onuncapturederror=null,u.destroy()};function JN(u,f){f=ot(f),u=se(u>>>0),Me+=1,Rs(f,u.popErrorScope().then(m=>{--Me,gt(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var b=oe(),E=m?ir(m.message):0;ud(f,1,g,E),ae(b)})},m=>{--Me,gt(()=>{var g=oe(),b=ir(m.message);ud(f,1,5,b),ae(g)})}))}function KN(u,f,m,g){if(f=ot(f),g>>>=0,m>>>=0){var b={featureLevel:DN[(x(),D)[m+4>>>2>>>0]],powerPreference:zN[(x(),D)[m+8>>>2>>>0]],forceFallbackAdapter:!!(x(),O)[m+12>>>2>>>0]};(u=(x(),O)[m>>>2>>>0])!==0&&(x(),b.De=!!(x(),O)[u+8>>>2>>>0])}"gpu"in navigator?(Me+=1,Rs(f,navigator.gpu.requestAdapter(b).then(E=>{--Me,gt(()=>{if(E)it[g>>>0]=E,Dn(f,1,g,0);else{var F=oe(),N=ir("WebGPU not available on this browser (requestAdapter returned null)");Dn(f,3,g,N),ae(F)}})},E=>{--Me,gt(()=>{var F=oe(),N=ir(E.message);Dn(f,4,g,N),ae(F)})}))):(b=oe(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),Dn(f,3,g,u),ae(b))}function ZN(u,f,m){return u>>>=0,f>>>=0,m>>>=0,tw(async()=>{var g=[];if(m){var b=(x(),D)[m>>>2>>>0];g.length=f+1,g[f]=new Promise(N=>setTimeout(N,b,0))}else g.length=f;for(var E=0;E<f;++E){var F=Nn(u+8*E);if(!(F in po))return F;g[E]=po[F]}return g=await Promise.race(g),delete po[g],g})}var nd,ad={},fw=()=>{var g;if(!nd){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(((g=globalThis.navigator)==null?void 0:g.language)??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in ad)ad[u]===void 0?delete f[u]:f[u]=ad[u];var m=[];for(u in f)m.push(`${u}=${f[u]}`);nd=m}return nd};function _w(u,f){if(n)return ce(19,1,u,f);u>>>=0,f>>>=0;var m,g=0,b=0;for(m of fw()){var E=f+g;(x(),O)[u+b>>>2>>>0]=E,g+=vr(m,E,1/0)+1,b+=4}return 0}function pw(u,f){if(n)return ce(20,1,u,f);u>>>=0,f>>>=0;var m=fw();for(var g of((x(),O)[u>>>2>>>0]=m.length,u=0,m))u+=yr(g)+1;return(x(),O)[f>>>2>>>0]=u,0}function mw(u){return n?ce(21,1,u):52}function gw(u,f,m,g){return n?ce(22,1,u,f,m,g):52}function ww(u,f,m,g){return n?ce(23,1,u,f,m,g):70}var e3=[null,[],[]];function vw(u,f,m,g){if(n)return ce(24,1,u,f,m,g);f>>>=0,m>>>=0,g>>>=0;for(var b=0,E=0;E<m;E++){var F=(x(),O)[f>>>2>>>0],N=(x(),O)[f+4>>>2>>>0];f+=8;for(var j=0;j<N;j++){var Y=u,ye=(x(),$)[F+j>>>0],K=e3[Y];ye===0||ye===10?((Y===1?A:S)(Ng(K)),K.length=0):K.push(ye)}b+=N}return(x(),O)[g>>>2>>>0]=b,0}function t3(u){return u>>>0}function r3(u,f){return dw(se(u>>>0).limits,f>>>0),1}function s3(u,f){return se(u>>>0).features.has(hw[f])}function n3(u){return BigInt(se(u>>>0).size)}function a3(u){return BigInt(se(u>>>0).usage)}function o3(u,f){if(u>>>=0,f>>>=0){var m=Mr(f+4);m={label:m,timestampWrites:f=(f=(x(),O)[f+12>>>2>>>0])!==0?{querySet:se((x(),O)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(x(),O)[f+8>>>2>>>0],endOfPassWriteIndex:(x(),O)[f+12>>>2>>>0]}:void 0}}return f=se(u),u=Cw(0),m=f.beginComputePass(m),it[u>>>0]=m,u}function i3(u,f,m,g){m=ot(m),(g=ot(g))==-1&&(g=void 0),(u=se(u>>>0)).clearBuffer(se(f>>>0),m,g)}function l3(u,f,m,g,b,E){m=ot(m),b=ot(b),E=ot(E),se(u>>>0).copyBufferToBuffer(se(f>>>0),m,se(g>>>0),b,E)}function c3(u){var f=se(u>>>0);return u=Ew(0),f=f.finish(),it[u>>>0]=f,u}function u3(u,f,m,g,b,E){E=ot(E),se(u>>>0).resolveQuerySet(se(f>>>0),m,g,se(b>>>0),E)}function d3(u,f,m,g){se(u>>>0).dispatchWorkgroups(f,m,g)}function h3(u,f,m){m=ot(m),se(u>>>0).dispatchWorkgroupsIndirect(se(f>>>0),m)}function f3(u){se(u>>>0).end()}function _3(u,f,m,g,b){g>>>=0,b>>>=0,u=se(u>>>0),m=se(m>>>0),g==0?u.setBindGroup(f,m):u.setBindGroup(f,m,(x(),O),b>>>2,g)}function p3(u,f){se(u>>>0).setPipeline(se(f>>>0))}function m3(u,f,m){se(u>>>0).Ce(se(f>>>0),m)}function g3(u,f){var m=se(u>>>0);return u=Tw(0),f=m.getBindGroupLayout(f),it[u>>>0]=f,u}function w3(u,f){function m(b){var E=(x(),O)[b+8>>>2>>>0],F=(x(),O)[b+32>>>2>>>0],N=(x(),O)[b+36>>>2>>>0],j=0;return IN(b,{327681:Y=>{j=(x(),O)[Y+8>>>2>>>0]}}),E?((F=Nn(b+24))==-1&&(F=void 0),E={buffer:se(E),offset:Nn(b+16),size:F}):E=se(F||N||j),{binding:(x(),O)[b+4>>>2>>>0],resource:E}}u>>>=0,f={label:Mr(4+(f>>>=0)),layout:se((x(),O)[f+12>>>2>>>0]),entries:(function(b,E){for(var F=[],N=0;N<b;++N)F.push(m(E+40*N));return F})((x(),O)[f+16>>>2>>>0],(x(),O)[f+20>>>2>>>0])},u=se(u);var g=kw(0);return LN(g,u.createBindGroup(f)),g}function v3(u,f){var m;return u>>>=0,(f>>>=0)&&(m={label:Mr(f+4)}),f=se(u),u=Aw(0),m=f.createCommandEncoder(m),it[u>>>0]=m,u}function y3(u,f){u>>>=0,f>>>=0,f={type:BN[(x(),D)[f+12>>>2>>>0]],count:(x(),O)[f+16>>>2>>>0]};var m=se(u);return u=Sw(0),f=m.createQuerySet(f),it[u>>>0]=f,u}function b3(u,f){u=se(u>>>0).adapterInfo,f>>>=0,(x(),O)[f+52>>>2>>>0]=u.subgroupMinSize,(x(),O)[f+56>>>2>>>0]=u.subgroupMaxSize;var m=u.vendor+u.architecture+u.device+u.description,g=yr(m)+1,b=Gs(g);return b&&vr(m,b,g),m=b,g=yr(u.vendor),mo(f+4,m,g),m+=g,g=yr(u.architecture),mo(f+12,m,g),m+=g,g=yr(u.device),mo(f+20,m,g),mo(f+28,m+g,yr(u.description)),(x(),D)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(x(),D)[f+40>>>2>>>0]=u,(x(),O)[f+44>>>2>>>0]=0,(x(),O)[f+48>>>2>>>0]=0,1}var M3={"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 x3(u,f){f>>>=0;var m=se(u>>>0);u=Gs(4*m.features.size);var g=0,b=0;for(let E of m.features)0<=(m=M3[E])&&((x(),D)[u+g>>>2>>>0]=m,g+=4,b++);(x(),O)[f+4>>>2>>>0]=u,(x(),O)[f>>>2>>>0]=b}function k3(u,f){return dw(se(u>>>0).limits,f>>>0),1}function T3(u,f){se(u>>>0).pushErrorScope(NN[f])}function E3(u,f,m){f>>>=0,m>>>=0,u=se(u>>>0),f=Array.from((x(),D).subarray(m>>>2>>>0,m+4*f>>>2>>>0),g=>se(g)),u.submit(f)}function A3(u,f,m,g,b){m=ot(m),g>>>=0,b>>>=0,u=se(u>>>0),f=se(f>>>0),g=(x(),$).subarray(g>>>0,g+b>>>0),u.writeBuffer(f,m,g,0,b)}n||(function(){for(var u=t.numThreads-1;u--;)Cg();It.push(async()=>{var f=(async function(){if(!n)return Promise.all(Nt.map(Ag))})();Ot++,await f,--Ot==0&&Qe&&(f=Qe,Qe=null,f())})})(),n||(Dr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),X()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>oe(),t.stackRestore=u=>ae(u),t.stackAlloc=u=>wo(u),t.setValue=function(u,f,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":(x(),z)[u>>>0]=f;break;case"i16":(x(),Q)[u>>>1>>>0]=f;break;case"i32":(x(),D)[u>>>2>>>0]=f;break;case"i64":(x(),ee)[u>>>3>>>0]=BigInt(f);break;case"float":(x(),te)[u>>>2>>>0]=f;break;case"double":(x(),W)[u>>>3>>>0]=f;break;case"*":(x(),O)[u>>>2>>>0]=f;break;default:we(`invalid type for setValue: ${m}`)}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(x(),z)[u>>>0];case"i16":return(x(),Q)[u>>>1>>>0];case"i32":return(x(),D)[u>>>2>>>0];case"i64":return(x(),ee)[u>>>3>>>0];case"float":return(x(),te)[u>>>2>>>0];case"double":return(x(),W)[u>>>3>>>0];case"*":return(x(),O)[u>>>2>>>0];default:we(`invalid type for getValue: ${f}`)}},t.UTF8ToString=zs,t.stringToUTF8=vr,t.lengthBytesUTF8=yr;var yw,bw,od,go,Xt,Gs,Mw,xw,kw,Tw,Ew,Aw,Cw,Sw,Pw,Fw,Lw,id,ld,cd,ud,Dn,dd,Iw,hd,Ow,Nw,Dw,fd,zw,Bw,_d,pe,zn,Rw,ae,wo,oe,Gw,pd,$w,Vw,Uw,md,jw,qw,Ww,Hw,Qw,Xw,Yw,Jw,Kw,Zw,ev,tv,rv,sv,nv,av,ov,iv,lv,cv,uv,dv,hv,fv,_v,pv,mv,gv,wv,vv,yv,bv,Mv,xv,kv,Tv,Ev,Av,xr,C3=[Pe,mt,Fg,Dg,zg,Bg,Rg,Gg,$g,Vg,Ug,jg,qg,Wg,Hg,Qg,ow,iw,lw,_w,pw,mw,gw,ww,vw],gd={970348:(u,f,m,g,b)=>{if(t===void 0||!t.Uc)return 1;if((u=zs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.get(u)))return 2;if(f=Number(f>>>0),m=Number(m>>>0),g=Number(g>>>0),f+m>u.byteLength)return 3;try{let E=u.subarray(f,f+m);switch(b){case 0:(x(),$).set(E,g>>>0);break;case 1:t.ad?t.ad(g,E):t.ne(g,E);break;default:return 4}return 0}catch{return 4}},971172:(u,f,m)=>{t.Sd(u,(x(),$).subarray(f>>>0,f+m>>>0))},971236:()=>t.le(),971278:u=>{t.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function S3(u,f,m,g){var b=oe();try{return Jw(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function P3(u,f,m){var g=oe();try{return Qw(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;pe(1,0)}}function F3(u){var f=oe();try{jw(u)}catch(m){if(ae(f),m!==m+0)throw m;pe(1,0)}}function L3(u,f){var m=oe();try{return md(u,f)}catch(g){if(ae(m),g!==g+0)throw g;pe(1,0)}}function I3(u,f,m){var g=oe();try{Uw(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;pe(1,0)}}function O3(u,f){var m=oe();try{Kw(u,f)}catch(g){if(ae(m),g!==g+0)throw g;pe(1,0)}}function N3(u,f,m,g,b,E,F){var N=oe();try{return Hw(u,f,m,g,b,E,F)}catch(j){if(ae(N),j!==j+0)throw j;pe(1,0)}}function D3(u,f,m,g,b,E){var F=oe();try{qw(u,f,m,g,b,E)}catch(N){if(ae(F),N!==N+0)throw N;pe(1,0)}}function z3(u,f,m,g){var b=oe();try{Yw(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function B3(u,f,m,g,b,E,F){var N=oe();try{ev(u,f,m,g,b,E,F)}catch(j){if(ae(N),j!==j+0)throw j;pe(1,0)}}function R3(u,f,m,g,b,E,F){var N=oe();try{tv(u,f,m,g,b,E,F)}catch(j){if(ae(N),j!==j+0)throw j;pe(1,0)}}function G3(u,f,m,g,b,E,F,N){var j=oe();try{uv(u,f,m,g,b,E,F,N)}catch(Y){if(ae(j),Y!==Y+0)throw Y;pe(1,0)}}function $3(u,f,m,g,b,E,F,N,j,Y,ye,K){var _e=oe();try{rv(u,f,m,g,b,E,F,N,j,Y,ye,K)}catch(Le){if(ae(_e),Le!==Le+0)throw Le;pe(1,0)}}function V3(u,f,m,g,b){var E=oe();try{return Zw(u,f,m,g,b)}catch(F){if(ae(E),F!==F+0)throw F;pe(1,0)}}function U3(u,f,m,g,b){var E=oe();try{Ww(u,f,m,g,b)}catch(F){if(ae(E),F!==F+0)throw F;pe(1,0)}}function j3(u,f,m,g,b,E,F,N){var j=oe();try{Xw(u,f,m,g,b,E,F,N)}catch(Y){if(ae(j),Y!==Y+0)throw Y;pe(1,0)}}function q3(u){var f=oe();try{return dv(u)}catch(m){if(ae(f),m!==m+0)throw m;pe(1,0)}}function W3(u,f,m){var g=oe();try{return hv(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;pe(1,0)}}function H3(u,f){var m=oe();try{return xv(u,f)}catch(g){if(ae(m),g!==g+0)throw g;return pe(1,0),0n}}function Q3(u){var f=oe();try{return sv(u)}catch(m){if(ae(f),m!==m+0)throw m;return pe(1,0),0n}}function X3(u,f,m,g){var b=oe();try{return fv(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function Y3(u,f,m,g,b){var E=oe();try{return _v(u,f,m,g,b)}catch(F){if(ae(E),F!==F+0)throw F;pe(1,0)}}function J3(u,f,m,g,b,E){var F=oe();try{return pv(u,f,m,g,b,E)}catch(N){if(ae(F),N!==N+0)throw N;pe(1,0)}}function K3(u,f,m,g,b,E){var F=oe();try{return lv(u,f,m,g,b,E)}catch(N){if(ae(F),N!==N+0)throw N;pe(1,0)}}function Z3(u,f,m,g,b,E){var F=oe();try{return mv(u,f,m,g,b,E)}catch(N){if(ae(F),N!==N+0)throw N;pe(1,0)}}function eD(u,f,m,g,b,E,F,N){var j=oe();try{return cv(u,f,m,g,b,E,F,N)}catch(Y){if(ae(j),Y!==Y+0)throw Y;pe(1,0)}}function tD(u,f,m,g,b){var E=oe();try{return gv(u,f,m,g,b)}catch(F){if(ae(E),F!==F+0)throw F;return pe(1,0),0n}}function rD(u,f,m,g){var b=oe();try{return wv(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function sD(u,f,m,g){var b=oe();try{return vv(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function nD(u,f,m,g,b,E,F,N,j,Y,ye,K){var _e=oe();try{return yv(u,f,m,g,b,E,F,N,j,Y,ye,K)}catch(Le){if(ae(_e),Le!==Le+0)throw Le;pe(1,0)}}function aD(u,f,m,g,b,E,F,N,j,Y,ye){var K=oe();try{bv(u,f,m,g,b,E,F,N,j,Y,ye)}catch(_e){if(ae(K),_e!==_e+0)throw _e;pe(1,0)}}function oD(u,f,m,g,b,E,F,N,j,Y,ye,K,_e,Le,tt,Bn){var wd=oe();try{Mv(u,f,m,g,b,E,F,N,j,Y,ye,K,_e,Le,tt,Bn)}catch(vd){if(ae(wd),vd!==vd+0)throw vd;pe(1,0)}}function iD(u,f,m){var g=oe();try{return av(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;return pe(1,0),0n}}function lD(u,f,m){var g=oe();try{return nv(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;pe(1,0)}}function cD(u,f,m){var g=oe();try{return ov(u,f,m)}catch(b){if(ae(g),b!==b+0)throw b;pe(1,0)}}function uD(u,f,m,g){var b=oe();try{iv(u,f,m,g)}catch(E){if(ae(b),E!==E+0)throw E;pe(1,0)}}function vo(){if(0<Ot)Qe=vo;else if(n)w==null||w(t),J();else{for(var u=It;0<u.length;)u.shift()(t);0<Ot?Qe=vo:(t.calledRun=!0,C||(J(),w==null||w(t)))}}return n||(xr=await Fe(),vo()),t.PTR_SIZE=4,t.webgpuInit=u=>{let f=new WeakMap,m,g,b=1;t.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var j=f.get(N);if(!j){let Y=((ye,K=0)=>{var _e=Lw(K);return K=Fw(K,_e),it[_e>>>0]=ye.queue,it[K>>>0]=ye,K})(N,j=xw(0));j=[b++,j,Y],f.set(N,j)}return m=N,g=j[0],j}m=void 0,g=0};let E=new Map;t.webgpuOnCreateSession=N=>{if(g!==void 0){var j=g;if(g=void 0,N){let Y=od(j);E.set(N,Y),j===0&&u(m??se(Y))}m=void 0}},t.webgpuOnReleaseSession=N=>{E.delete(N)};let F=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(N,j,Y)=>{if(Y)return N[F]=[Y,NaN],Y;if(Y=N[F])return Y[1]++,Y[0];if((j=E.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((ye,K=0)=>(ye.mapState==="unmapped"||we(),K=Pw(K),it[K>>>0]=ye,K))(N,j),N[F]=[j,1],j},t.webgpuUnregisterBuffer=N=>{let j=N[F];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(Mw(j[0]),delete N[F])},t.webgpuGetBuffer=N=>se(N),t.webgpuCreateDownloader=(N,j,Y)=>{if((Y=E.get(Y))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ye=se(Y),K=16*Math.ceil(Number(j)/16);return async()=>{let _e=ye.createBuffer({size:K,usage:9});try{let Le=ye.createCommandEncoder();return Le.copyBufferToBuffer(N,0,_e,0,K),ye.queue.submit([Le.finish()]),await _e.mapAsync(GPUMapMode.READ),_e.getMappedRange().slice(0,j)}finally{_e.destroy()}}},t.ad=(N,j)=>{var Y=j.buffer;let ye=j.byteOffset,K=j.byteLength;if(j=16*Math.ceil(Number(K)/16),N=se(N),!m){var _e=od(g);m=se(_e)}let Le=(_e=m.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(Le).set(new Uint8Array(Y,ye,K)),_e.unmap(),(Y=m.createCommandEncoder()).copyBufferToBuffer(_e,0,N,0,j),m.queue.submit([Y.finish()]),_e.destroy()}},t.webnnInit=u=>{let f=u[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=m=>f.onRunStart(m),t.webnnOnRunEnd=f.onRunEnd.bind(f),t.webnnOnReleaseSession=m=>{f.onReleaseSession(m)},t.webnnCreateMLTensorDownloader=(m,g)=>f.createMLTensorDownloader(m,g),t.webnnRegisterMLTensor=(m,g,b,E)=>f.registerMLTensor(m,g,b,E),t.webnnCreateMLContext=m=>f.createMLContext(m),t.webnnRegisterMLConstant=(m,g,b,E,F,N)=>f.registerMLConstant(m,g,b,E,F,t.Uc,N),t.webnnRegisterGraphInput=f.registerGraphInput.bind(f),t.webnnIsGraphInput=f.isGraphInput.bind(f),t.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),t.webnnIsGraphOutput=f.isGraphOutput.bind(f),t.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),t.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f)},V?t:new Promise((u,f)=>{w=u,v=f})}var jd,qd,Zv=me(()=>{var e,t;jd=Ud,qd=(t=(e=globalThis.self)==null?void 0:e.name)==null?void 0:t.startsWith("em-pthread"),qd&&Ud()}),Po,Fo,Wd,xt,Hd,Un,Qd,Xd,Lo,Yd,Io,Jd,Oo,Kd,No=me(()=>{Ao(),Po=typeof location>"u"?void 0:location.origin,Fo=self.location.href>"file:"&&self.location.href<"file;",Wd=()=>{{if(Fo){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",self.location.href).href,Po).href}return self.location.href}},xt=Wd(),Hd=()=>{if(xt&&!xt.startsWith("blob:"))return xt.substring(0,xt.lastIndexOf("/")+1)},Un=(e,t)=>{try{let r=t??xt;return(r?new URL(e,r):new URL(e)).origin===Po}catch{return!1}},Qd=(e,t)=>{let r=t??xt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Xd=(e,t)=>`${t??"./"}${e}`,Lo=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Yd=async e=>(await import(e)).default,Io=(Kv(),Gn(Gd)).default,Jd=async()=>{if(!xt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Un(xt))return[void 0,Io()];let e=await Lo(xt);return[e,Io(e)]},Oo=(Zv(),Gn(Vd)).default,Kd=async(e,t,r,s)=>{let n=Oo&&!(e||t);if(n)if(xt)n=Un(xt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Oo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Qd(a,t),i=r&&o&&!Un(o,t),l=i?await Lo(o):o??Xd(a,t);return[i?l:void 0,await Yd(l)]}}}),Do,jn,js,zo,Zd,eh,th,Bo,Se,Ur=me(()=>{No(),jn=!1,js=!1,zo=!1,Zd=()=>{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}},eh=()=>{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}},th=()=>{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}},Bo=async e=>{if(jn)return Promise.resolve();if(js)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zo)throw new Error("previous call to 'initializeWebAssembly()' failed.");js=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!th())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!eh())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Zd();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let n=e.wasmPaths,a=typeof n=="string"?n:void 0,o=n==null?void 0:n.mjs,i=(o==null?void 0:o.href)??o,l=n==null?void 0:n.wasm,c=(l==null?void 0:l.href)??l,d=e.wasmBinary,[h,_]=await Kd(i,a,r>1,!!d||!!c),p=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{p=!0,v()},t)})),w.push(new Promise((v,y)=>{let M={numThreads:r};if(d)M.wasmBinary=d,M.locateFile=T=>T;else if(c||a)M.locateFile=T=>c??a+T;else if(i&&i.indexOf("blob:")!==0)M.locateFile=T=>new URL(T,i).href;else if(h){let T=Hd();T&&(M.locateFile=A=>T+A)}_(M).then(T=>{js=!1,jn=!0,Do=T,v(),h&&URL.revokeObjectURL(h)},T=>{js=!1,zo=!0,y(T)})})),await Promise.race(w),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Se=()=>{if(jn&&Do)return Do;throw new Error("WebAssembly is not initialized yet.")}}),kt,qn,ke,Ro=me(()=>{Ur(),kt=(e,t)=>{let r=Se(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},qn=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,a])=>{let o=t?t+n:n;if(typeof a=="object")qn(a,o+".",r,s);else if(typeof a=="string"||typeof a=="number")s(o,a.toString());else if(typeof a=="boolean")s(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ke=e=>{let t=Se(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetLastError(n,n+s);let a=Number(t.getValue(n,s===4?"i32":"i64")),o=t.getValue(n+s,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),rh,ey=me(()=>{Ur(),Ro(),rh=e=>{let t=Se(),r=0,s=[],n=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(n.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=kt(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,a),r===0&&ke("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&qn(e.extra,"",new WeakSet,(o,i)=>{let l=kt(o,s),c=kt(i,s);t._OrtAddRunConfigEntry(r,l,c)!==0&&ke(`Can't set a run config entry: ${o} - ${i}.`)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),a}}}),sh,nh,ah,Wn,Ar,oh,ih,ty=me(()=>{Ur(),Ro(),sh=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},nh=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ah=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Wn=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);Se()._OrtAddSessionConfigEntry(e,n,a)!==0&&ke(`Can't set a session config entry: ${t} - ${r}.`)},Ar=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);e.push([n,a])},oh=async(e,t,r)=>{let s=t.executionProviders;for(let n of s){let a=typeof n=="string"?n:n.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof n!="string"){let h=n==null?void 0:n.deviceType;h&&Wn(e,"deviceType",h,r)}break;case"webgpu":{a="WebGPU";let h;if(typeof n!="string"){let p=n;if(p.device)if(typeof GPUDevice<"u"&&p.device instanceof GPUDevice)h=p.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&Ar(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&Ar(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let v=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];Ar(o,"forceCpuNodeNames",v.join(`
8
+ `),r)}p.validationMode&&Ar(o,"validationMode",p.validationMode,r)}let _=Se().webgpuRegisterDevice(h);if(_){let[p,w,v]=_;Ar(o,"deviceId",p.toString(),r),Ar(o,"webgpuInstance",w.toString(),r),Ar(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=kt(a,r),l=o.length,c=0,d=0;if(l>0){c=Se()._malloc(l*Se().PTR_SIZE),r.push(c),d=Se()._malloc(l*Se().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Se().setValue(c+h*Se().PTR_SIZE,o[h][0],"*"),Se().setValue(d+h*Se().PTR_SIZE,o[h][1],"*")}await Se()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&ke(`Can't append execution provider: ${a}.`)}},ih=async e=>{let t=Se(),r=0,s=[],n=e||{};ah(n);try{let a=sh(n.graphOptimizationLevel??"all"),o=nh(n.executionMode??"sequential"),i=typeof n.logId=="string"?kt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof n.optimizedModelFilePath=="string"?kt(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(a,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,i,l,c,d),r===0&&ke("Can't create session options."),n.executionProviders&&await oh(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Wn(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[h,_]of Object.entries(n.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let p=kt(h,s);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&ke(`Can't set a free dimension override: ${h} - ${_}.`)}return n.extra!==void 0&&qn(n.extra,"",new WeakSet,(h,_)=>{Wn(r,h,_,s)}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&ke("Can't release session options."),s.forEach(o=>t._free(o)),a}}}),jr,Hn,rs,qs,Qn,Go,$o,Vo,ss=me(()=>{jr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Hn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},rs=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof t=="number"?t:t.reduce((n,a)=>n*a,1);return r>0?Math.ceil(s*r):void 0},qs=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Qn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Go=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",$o=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Uo,lh=me(()=>{Ao(),Uo=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),a;try{a=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),ch,ry=me(()=>{ss(),ch=(e,t)=>new(qs(t))(e)}),uh,dh,hh,fh,_h,ph,lt,mh=me(()=>{ss(),uh=["V","I","W","E","F"],dh=(e,t)=>{console.log(`[${uh[e]},${new Date().toISOString()}]${t}`)},_h=(e,t)=>{hh=e,fh=t},ph=(e,t)=>{let r=Qn(e),s=Qn(hh);r>=s&&dh(r,typeof t=="function"?t():t)},lt=(...e)=>{fh&&ph(...e)}}),jo,qo,Wo,gh,Ho,wh,Qo,Xo,Yo,vh,yh,sy=me(()=>{ss(),mh(),jo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qo=(e,t)=>{if(t==="int32")return e;let r=jo.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let s=r/8;if(e.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=e.byteLength/s,a=new(qs(t))(e.buffer,e.byteOffset,n);switch(t){case"int64":case"uint64":{let o=new Int32Array(n);for(let i=0;i<n;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Wo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},gh=1,Ho=()=>gh++,wh=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Qo=(e,t)=>{let r=jo.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((s,n)=>s*n)*r/8):0},Xo=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:s,dataType:n,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qo(this.dataType,this.tensorShape)}destroy(){lt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Wo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(e){this.isDataConverted=e}},Yo=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,s){let n=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!(a!=null&&a.input.dataTypes.includes(t))){if(o=wh.get(t),!o||(a==null?void 0:a.input.dataTypes.includes(o)))throw new Error(`WebNN backend does not support data type: ${t}`);lt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Qo(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),s&&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=qo(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else lt("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){var t,r;if(this.activeUpload){let s=(t=this.wrapper)!=null&&t.isDataConverted?Wo(this.activeUpload,(r=this.wrapper)==null?void 0:r.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(s):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s);return}else return s.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},vh=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Ho();return this.tensorTrackersById.set(e,new Yo(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,s,n){lt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,s,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){lt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,s){let n=this.getMLContext(e),a=Ho(),o=new Xo({sessionId:e,context:n,tensor:t,dataType:r,shape:s});return this.tensorTrackersById.set(a,new Yo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,s,n,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){lt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(c,1)[0];return h.sessionId=e,h}lt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:s,writable:n,readable:a});return new Xo({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},yh=(...e)=>new vh(...e)}),bh={};$s(bh,{WebNNBackend:()=>xh});var Ws,Mh,xh,ny=me(()=>{ss(),Ur(),ry(),sy(),mh(),Ws=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Mh=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),s=Object.keys(t).sort();return r.length===s.length&&r.every((n,a)=>n===s[a]&&e[n]===t[n])},xh=class{constructor(e){this.tensorManager=yh(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,_h(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){lt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){lt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)lt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let t=this.mlContextCache.findIndex(r=>Mh(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let s=this.mlContextCache.findIndex(n=>n.mlContext===t);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){lt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s,n){let a=Ws.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,s,n)}async createTemporaryTensor(e,t,r){lt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let s=Ws.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!Se().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");lt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return ch(r,t)}}registerMLTensor(e,t,r,s){let n=Ws.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,n,s);return lt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,s,n,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(t,t+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(c);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":d=new Int32Array(c);break;case"uint32":d=new Uint32Array(c);break;case"int64":if(o){let h=qo(new Uint8Array(c),"int64");d=new Int32Array(h.buffer),n.dataType="int32"}else d=new BigInt64Array(c);break;case"uint64":d=new BigUint64Array(c);break;case"int8":d=new Int8Array(c);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return lt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let s=Ws.get(jr(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?!1:r?!!(n!=null&&n.input.dataTypes.includes(s)):!!(n!=null&&n.output.dataTypes.includes(s))}flush(){}}}),kh,Jo,Ko,Cr,Th,Zo,Xn,ei,ti,ri,si,ni,ai,Eh=me(()=>{Vr(),ey(),ty(),ss(),Ur(),Ro(),lh(),kh=(e,t)=>{Se()._OrtInit(e,t)!==0&&ke("Can't initialize onnxruntime.")},Jo=async e=>{kh(e.wasm.numThreads,Qn(e.logLevel))},Ko=async(e,t)=>{var s,n;(n=(s=Se()).asyncInit)==null||n.call(s);let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=e.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:o}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Se().webgpuInit(a=>{e.webgpu.device=a}),t==="webnn"){let a=new(ny(),Gn(bh)).WebNNBackend(e);Se().webnnInit([a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,i,l,c,d)=>a.ensureTensor(o,i,l,c,d),(o,i)=>{a.uploadTensor(o,i)},async(o,i)=>a.downloadTensor(o,i),(o,i)=>a.registerMLContext(o,i),!!e.trace])}},Cr=new Map,Th=e=>{let t=Se(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetInputOutputCount(e,n,n+s)!==0&&ke("Can't get session input/output count.");let a=s===4?"i32":"i64";return[Number(t.getValue(n,a)),Number(t.getValue(n+s,a))]}finally{t.stackRestore(r)}},Zo=(e,t)=>{let r=Se(),s=r.stackSave(),n=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&ke("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));n=Number(r.getValue(o+a,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],d=[];for(let h=0;h<c;h++){let _=Number(r.getValue(n+8+h*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(n+8+(h+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},Xn=e=>{let t=Se(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},ei=async(e,t)=>{var h,_,p,w;let r,s,n=Se();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=Xn(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await ih(t),(t==null?void 0:t.externalData)&&n.mountExternalData){let R=[];for(let z of t.externalData){let $=typeof z=="string"?z:z.path;R.push(Uo(typeof z=="string"?z:z.data).then(Q=>{n.mountExternalData($,Q)}))}await Promise.all(R)}for(let R of(t==null?void 0:t.executionProviders)??[])if((typeof R=="string"?R:R.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof R!="string"){let z=R,$=z==null?void 0:z.context,Q=z==null?void 0:z.gpuDevice,H=z==null?void 0:z.deviceType,D=z==null?void 0:z.powerPreference;$?n.currentContext=$:Q?n.currentContext=await n.webnnCreateMLContext(Q):n.currentContext=await n.webnnCreateMLContext({deviceType:H,powerPreference:D})}else n.currentContext=await n.webnnCreateMLContext();break}a=await n._OrtCreateSession(r,s,o),(h=n.webgpuOnCreateSession)==null||h.call(n,a),a===0&&ke("Can't create a session."),(_=n.jsepOnCreateSession)==null||_.call(n),n.currentContext&&(n.webnnRegisterMLContext(a,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[v,y]=Th(a),M=!!(t!=null&&t.enableGraphCapture),T=[],A=[],S=[],C=[],I=[];for(let R=0;R<v;R++){let[z,$,Q]=Zo(a,R);z===0&&ke("Can't get an input name."),c.push(z);let H=n.UTF8ToString(z);T.push(H),S.push($===0?{name:H,isTensor:!1}:{name:H,isTensor:!0,type:Hn($),shape:Q})}for(let R=0;R<y;R++){let[z,$,Q]=Zo(a,R+v);z===0&&ke("Can't get an output name."),d.push(z);let H=n.UTF8ToString(z);A.push(H),C.push($===0?{name:H,isTensor:!1}:{name:H,isTensor:!0,type:Hn($),shape:Q});{if(M&&(t==null?void 0:t.preferredOutputLocation)===void 0){I.push("gpu-buffer");continue}let D=typeof(t==null?void 0:t.preferredOutputLocation)=="string"?t.preferredOutputLocation:((p=t==null?void 0:t.preferredOutputLocation)==null?void 0:p[H])??"cpu",O=n.webnnIsGraphOutput;if(D==="cpu"&&O&&O(a,H)){I.push("ml-tensor-cpu-output");continue}if(D!=="cpu"&&D!=="cpu-pinned"&&D!=="gpu-buffer"&&D!=="ml-tensor")throw new Error(`Not supported preferred output location: ${D}.`);if(M&&D!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);I.push(D)}}let x=null;return I.some(R=>R==="gpu-buffer"||R==="ml-tensor"||R==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(a),i===0&&ke("Can't create IO binding."),x={handle:i,outputPreferredLocations:I,outputPreferredLocationsEncoded:I.map(R=>R==="ml-tensor-cpu-output"?"ml-tensor":R).map(R=>Vo(R))}),Cr.set(a,[a,c,d,x,M,!1]),[a,T,A,S,C]}catch(v){throw c.forEach(y=>n._OrtFree(y)),d.forEach(y=>n._OrtFree(y)),i!==0&&n._OrtReleaseBinding(i)!==0&&ke("Can't release IO binding."),a!==0&&n._OrtReleaseSession(a)!==0&&ke("Can't release session."),v}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&ke("Can't release session options."),l.forEach(v=>n._free(v)),(w=n.unmountExternalData)==null||w.call(n)}},ti=e=>{var l,c,d;let t=Se(),r=Cr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&ke("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ke("Can't release IO binding.")),(l=t.jsepOnReleaseSession)==null||l.call(t,e),(c=t.webnnOnReleaseSession)==null||c.call(t,e),(d=t.webgpuOnReleaseSession)==null||d.call(t,e),n.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(s)!==0&&ke("Can't release session."),Cr.delete(e)},ri=async(e,t,r,s,n,a,o=!1)=>{if(!e){t.push(0);return}let i=Se(),l=i.PTR_SIZE,c=e[0],d=e[1],h=e[3],_=h,p,w;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let M=e[2].gpuBuffer;w=rs(jr(c),d);{let T=i.webgpuRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=T(M,s)}}else if(h==="ml-tensor"){let M=e[2].mlTensor;w=rs(jr(c),d);let T=i.webnnRegisterMLTensor;if(!T)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=T(s,M,jr(c),d)}else{let M=e[2];if(Array.isArray(M)){w=l*M.length,p=i._malloc(w),r.push(p);for(let T=0;T<M.length;T++){if(typeof M[T]!="string")throw new TypeError(`tensor data at index ${T} is not a string`);i.setValue(p+T*l,kt(M[T],r),"*")}}else{let T=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(c!=="string"&&T&&A){let S=i.UTF8ToString(n);if(T(s,S)||A(s,S)){let C=jr(c);w=rs(C,d),_="ml-tensor";let I=i.webnnCreateTemporaryTensor,x=i.webnnUploadTensor;if(!I||!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let R=await I(s,C,d);x(R,new Uint8Array(M.buffer,M.byteOffset,M.byteLength)),p=R}else w=M.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),p)}else w=M.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),p)}}let v=i.stackSave(),y=i.stackAlloc(4*d.length);try{d.forEach((T,A)=>i.setValue(y+A*l,T,l===4?"i32":"i64"));let M=i._OrtCreateTensor(jr(c),p,w,y,d.length,Vo(_));M===0&&ke(`Can't create tensor for input/output. session=${s}, index=${a}.`),t.push(M)}finally{i.stackRestore(v)}},si=async(e,t,r,s,n,a)=>{var H,D,O,te;let o=Se(),i=o.PTR_SIZE,l=Cr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],h=l[2],_=l[3],p=l[4],w=l[5],v=t.length,y=s.length,M=0,T=[],A=[],S=[],C=[],I=[],x=o.stackSave(),R=o.stackAlloc(v*i),z=o.stackAlloc(v*i),$=o.stackAlloc(y*i),Q=o.stackAlloc(y*i);try{[M,T]=rh(a),Tr("wasm prepareInputOutputTensor");for(let L=0;L<v;L++)await ri(r[L],A,C,e,d[t[L]],t[L],p);for(let L=0;L<y;L++)await ri(n[L],S,C,e,h[s[L]],v+s[L],p);Er("wasm prepareInputOutputTensor");for(let L=0;L<v;L++)o.setValue(R+L*i,A[L],"*"),o.setValue(z+L*i,d[t[L]],"*");for(let L=0;L<y;L++)o.setValue($+L*i,S[L],"*"),o.setValue(Q+L*i,h[s[L]],"*");if(_&&!w){let{handle:L,outputPreferredLocations:V,outputPreferredLocationsEncoded:X}=_;if(d.length!==v)throw new Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${d.length}).`);Tr("wasm bindInputsOutputs");for(let J=0;J<v;J++){let we=t[J];await o._OrtBindInput(L,d[we],A[J])!==0&&ke(`Can't bind input[${J}] for session=${e}.`)}for(let J=0;J<y;J++){let we=s[J];(H=n[J])!=null&&H[3]?(I.push(S[J]),o._OrtBindOutput(L,h[we],S[J],0)!==0&&ke(`Can't bind pre-allocated output[${J}] for session=${e}.`)):o._OrtBindOutput(L,h[we],0,X[we])!==0&&ke(`Can't bind output[${J}] to ${V[J]} for session=${e}.`)}Er("wasm bindInputsOutputs"),Cr.set(e,[c,d,h,_,p,!0])}(D=o.jsepOnRunStart)==null||D.call(o,c),(O=o.webnnOnRunStart)==null||O.call(o,c);let W;_?W=await o._OrtRunWithBinding(c,_.handle,y,$,M):W=await o._OrtRun(c,z,R,v,Q,y,$,M),W!==0&&ke("failed to call OrtRun().");let ee=[],G=[];Tr("wasm ProcessOutputTensor");for(let L=0;L<y;L++){let V=Number(o.getValue($+L*i,"*"));if(V===S[L]||I.includes(S[L])){ee.push(n[L]),V!==S[L]&&o._OrtReleaseTensor(V)!==0&&ke("Can't release tensor.");continue}let X=o.stackSave(),J=o.stackAlloc(4*i),we=!1,re,Fe=0;try{o._OrtGetTensorData(V,J,J+i,J+2*i,J+3*i)!==0&&ke(`Can't access output tensor data on index ${L}.`);let qe=i===4?"i32":"i64",bt=Number(o.getValue(J,qe));Fe=o.getValue(J+i,"*");let It=o.getValue(J+i*2,"*"),Ot=Number(o.getValue(J+i*3,qe)),Qe=[];for(let ce=0;ce<Ot;ce++)Qe.push(Number(o.getValue(It+ce*i,qe)));o._OrtFree(It)!==0&&ke("Can't free memory for tensor dims.");let pt=Qe.reduce((ce,Pe)=>ce*Pe,1);re=Hn(bt);let Me=_==null?void 0:_.outputPreferredLocations[s[L]];if(re==="string"){if(Me==="gpu-buffer"||Me==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let Pe=0;Pe<pt;Pe++){let mt=o.getValue(Fe+Pe*i,"*"),nr=o.getValue(Fe+(Pe+1)*i,"*"),Nt=Pe===pt-1?void 0:nr-mt;ce.push(o.UTF8ToString(mt,Nt))}ee.push([re,Qe,ce,"cpu"])}else if(Me==="gpu-buffer"&&pt>0){let ce=o.webgpuGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Pe=ce(Fe),mt=rs(bt,pt);if(mt===void 0||!Go(re))throw new Error(`Unsupported data type: ${re}`);we=!0;{o.webgpuRegisterBuffer(Pe,e,Fe);let nr=o.webgpuCreateDownloader(Pe,mt,e);ee.push([re,Qe,{gpuBuffer:Pe,download:async()=>{let Nt=await nr();return new(qs(re))(Nt)},dispose:()=>{o._OrtReleaseTensor(V)!==0&&ke("Can't release tensor.")}},"gpu-buffer"])}}else if(Me==="ml-tensor"&&pt>0){let ce=o.webnnEnsureTensor,Pe=o.webnnIsGraphInputOutputTypeSupported;if(!ce||!Pe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rs(bt,pt)===void 0||!$o(re))throw new Error(`Unsupported data type: ${re}`);if(!Pe(e,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let mt=await ce(e,Fe,bt,Qe,!1);we=!0,ee.push([re,Qe,{mlTensor:mt,download:o.webnnCreateMLTensorDownloader(Fe,re),dispose:()=>{o.webnnReleaseTensorId(Fe),o._OrtReleaseTensor(V)}},"ml-tensor"])}else if(Me==="ml-tensor-cpu-output"&&pt>0){let ce=o.webnnCreateMLTensorDownloader(Fe,re)(),Pe=ee.length;we=!0,G.push((async()=>{let mt=[Pe,await ce];return o.webnnReleaseTensorId(Fe),o._OrtReleaseTensor(V),mt})()),ee.push([re,Qe,[],"cpu"])}else{let ce=qs(re),Pe=new ce(pt);new Uint8Array(Pe.buffer,Pe.byteOffset,Pe.byteLength).set(o.HEAPU8.subarray(Fe,Fe+Pe.byteLength)),ee.push([re,Qe,Pe,"cpu"])}}finally{o.stackRestore(X),re==="string"&&Fe&&o._free(Fe),we||o._OrtReleaseTensor(V)}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&ke("Can't clear bound outputs."),Cr.set(e,[c,d,h,_,p,!1]));for(let[L,V]of await Promise.all(G))ee[L][2]=V;return Er("wasm ProcessOutputTensor"),ee}finally{(te=o.webnnOnRunEnd)==null||te.call(o,c),o.stackRestore(x),r.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),n.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),A.forEach(W=>o._OrtReleaseTensor(W)),S.forEach(W=>o._OrtReleaseTensor(W)),C.forEach(W=>o._free(W)),M!==0&&o._OrtReleaseRunOptions(M),T.forEach(W=>o._free(W))}},ni=e=>{let t=Se(),r=Cr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&ke("Can't get an profile file name."),t._OrtFree(n)},ai=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),Sr,wt,ns,Hs,Qs,Yn,oi,Jn,qr,Wr,Ah,Ch,Sh,Ph,Fh,Lh,Ih,Oh,Nh=me(()=>{Vr(),Eh(),Ur(),No(),Sr=()=>!!Be.wasm.proxy&&typeof document<"u",ns=!1,Hs=!1,Qs=!1,Jn=new Map,qr=(e,t)=>{let r=Jn.get(e);r?r.push(t):Jn.set(e,[t])},Wr=()=>{if(ns||!Hs||Qs||!wt)throw new Error("worker not ready")},Ah=e=>{switch(e.data.type){case"init-wasm":ns=!1,e.data.err?(Qs=!0,oi[1](e.data.err)):(Hs=!0,oi[0]()),Yn&&(URL.revokeObjectURL(Yn),Yn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Jn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Ch=async()=>{if(!Hs){if(ns)throw new Error("multiple calls to 'initWasm()' detected.");if(Qs)throw new Error("previous call to 'initWasm()' failed.");if(ns=!0,Sr())return new Promise((e,t)=>{wt==null||wt.terminate(),Jd().then(([r,s])=>{try{wt=s,wt.onerror=a=>t(a),wt.onmessage=Ah,oi=[e,t];let n={type:"init-wasm",in:Be};!n.in.wasm.wasmPaths&&(r||Fo)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.asyncify-DMmc6YqF.wasm",self.location.href).href,self.location.href).href}),wt.postMessage(n),Yn=r}catch(n){t(n)}},t)});try{await Bo(Be.wasm),await Jo(Be),Hs=!0}catch(e){throw Qs=!0,e}finally{ns=!1}}},Sh=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:Be}};wt.postMessage(s)});await Ko(Be,e)},Ph=async e=>Sr()?(Wr(),new Promise((t,r)=>{qr("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};wt.postMessage(s,[e.buffer])})):Xn(e),Fh=async(e,t)=>{if(Sr()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wr(),new Promise((r,s)=>{qr("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),wt.postMessage(n,a)})}else return ei(e,t)},Lh=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("release",[t,r]);let s={type:"release",in:e};wt.postMessage(s)});ti(e)},Ih=async(e,t,r,s,n,a)=>{if(Sr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wr(),new Promise((o,i)=>{qr("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:s,options:a}};wt.postMessage(c,ai(l))})}else return si(e,t,r,s,n,a)},Oh=async e=>{if(Sr())return Wr(),new Promise((t,r)=>{qr("end-profiling",[t,r]);let s={type:"end-profiling",in:e};wt.postMessage(s)});ni(e)}}),ii,Dh,zh,ay=me(()=>{Vr(),Nh(),ss(),Ao(),lh(),ii=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Dh=e=>{switch(e[3]){case"cpu":return new zt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Go(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return zt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let t=e[0];if(!$o(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=e[2];return zt.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},zh=class{async fetchModelAndCopyToWasmMemory(e){return Ph(await Uo(e))}async loadModel(e,t){Gr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Fh(r,t),$r()}async dispose(){return Lh(this.sessionId)}async run(e,t,r){Gr();let s=[],n=[];Object.entries(e).forEach(h=>{let _=h[0],p=h[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(p),n.push(w)});let a=[],o=[];Object.entries(t).forEach(h=>{let _=h[0],p=h[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(p),o.push(w)});let i=s.map((h,_)=>ii(h,()=>`input "${this.inputNames[n[_]]}"`)),l=a.map((h,_)=>h?ii(h,()=>`output "${this.outputNames[o[_]]}"`):null),c=await Ih(this.sessionId,n,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??Dh(c[h]);return $r(),d}startProfiling(){}endProfiling(){Oh(this.sessionId)}}}),Bh={};$s(Bh,{OnnxruntimeWebAssemblyBackend:()=>ci,initializeFlags:()=>li,wasmBackend:()=>Rh});var li,ci,Rh,oy=me(()=>{Vr(),Nh(),ay(),li=()=>{(typeof Be.wasm.initTimeout!="number"||Be.wasm.initTimeout<0)&&(Be.wasm.initTimeout=0);let e=Be.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Be.wasm.simd=!1),typeof Be.wasm.proxy!="boolean"&&(Be.wasm.proxy=!1),typeof Be.wasm.trace!="boolean"&&(Be.wasm.trace=!1),typeof Be.wasm.numThreads!="number"||!Number.isInteger(Be.wasm.numThreads)||Be.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Be.wasm.numThreads=1;else{let t=typeof navigator>"u"?zv("node:os").cpus().length:navigator.hardwareConcurrency;Be.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ci=class{async init(e){li(),await Ch(),await Sh(e)}async createInferenceSessionHandler(e,t){let r=new zh;return await r.loadModel(e,t),r}},Rh=new ci});Vr(),Vr(),Vr();var iy="1.26.0-dev.20260416-b7804b056c",ly=Rd;{let e=(oy(),Gn(Bh)).wasmBackend;Br("webgpu",e,5),Br("webnn",e,5),Br("cpu",e,10),Br("wasm",e,10)}Object.defineProperty(Be.versions,"web",{value:iy,enumerable:!0});var cy=Object.freeze({__proto__:null,get InferenceSession(){return Eo},get TRACE(){return Vn},get TRACE_EVENT_BEGIN(){return Tr},get TRACE_EVENT_END(){return Er},get TRACE_FUNC_BEGIN(){return Gr},get TRACE_FUNC_END(){return $r},get Tensor(){return zt},default:ly,get env(){return Be},get registerBackend(){return Br}});const uy=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];const s=r.getContext("2d");if(s!=null){let n,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);const o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",i=t==null?void 0:t.norm;let l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));const d=a*n;let h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let v=0;v<a;v++)for(let y=0;y<n;y++){const M=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],A=(e.data[p++]-c[2])*l[2],S=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+M+","+T+","+A+","+S+")",s.fillRect(y,v,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},dy=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(r!=null){let n,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm;let c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let p=0,w=1,v=2,y=3,M=0,T=h,A=h*2,S=-1;i==="RGBA"?(M=0,T=h,A=h*2,S=h*3):i==="RGB"?(M=0,T=h,A=h*2):i==="RBG"&&(M=0,A=h,T=h*2),s=r.createImageData(n,a);for(let C=0;C<a*n;p+=_,w+=_,v+=_,y+=_,C++)s.data[p]=(e.data[M++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[v]=(e.data[A++]-d[2])*c[2],s.data[y]=S===-1?255:(e.data[S++]-d[3])*c[3]}else throw new Error("Can not access image data");return s},ui=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:s}=t,n=t.norm??{mean:255,bias:0};let a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let h=4,_=0,p=1,w=2,v=3,y=0,M=c,T=c*2,A=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(y=0,T=c,M=c*2):l==="BGR"&&(T=0,M=c,y=c*2);for(let C=0;C<c;C++,_+=h,w+=h,p+=h,v+=h)d[y++]=(e[_]+o[0])/a[0],d[M++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new St("float32",d,[1,4,r,s]):new St("float32",d,[1,3,r,s])},hy=async(e,t)=>{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let o,i=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){const d=l();d.width=e.width,d.height=e.height;const h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){const _=l();_.width=h,_.height=d;const p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const d=l();d.width=e.width,d.height=e.height;const h=c(d);if(h!=null){const _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,ui(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{const _=l(),p=c(_);if(!e||!p)return h();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);const v=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(ui(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ui(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},fy=(e,t)=>{const{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new St({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},_y=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new St({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},py=(e,t)=>{const{dataType:r,dims:s,download:n,dispose:a}=t;return new St({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},my=(e,t,r)=>new St({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),as=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Kn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Gh=!1;const gy=()=>{if(!Gh){Gh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(as.set("int64",BigInt64Array),Kn.set(BigInt64Array,"int64")),t&&(as.set("uint64",BigUint64Array),Kn.set(BigUint64Array,"uint64")),s?(as.set("float16",r),Kn.set(r,"float16")):as.set("float16",Uint16Array)}},wy=e=>{let t=1;for(let r=0;r<e.length;r++){const s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s}return t},vy=(e,t)=>{switch(e.location){case"cpu":return new St(e.type,e.data,t);case"cpu-pinned":return new St({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new St({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new St({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new St({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let St=class{constructor(t,r,s){gy();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=as.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof t=="string")if(n=t,l=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const c=as.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof t[0];if(c==="string")n="string",i=t;else if(c==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(t);else{const c=Kn.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=c,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}const o=wy(a);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=o}static async fromImage(t,r){return hy(t,r)}static fromTexture(t,r){return fy(t,r)}static fromGpuBuffer(t,r){return _y(t,r)}static fromMLTensor(t,r){return py(t,r)}static fromPinnedBuffer(t,r,s){return my(t,r,s)}toDataURL(t){return uy(this,t)}toImageData(t){return dy(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return vy(this,t)}};const yy=St;var cr={},by=Object.defineProperty,os=(e,t)=>{for(var r in t)by(e,r,{get:t[r],enumerable:!0})},Tt={},Yt={},My={},xy="4.2.0",di=typeof self<"u",is=!Wh(Tt),$h=!Wh(Yt),Zn=di&&"caches"in self,ky=typeof globalThis.Deno<"u",ea=ky&&Zn&&!is,Vh=typeof process<"u",Uh=Vh&&((yg=process==null?void 0:process.release)==null?void 0:yg.name)==="node"&&!ea,hi=typeof window<"u"&&typeof window.document<"u",fi=di&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((bg=self.constructor)==null?void 0:bg.name),Ty=hi||fi||ea,Ey=Uh||typeof navigator<"u"&&"gpu"in navigator,Ay=typeof navigator<"u"&&"ml"in navigator,Cy=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",Sy=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",Py=typeof ServiceWorkerGlobalScope<"u"&&di&&self instanceof ServiceWorkerGlobalScope,Fy=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&s},Ly=Fy(),fe=Object.freeze({IS_BROWSER_ENV:hi,IS_WEBWORKER_ENV:fi,IS_WEB_ENV:Ty,IS_SERVICE_WORKER_ENV:Py,IS_DENO_WEB_RUNTIME:ea,IS_WEB_CACHE_AVAILABLE:Zn,IS_WEBGPU_AVAILABLE:Ey,IS_WEBNN_AVAILABLE:Ay,IS_SAFARI:Ly,IS_PROCESS_AVAILABLE:Vh,IS_NODE_ENV:Uh,IS_FS_AVAILABLE:is,IS_PATH_AVAILABLE:$h,IS_CRYPTO_AVAILABLE:Cy,IS_CHROME_AVAILABLE:Sy}),_i=is&&$h,ta="./";if(_i){const e=Object({url:self.location.href}).url;e?ta=Yt.dirname(Yt.dirname(My.fileURLToPath(e))):typeof __dirname<"u"&&(ta=Yt.dirname(__dirname))}var Iy=_i?Yt.join(ta,"/.cache/"):null,jh="/models/",Oy=_i?Yt.join(ta,jh):jh,Ny=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Bt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),qh=Bt.WARNING,be={version:xy,backends:{onnx:{}},get logLevel(){return qh},set logLevel(e){var t,r;qh=e,(r=(t=be.backends.onnx)==null?void 0:t.setLogLevel)==null||r.call(t,e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(hi||fi||ea),localModelPath:Oy,useFS:is,useBrowserCache:Zn,useFSCache:is,cacheDir:Iy,useCustomCache:!1,customCache:null,useWasmCache:Zn||is,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:Ny};function Wh(e){return Object.keys(e).length===0}var vt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Pr(e,t){e&&e(t)}var pi=class extends vt{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};const t=Object.values(this.files_loading).reduce((n,a)=>n+a.loaded,0),r=Object.values(this.files_loading).reduce((n,a)=>n+a.total,0),s=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:s,loaded:t,total:r,files:structuredClone(this.files_loading)})}this.callback(e)}};function Dy(e){return Number.isInteger(e)||typeof e=="bigint"}function Hh(e){return e==null||e===-1}function Qh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Jt(...e){return Array.prototype.concat.apply([],e)}function zy(...e){return e.reduce((t,r)=>t.flatMap(s=>r.map(n=>[s,n])))}function ra(e,t){return Math.abs((e+t)%(2*t)-t)}function Ze(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function By(e,t){let r=0;for(const s of e)s===t&&++r;return r}var ue={error(...e){be.logLevel<=Bt.ERROR&&console.error(...e)},warn(...e){be.logLevel<=Bt.WARNING&&console.warn(...e)},info(...e){be.logLevel<=Bt.INFO&&console.log(...e)},debug(...e){be.logLevel<=Bt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Ry=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let s=t;for(let n=0;n<r.length;++n){const a=r[n];s=s[a]??(s[a]=Object.create(null))}s.end=r}return t}split(e){const t=[],r=e.length;let s=0,n=0;for(;n<r;){let a=this.trie,o=null,i=n;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(n>s&&t.push(e.slice(s,n)),t.push(o),n+=o.length,s=n):++n}return s<r&&t.push(e.slice(s)),t}},Xh=Ry,Gy=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},$y=Gy,Yh=(()=>{const e=[...Array.from({length:94},(n,a)=>a+33),...Array.from({length:12},(n,a)=>a+161),...Array.from({length:82},(n,a)=>a+174)],t=e.slice();let r=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);const s=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,a)=>[n,s[a]]))})(),Vy=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),Uy=Vy(Yh),Jh=".,!?…。,、।۔،",jy=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|[${Jh}])]+`,` ?[^\\s${Jh}]+`]]),sa="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",mi=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"),na=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[s,n]of jy)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(a,"gu")}catch{throw s}}}else if(e.String!==void 0){const r=qy(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},qy=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Wy=(e,t,r)=>{const s=[];let n=0;for(;n<e.length;){if(s.push(e[n]),(t.get(e[n])??r)!==r){++n;continue}for(;++n<e.length&&(t.get(e[n])??r)===r;)t.get(s.at(-1))!==r&&(s[s.length-1]+=e[n])}return s},Hy=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Qy=e=>Number.isInteger(e)||typeof e=="bigint",Xy=e=>{let t=0;for(const r of e)++t;return t},Yy=e=>Kh(e.toLowerCase()),Rt=(...e)=>Array.prototype.concat.apply([],e),gi=e=>new Map(Object.entries(e)),Jy=(e,t)=>{const r=[];let s=0;for(const n of e.matchAll(t)){const a=n[0];s<n.index&&r.push(e.slice(s,n.index)),a.length>0&&r.push(a),s=n.index+a.length}return s<e.length&&r.push(e.slice(s)),r},Kh=e=>e.replace(new RegExp("\\p{M}","gu"),""),Zh=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const s of r)if(!(s in e))return`${t} must contain a "${s}" property`;return null},Ky=e=>e.match(/\S+/g)||[],Zy=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Xs=Zy,eb=class extends Xs{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},ur=eb,tb=class extends ur{tokenize_chinese_chars(e){const t=[];for(let r=0;r<e.length;++r){const s=e[r],n=s.charCodeAt(0);Hy(n)?(t.push(" "),t.push(s),t.push(" ")):t.push(s)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(e){switch(e){case" ":case`
9
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(e)}}clean_text(e){const t=[];for(const r of e){const s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},rb=tb,sb=class extends ur{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("~")?e=e.split("~").map(r=>r.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},nb=sb,ab=class extends ur{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>ef(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},ob=ab,ib=class extends ur{normalize(e){const t=na(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},lb=ib,cb=class extends ur{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},aa=cb,ub=class extends aa{constructor(){super(...arguments),this.form="NFC"}},db=ub,hb=class extends aa{constructor(){super(...arguments),this.form="NFD"}},fb=hb,_b=class extends aa{constructor(){super(...arguments),this.form="NFKC"}},pb=_b,mb=class extends aa{constructor(){super(...arguments),this.form="NFKD"}},gb=mb,wb=class extends ur{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}},vb=wb,yb=class extends ur{normalize(e){return Kh(e)}},bb=yb,Mb=class extends ur{normalize(e){return e.toLowerCase()}},xb=Mb,kb=class extends ur{normalize(e){return e=this.config.prepend+e,e}},Tb=kb;function Eb(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new rb(e);case"Precompiled":return new nb(e);case"Sequence":return new ob(e);case"Replace":return new lb(e);case"NFC":return new db(e);case"NFD":return new fb(e);case"NFKC":return new pb(e);case"NFKD":return new gb(e);case"Strip":return new vb(e);case"StripAccents":return new bb(e);case"Lowercase":return new xb(e);case"Prepend":return new Tb(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var ef=Eb,Ab=class extends Xs{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Gt=Ab,Cb=class extends Gt{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Yh,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(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},Sb=Cb,Pb=class extends Gt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Fb=Pb,Lb=class extends Gt{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:r=void 0}=t??{};let s=e.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},Ib=Lb,Ob=class extends Gt{constructor(e){super(),this.config=e,this.pattern=na(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){var t;return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:((t=this.config.behavior)==null?void 0:t.toLowerCase())==="removed"?e.split(this.pattern).filter(r=>r):Jy(e,this.pattern)}},Nb=Ob,Db=class extends Gt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${sa}]+|[${sa}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},zb=Db,Bb=class extends Gt{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Rb=Bb,Gb=class extends Gt{constructor(){super(),this.pattern=new RegExp(`[^\\s${sa}]+|[${sa}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},$b=Gb,Vb=class extends Gt{constructor(e){super(),this.config=e,this.pattern=na(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},Ub=Vb,jb=class extends Gt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>tf(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,t):r,[e])}},qb=jb,Wb=class extends Gt{pre_tokenize_text(e){return Ky(e)}},Hb=Wb,Qb=class extends Gt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},Xb=Qb;function Yb(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new $b;case"Sequence":return new qb(e);case"Whitespace":return new Fb;case"WhitespaceSplit":return new Hb;case"Metaspace":return new Ib(e);case"ByteLevel":return new Sb(e);case"Split":return new Nb(e);case"Punctuation":return new zb(e);case"Digits":return new Rb(e);case"Replace":return new Ub(e);case"FixedLength":return new Xb(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var tf=Yb,Jb=class extends Xs{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=Wy(t,this.tokens_to_ids,this.unk_token_id)),t}},oa=Jb,Kb=class extends oa{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=gi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){const t=[];for(const r of e){const s=[...r];if(s.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,a=0;const o=[];for(;a<s.length;){let i=s.length,l=null;for(;a<i;){let c=s.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}o.push(l),a=i}n?t.push(this.unk_token):t.push(...o)}return t}},rf=Kb,sf=class Iv{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new Iv(!1,new Map)}},Zb=class{constructor(){this.root=sf.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let s=t.children.get(r);s===void 0&&(s=sf.default(),t.children.set(r,s)),t=s}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const s of e){if(r+=s,t=t.children.get(s),t===void 0)return;t.is_leaf&&(yield r)}}},e0=Zb,wi=class Ov{constructor(t,r,s,n,a){this.token_id=t,this.node_id=r,this.pos=s,this.length=n,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new Ov(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},t0=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);const s=new wi(this.bos_token_id??0,0,0,0,0),n=new wi(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(e,t,r,s){const n=this.nodes.length,a=new wi(s,n,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let c of this.end_nodes[t]){const d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.clone(),i=d)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}const r=[],n=this.begin_nodes[e][0].prev;if(n===null)return[];let a=n.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},r0=t0;function s0(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}var n0=class extends oa{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=e.vocab[s];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=s0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new e0,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let s=0;for(;s<t.length;){let n=!1;const a=t.slice(s).join(""),o=this.trie.common_prefix_search(a);for(const i of o){const l=this.tokens_to_ids.get(i),c=this.scores[l],d=Xy(i);e.insert(s,d,c,l),!n&&d===r&&(n=!0)}n||e.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(e){const t=new r0(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const r of e){const s=this.tokenize(r);t.push(...s)}return t}},nf=n0,a0=class{constructor(e=(r,s)=>r>s,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{const r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},o0=a0,i0=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},l0=i0,c0=class extends oa{constructor(e){super(e),this.tokens_to_ids=gi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,s]of this.tokens_to_ids)this.vocab[s]=r;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),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 l0(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){const n=new o0((i,l)=>i.score<l.score);let a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){const l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(n,o),o=l}for(;!n.is_empty();){const i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){const c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}const l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=a;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,s),s}add_node(e,t){const r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){const t=[];for(const r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}const s=this.bpe(r);for(const n of s)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(n)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},af=c0,u0=class extends oa{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=gi(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(e){return e}},d0=u0;function h0(e,t){switch(e.type){case"WordPiece":return new rf(e);case"Unigram":return new nf(e,t.eos_token);case"BPE":return new af(e);default:if(e.vocab)return Array.isArray(e.vocab)?new nf(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new af(e):new rf(e):new d0(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e==null?void 0:e.type}`)}}var f0=h0,_0=class extends Xs{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Ys=_0,p0=class extends Ys{post_process(e,t=null,r=!0){const s=t===null?this.config.single:this.config.pair;let n=[],a=[];for(const o of s)"SpecialToken"in o?r&&(n.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(n=Rt(n,e),a=Rt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(n=Rt(n,t),a=Rt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:n,token_type_ids:a}}},m0=p0,g0=class extends Ys{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},w0=g0,v0=class extends Ys{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Rt([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=[],a=r?[this.sep[0]]:[];e=Rt(e,n,t,a),s=Rt(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},y0=v0,b0=class extends Ys{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Rt([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const n=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Rt(e,n,t,a),s=Rt(s,new Array(t.length+n.length+a.length).fill(1))}return{tokens:e,token_type_ids:s}}},M0=b0,x0=class extends Ys{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>of(t))}post_process(e,t=null,r=!0){let s={tokens:e,tokens_pair:t};for(const n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},k0=x0;function T0(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new m0(e);case"ByteLevel":return new w0(e);case"BertProcessing":return new y0(e);case"RobertaProcessing":return new M0(e);case"Sequence":return new k0(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var of=T0,E0=class extends Xs{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("")}},$t=E0,A0=class extends $t{constructor(e){super(e),this.byte_decoder=Uy,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const s of e)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},C0=A0,S0=class extends $t{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const s=this.config.prefix;s&&t.startsWith(s)?t=t.replace(s,""):t=" "+t}return this.cleanup&&(t=mi(t)),t})}},P0=S0,F0=class extends $t{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;r<e.length;++r){let s=e[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),t.push(s)}return t}},L0=F0,I0=class extends $t{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},O0=I0,N0=class extends $t{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let s=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=mi(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},D0=N0,z0=class extends $t{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>lf(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},B0=z0,R0=class extends $t{decode_chain(e){const t=na(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(s=>s.replaceAll(t,r))}},G0=R0,$0=class extends $t{decode_chain(e){return[e.join("")]}},V0=$0,U0=class extends $t{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let n=0;n<this.start&&t[n]===this.content;++n){r=n+1;continue}let s=t.length;for(let n=0;n<this.stop;++n){const a=t.length-n-1;if(t[a]===this.content){s=a;continue}else break}return t.slice(r,s)})}},j0=U0,q0=class extends $t{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const s of e){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){const a=parseInt(s.slice(3,5),16);isNaN(a)||(n=a)}if(n!==null)r.push(n);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}return t}},W0=q0;function H0(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new C0(e);case"WordPiece":return new P0(e);case"Metaspace":return new L0(e);case"BPEDecoder":return new O0(e);case"CTC":return new D0(e);case"Sequence":return new B0(e);case"Replace":return new G0(e);case"Fuse":return new V0(e);case"Strip":return new j0(e);case"ByteFallback":return new W0(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var lf=H0,Q0=class{constructor(e,t){const r=Zh(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const s=Zh(t,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=t,this.normalizer=ef(this.tokenizer.normalizer),this.pre_tokenizer=tf(this.tokenizer.pre_tokenizer),this.model=f0(this.tokenizer.model,this.config),this.post_processor=of(this.tokenizer.post_processor),this.decoder=lf(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const n=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new $y(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Xh(n),this.splitter_normalized=new Xh(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{tokens:n,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=n.map(l=>{var c;return((c=this.added_tokens_map.get(l))==null?void 0:c.id)??this.model.tokens_to_ids.get(l)??this.model.unk_token_id}),i={ids:o,tokens:n,attention_mask:new Array(o.length).fill(1)};return s&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Qy(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(s=s.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=mi(s)),s}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,s)=>{const n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(t[s-1]=t[s-1].trimEnd()),n.rstrip&&s<t.length-1&&(t[s+1]=t[s+1].trimStart()))}),t.flatMap((r,s)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=Yy(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const n=this.splitter_normalized.split(r);return n.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(n[o-1]=n[o-1].trimEnd()),i.rstrip&&o<n.length-1&&(n[o+1]=n[o+1].trimStart()))}),n.flatMap(a=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:s}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const s=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Rt(s??[],n??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let r=0;r<this.model.vocab.length;++r){const s=this.model.vocab[r];(e||!this.added_tokens_map.has(s))&&t.set(s,r)}return t}},X0=Q0,B=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Pt=class{constructor(e,t){this.value=e,this.type=t}};function cf(e){return/\w/.test(e)}function Js(e){return/[0-9]/.test(e)}function uf(e){return/\s/.test(e)}var Y0=[["{%",B.OpenStatement],["%}",B.CloseStatement],["{{",B.OpenExpression],["}}",B.CloseExpression],["(",B.OpenParen],[")",B.CloseParen],["{",B.OpenCurlyBracket],["}",B.CloseCurlyBracket],["[",B.OpenSquareBracket],["]",B.CloseSquareBracket],[",",B.Comma],[".",B.Dot],[":",B.Colon],["|",B.Pipe],["<=",B.ComparisonBinaryOperator],[">=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],J0=new Map([["n",`
10
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function K0(e,t={}){return e.endsWith(`
11
+ `)&&(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 Z0(e,t={}){var c,d;const r=[],s=K0(e,t);let n=0,a=0;const o=h=>{let _="";for(;h(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");const p=s[n++],w=J0.get(p);if(w===void 0)throw new SyntaxError(`Unexpected escaped character: ${p}`);_+=w;continue}if(_+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return _},i=()=>{const h=r.at(-1);h&&h.type===B.Text&&(h.value=h.value.trimEnd(),h.value===""&&r.pop())},l=()=>{for(;n<s.length&&uf(s[n]);)++n};e:for(;n<s.length;){const h=(c=r.at(-1))==null?void 0:c.type;if(h===void 0||h===B.CloseStatement||h===B.CloseExpression||h===B.Comment){let p="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)p+=s[n++];if(p.length>0){r.push(new Pt(p,B.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;const p=s[n]==="-";p&&++n;let w="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");w+=s[n++]}const v=w.endsWith("-");v&&(w=w.slice(0,-1)),p&&i(),r.push(new Pt(w,B.Comment)),n+=2,v&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Pt("{%",B.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Pt("{{",B.OpenExpression)),a=0,n+=3;continue}if(o(uf),s.slice(n,n+3)==="-%}"){r.push(new Pt("%}",B.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Pt("}}",B.CloseExpression)),n+=3,l();continue}const _=s[n];if(_==="-"||_==="+"){const p=(d=r.at(-1))==null?void 0:d.type;if(p===B.Text||p===void 0)throw new SyntaxError(`Unexpected character: ${_}`);switch(p){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++n;const w=o(Js);r.push(new Pt(`${_}${w}`,w.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(const[p,w]of Y0){if(p==="}}"&&a>0)continue;if(s.slice(n,n+p.length)===p){r.push(new Pt(p,w)),w===B.OpenExpression?a=0:w===B.OpenCurlyBracket?++a:w===B.CloseCurlyBracket&&--a,n+=p.length;continue e}}if(_==="'"||_==='"'){++n;const p=o(w=>w!==_);r.push(new Pt(p,B.StringLiteral)),++n;continue}if(Js(_)){let p=o(Js);if(s[n]==="."&&Js(s[n+1])){++n;const w=o(Js);p=`${p}.${w}`}r.push(new Pt(p,B.NumericLiteral));continue}if(cf(_)){const p=o(cf);r.push(new Pt(p,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${_}`)}return r}var Vt=class{constructor(){k(this,"type","Statement")}},eM=class extends Vt{constructor(t){super();k(this,"type","Program");this.body=t}},tM=class extends Vt{constructor(t,r,s){super();k(this,"type","If");this.test=t,this.body=r,this.alternate=s}},rM=class extends Vt{constructor(t,r,s,n){super();k(this,"type","For");this.loopvar=t,this.iterable=r,this.body=s,this.defaultBlock=n}},sM=class extends Vt{constructor(){super(...arguments);k(this,"type","Break")}},nM=class extends Vt{constructor(){super(...arguments);k(this,"type","Continue")}},aM=class extends Vt{constructor(t,r,s){super();k(this,"type","Set");this.assignee=t,this.value=r,this.body=s}},oM=class extends Vt{constructor(t,r,s){super();k(this,"type","Macro");this.name=t,this.args=r,this.body=s}},iM=class extends Vt{constructor(t){super();k(this,"type","Comment");this.value=t}},Et=class extends Vt{constructor(){super(...arguments);k(this,"type","Expression")}},lM=class extends Et{constructor(t,r,s){super();k(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=s}},df=class extends Et{constructor(t,r){super();k(this,"type","CallExpression");this.callee=t,this.args=r}},ls=class extends Et{constructor(t){super();k(this,"type","Identifier");this.value=t}},cs=class extends Et{constructor(t){super();k(this,"type","Literal");this.value=t}},cM=class extends cs{constructor(){super(...arguments);k(this,"type","IntegerLiteral")}},uM=class extends cs{constructor(){super(...arguments);k(this,"type","FloatLiteral")}},hf=class extends cs{constructor(){super(...arguments);k(this,"type","StringLiteral")}},dM=class extends cs{constructor(){super(...arguments);k(this,"type","ArrayLiteral")}},ff=class extends cs{constructor(){super(...arguments);k(this,"type","TupleLiteral")}},hM=class extends cs{constructor(){super(...arguments);k(this,"type","ObjectLiteral")}},Ks=class extends Et{constructor(t,r,s){super();k(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=s}},fM=class extends Et{constructor(t,r){super();k(this,"type","FilterExpression");this.operand=t,this.filter=r}},_M=class extends Vt{constructor(t,r){super();k(this,"type","FilterStatement");this.filter=t,this.body=r}},pM=class extends Et{constructor(t,r){super();k(this,"type","SelectExpression");this.lhs=t,this.test=r}},mM=class extends Et{constructor(t,r,s){super();k(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=s}},gM=class extends Et{constructor(t,r){super();k(this,"type","UnaryExpression");this.operator=t,this.argument=r}},wM=class extends Et{constructor(t=void 0,r=void 0,s=void 0){super();k(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=s}},vM=class extends Et{constructor(t,r){super();k(this,"type","KeywordArgumentExpression");this.key=t,this.value=r}},yM=class extends Et{constructor(t){super();k(this,"type","SpreadExpression");this.argument=t}},bM=class extends Vt{constructor(t,r,s){super();k(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=s}},MM=class extends Et{constructor(t,r,s){super();k(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=s}};function xM(e){const t=new eM([]);let r=0;function s(G,L){const V=e[r++];if(!V||V.type!==G)throw new Error(`Parser Error: ${L}. ${V.type} !== ${G}.`);return V}function n(G){if(!l(G))throw new SyntaxError(`Expected ${G}`);++r}function a(){switch(e[r].type){case B.Comment:return new iM(e[r++].value);case B.Text:return c();case B.OpenStatement:return d();case B.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...G){return r+G.length<=e.length&&G.every((L,V)=>L===e[r+V].type)}function i(...G){var L,V,X;return((L=e[r])==null?void 0:L.type)===B.OpenStatement&&((V=e[r+1])==null?void 0:V.type)===B.Identifier&&G.includes((X=e[r+1])==null?void 0:X.value)}function l(...G){return r+G.length<=e.length&&G.every((L,V)=>e[r+V].type==="Identifier"&&L===e[r+V].value)}function c(){return new hf(s(B.Text,"Expected text token").value)}function d(){if(s(B.OpenStatement,"Expected opening statement token"),e[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const G=e[r].value;let L;switch(G){case"set":++r,L=_();break;case"if":++r,L=p(),s(B.OpenStatement,"Expected {% token"),n("endif"),s(B.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),s(B.OpenStatement,"Expected {% token"),n("endmacro"),s(B.CloseStatement,"Expected %} token");break;case"for":++r,L=y(),s(B.OpenStatement,"Expected {% token"),n("endfor"),s(B.CloseStatement,"Expected %} token");break;case"call":{++r;let V=null;o(B.OpenParen)&&(V=$());const X=ee();if(X.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const J=$();s(B.CloseStatement,"Expected closing statement token");const we=[];for(;!i("endcall");)we.push(a());s(B.OpenStatement,"Expected '{%'"),n("endcall"),s(B.CloseStatement,"Expected closing statement token");const re=new df(X,J);L=new bM(re,V,we);break}case"break":++r,s(B.CloseStatement,"Expected closing statement token"),L=new sM;break;case"continue":++r,s(B.CloseStatement,"Expected closing statement token"),L=new nM;break;case"filter":{++r;let V=ee();V instanceof ls&&o(B.OpenParen)&&(V=z(V)),s(B.CloseStatement,"Expected closing statement token");const X=[];for(;!i("endfilter");)X.push(a());s(B.OpenStatement,"Expected '{%'"),n("endfilter"),s(B.CloseStatement,"Expected '%}'"),L=new _M(V,X);break}default:throw new SyntaxError(`Unknown statement type: ${G}`)}return L}function h(){s(B.OpenExpression,"Expected opening expression token");const G=M();return s(B.CloseExpression,"Expected closing expression token"),G}function _(){const G=v();let L=null;const V=[];if(o(B.Equals))++r,L=v();else{for(s(B.CloseStatement,"Expected %} token");!i("endset");)V.push(a());s(B.OpenStatement,"Expected {% token"),n("endset")}return s(B.CloseStatement,"Expected closing statement token"),new aM(G,L,V)}function p(){const G=M();s(B.CloseStatement,"Expected closing statement token");const L=[],V=[];for(;!i("elif","else","endif");)L.push(a());if(i("elif")){++r,++r;const X=p();V.push(X)}else if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endif");)V.push(a());return new tM(G,L,V)}function w(){const G=ee();if(G.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const L=$();s(B.CloseStatement,"Expected closing statement token");const V=[];for(;!i("endmacro");)V.push(a());return new oM(G,L,V)}function v(G=!1){const L=G?ee:M,V=[L()],X=o(B.Comma);for(;X&&(++r,V.push(L()),!!o(B.Comma)););return X?new ff(V):V[0]}function y(){const G=v(!0);if(!(G instanceof ls||G instanceof ff))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${G.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const L=M();s(B.CloseStatement,"Expected closing statement token");const V=[];for(;!i("endfor","else");)V.push(a());const X=[];if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endfor");)X.push(a());return new rM(G,L,V,X)}function M(){return T()}function T(){const G=A();if(l("if")){++r;const L=A();if(l("else")){++r;const V=T();return new MM(L,G,V)}else return new pM(G,L)}return G}function A(){let G=S();for(;l("or");){const L=e[r];++r;const V=S();G=new Ks(L,G,V)}return G}function S(){let G=C();for(;l("and");){const L=e[r];++r;const V=C();G=new Ks(L,G,V)}return G}function C(){let G;for(;l("not");){const L=e[r];++r;const V=C();G=new gM(L,V)}return G??I()}function I(){let G=x();for(;;){let L;if(l("not","in"))L=new Pt("not in",B.Identifier),r+=2;else if(l("in"))L=e[r++];else if(o(B.ComparisonBinaryOperator))L=e[r++];else break;const V=x();G=new Ks(L,G,V)}return G}function x(){let G=O();for(;o(B.AdditiveBinaryOperator);){const L=e[r];++r;const V=O();G=new Ks(L,G,V)}return G}function R(){const G=D(ee());return o(B.OpenParen)?z(G):G}function z(G){let L=new df(G,$());return L=D(L),o(B.OpenParen)&&(L=z(L)),L}function $(){s(B.OpenParen,"Expected opening parenthesis for arguments list");const G=Q();return s(B.CloseParen,"Expected closing parenthesis for arguments list"),G}function Q(){const G=[];for(;!o(B.CloseParen);){let L;if(e[r].type===B.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const V=M();L=new yM(V)}else if(L=M(),o(B.Equals)){if(++r,!(L instanceof ls))throw new SyntaxError("Expected identifier for keyword argument");const V=M();L=new vM(L,V)}G.push(L),o(B.Comma)&&++r}return G}function H(){const G=[];let L=!1;for(;!o(B.CloseSquareBracket);)o(B.Colon)?(G.push(void 0),++r,L=!0):(G.push(M()),o(B.Colon)&&(++r,L=!0));if(G.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(G.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new wM(...G)}return G[0]}function D(G){for(;o(B.Dot)||o(B.OpenSquareBracket);){const L=e[r];++r;let V;const X=L.type===B.OpenSquareBracket;if(X)V=H(),s(B.CloseSquareBracket,"Expected closing square bracket");else if(V=ee(),V.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");G=new lM(G,V,X)}return G}function O(){let G=te();for(;o(B.MultiplicativeBinaryOperator);){const L=e[r++],V=te();G=new Ks(L,G,V)}return G}function te(){let G=W();for(;l("is");){++r;const L=l("not");L&&++r;const V=ee();if(!(V instanceof ls))throw new SyntaxError("Expected identifier for the test");G=new mM(G,L,V)}return G}function W(){let G=R();for(;o(B.Pipe);){++r;let L=ee();if(!(L instanceof ls))throw new SyntaxError("Expected identifier for the filter");o(B.OpenParen)&&(L=z(L)),G=new fM(G,L)}return G}function ee(){const G=e[r++];switch(G.type){case B.NumericLiteral:{const L=G.value;return L.includes(".")?new uM(Number(L)):new cM(Number(L))}case B.StringLiteral:{let L=G.value;for(;o(B.StringLiteral);)L+=e[r++].value;return new hf(L)}case B.Identifier:return new ls(G.value);case B.OpenParen:{const L=v();return s(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case B.OpenSquareBracket:{const L=[];for(;!o(B.CloseSquareBracket);)L.push(M()),o(B.Comma)&&++r;return++r,new dM(L)}case B.OpenCurlyBracket:{const L=new Map;for(;!o(B.CloseCurlyBracket);){const V=M();s(B.Colon,"Expected colon between key and value in object literal");const X=M();L.set(V,X),o(B.Comma)&&++r}return++r,new hM(L)}default:throw new SyntaxError(`Unexpected token: ${G.type}`)}}for(;r<e.length;)t.body.push(a());return t}function kM(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const s=[];if(r>0)for(let n=e;n<t;n+=r)s.push(n);else for(let n=e;n>t;n+=r)s.push(n);return s}function _f(e,t,r,s=1){const n=Math.sign(s);n>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;n*o<n*r;o+=s)a.push(e[o]);return a}function TM(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function EM(e){return AM(new Date,e)}function AM(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return n(e.getMonth()+1);case"%d":return n(e.getDate());case"%b":return s.format(e);case"%B":return r.format(e);case"%H":return n(e.getHours());case"%M":return n(e.getMinutes());case"%%":return"%";default:return a}})}function CM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function SM(e,t,r,s){if(s===0)return e;let n=s==null||s<0?1/0:s;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(CM(t),"gu");return e.replaceAll(a,o=>n>0?(--n,r):o)}var pf=class extends Error{},mf=class extends Error{},Kt=class{constructor(e=void 0){k(this,"type","RuntimeValue");k(this,"value");k(this,"builtins",new Map);this.value=e}__bool__(){return new ie(!!this.value)}toString(){return String(this.value)}},he=class extends Kt{constructor(){super(...arguments);k(this,"type","IntegerValue")}},$e=class extends Kt{constructor(){super(...arguments);k(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends Kt{constructor(){super(...arguments);k(this,"type","StringValue");k(this,"builtins",new Map([["upper",new Ne(()=>new Z(this.value.toUpperCase()))],["lower",new Ne(()=>new Z(this.value.toLowerCase()))],["strip",new Ne(()=>new Z(this.value.trim()))],["title",new Ne(()=>new Z(TM(this.value)))],["capitalize",new Ne(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Ne(()=>new Z(this.value.trimEnd()))],["lstrip",new Ne(()=>new Z(this.value.trimStart()))],["startswith",new Ne(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");const r=t[0];if(r instanceof Z)return new ie(this.value.startsWith(r.value));if(r instanceof ge){for(const s of r.value){if(!(s instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new ie(!0)}return new ie(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ne(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");const r=t[0];if(r instanceof Z)return new ie(this.value.endsWith(r.value));if(r instanceof ge){for(const s of r.value){if(!(s instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new ie(!0)}return new ie(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ne(t=>{const r=t[0]??new Re;if(!(r instanceof Z||r instanceof Re))throw new Error("sep argument must be a string or null");const s=t[1]??new he(-1);if(!(s instanceof he))throw new Error("maxsplit argument must be a number");let n=[];if(r instanceof Re){const a=this.value.trimStart();for(const{0:o,index:i}of a.matchAll(/\S+/g)){if(s.value!==-1&&n.length>=s.value&&i!==void 0){n.push(o+a.slice(i+o.length));break}n.push(o)}}else{if(r.value==="")throw new Error("empty separator");n=this.value.split(r.value),s.value!==-1&&n.length>s.value&&n.push(n.splice(s.value).join(r.value))}return new ge(n.map(a=>new Z(a)))})],["replace",new Ne(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");const r=t[0],s=t[1];if(!(r instanceof Z&&s instanceof Z))throw new Error("replace() arguments must be strings");let n;if(t.length>2?t[2].type==="KeywordArgumentsValue"?n=t[2].value.get("count")??new Re:n=t[2]:n=new Re,!(n instanceof he||n instanceof Re))throw new Error("replace() count argument must be a number or null");return new Z(SM(this.value,r.value,s.value,n.value))})]]))}},ie=class extends Kt{constructor(){super(...arguments);k(this,"type","BooleanValue")}},PM=/[\x7f-\uffff]/g;function gf(e){return e.replace(PM,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Hr(e,t={},r=0,s=!0){const{indent:n=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,c;switch(o?[l,c]=o:n?(l=",",c=": "):(l=", ",c=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let d=JSON.stringify(e.value);return a&&(d=gf(d)),d}case"ArrayValue":case"ObjectValue":{const d=n?" ".repeat(n):"",h=`
12
+ `+d.repeat(r),_=h+d;if(e.type==="ArrayValue"){const p=e.value.map(w=>Hr(w,t,r+1,s));return n?`[${_}${p.join(`${l}${_}`)}${h}]`:`[${p.join(l)}]`}else{let p=Array.from(e.value.entries());i&&(p=p.sort(([v],[y])=>v.localeCompare(y)));const w=p.map(([v,y])=>{let M=JSON.stringify(v);a&&(M=gf(M));const T=`${M}${c}${Hr(y,t,r+1,s)}`;return n?`${_}${T}`:T});return n?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var et=class extends Kt{constructor(){super(...arguments);k(this,"type","ObjectValue");k(this,"builtins",new Map([["get",new Ne(([t,r])=>{if(!(t instanceof Z))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new Re})],["items",new Ne(()=>this.items())],["keys",new Ne(()=>this.keys())],["values",new Ne(()=>this.values())],["dictsort",new Ne(t=>{let r=new Map;const s=t.filter(l=>l instanceof Zs?(r=l.value,!1):!0),n=s.at(0)??r.get("case_sensitive")??new ie(!1);if(!(n instanceof ie))throw new Error("case_sensitive must be a boolean");const a=s.at(1)??r.get("by")??new Z("key");if(!(a instanceof Z))throw new Error("by must be a string");if(!["key","value"].includes(a.value))throw new Error("by must be either 'key' or 'value'");const o=s.at(2)??r.get("reverse")??new ie(!1);if(!(o instanceof ie))throw new Error("reverse must be a boolean");const i=Array.from(this.value.entries()).map(([l,c])=>new ge([new Z(l),c])).sort((l,c)=>{const d=a.value==="key"?0:1,h=l.value[d],_=c.value[d],p=vi(h,_,n.value);return o.value?-p:p});return new ge(i)})]]))}__bool__(){return new ie(this.value.size>0)}items(){return new ge(Array.from(this.value.entries()).map(([t,r])=>new ge([new Z(t),r])))}keys(){return new ge(Array.from(this.value.keys()).map(t=>new Z(t)))}values(){return new ge(Array.from(this.value.values()))}toString(){return Hr(this,{},0,!1)}},Zs=class extends et{constructor(){super(...arguments);k(this,"type","KeywordArgumentsValue")}},ge=class extends Kt{constructor(){super(...arguments);k(this,"type","ArrayValue");k(this,"builtins",new Map([["length",new he(this.value.length)]]))}__bool__(){return new ie(this.value.length>0)}toString(){return Hr(this,{},0,!1)}},wf=class extends ge{constructor(){super(...arguments);k(this,"type","TupleValue")}},Ne=class extends Kt{constructor(){super(...arguments);k(this,"type","FunctionValue")}},Re=class extends Kt{constructor(){super(...arguments);k(this,"type","NullValue")}},De=class extends Kt{constructor(){super(...arguments);k(this,"type","UndefinedValue")}},Qr=class{constructor(e){k(this,"variables",new Map([["namespace",new Ne(e=>{if(e.length===0)return new et(new Map);if(e.length!==1||!(e[0]instanceof et))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));k(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Ne],["odd",e=>{if(!(e instanceof he))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof he))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof he||e instanceof $e],["integer",e=>e instanceof he],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof et],["sequence",e=>e instanceof ge||e instanceof et||e instanceof Z],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));this.parent=e}set(e,t){return this.declareVariable(e,ia(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new De}catch{return new De}}};function FM(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",kM),e.set("strftime_now",EM),e.set("True",!0),e.set("False",!1),e.set("None",null)}function vf(e,t){const r=t.split(".");let s=e;for(const n of r)if(s instanceof et)s=s.value.get(n)??new De;else if(s instanceof ge){const a=parseInt(n,10);if(!isNaN(a)&&a>=0&&a<s.value.length)s=s.value[a];else return new De}else return new De;return s}function vi(e,t,r=!1){if(e instanceof Re&&t instanceof Re)return 0;if(e instanceof Re||t instanceof Re)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof De&&t instanceof De)return 0;if(e instanceof De||t instanceof De)throw new Error(`Cannot compare ${e.type} with ${t.type}`);const s=a=>a instanceof he||a instanceof $e||a instanceof ie,n=a=>a instanceof ie?a.value?1:0:a.value;if(s(e)&&s(t)){const a=n(e),o=n(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var LM=class{constructor(e){k(this,"global");this.global=e??new Qr}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}const s=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ie(r.value==s.value);case"!=":return new ie(r.value!=s.value)}if(r instanceof De||s instanceof De){if(s instanceof De&&["in","not in"].includes(e.operator.value))return new ie(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Re||s instanceof Re)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Z(r.value.toString()+s.value.toString());if((r instanceof he||r instanceof $e)&&(s instanceof he||s instanceof $e)){const n=r.value,a=s.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?n+a:e.operator.value==="-"?n-a:n*a;return r instanceof $e||s instanceof $e?new $e(o):new he(o)}case"/":return new $e(n/a);case"%":{const o=n%a;return r instanceof $e||s instanceof $e?new $e(o):new he(o)}case"<":return new ie(n<a);case">":return new ie(n>a);case">=":return new ie(n>=a);case"<=":return new ie(n<=a)}}else if(r instanceof ge&&s instanceof ge)switch(e.operator.value){case"+":return new ge(r.value.concat(s.value))}else if(s instanceof ge){const n=s.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ie(n);case"not in":return new ie(!n)}}}if(r instanceof Z||s instanceof Z)switch(e.operator.value){case"+":return new Z(r.value.toString()+s.value.toString())}if(r instanceof Z&&s instanceof Z)switch(e.operator.value){case"in":return new ie(s.value.includes(r.value));case"not in":return new ie(!s.value.includes(r.value))}if(r instanceof Z&&s instanceof et)switch(e.operator.value){case"in":return new ie(s.value.has(r.value));case"not in":return new ie(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,t){const r=[],s=new Map;for(const n of e)if(n.type==="SpreadExpression"){const a=n,o=this.evaluate(a.argument,t);if(!(o instanceof ge))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){const a=n;s.set(a.key.value,this.evaluate(a.value,t))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,t))}return[r,s]}applyFilter(e,t,r){if(t.type==="Identifier"){const s=t;if(s.value==="safe")return e;if(s.value==="tojson")return new Z(Hr(e,{}));if(e instanceof ge)switch(s.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new he(e.value.length);case"reverse":return new ge(e.value.slice().reverse());case"sort":return new ge(e.value.slice().sort((n,a)=>vi(n,a,!1)));case"join":return new Z(e.value.map(n=>n.value).join(""));case"string":return new Z(Hr(e,{},0,!1));case"unique":{const n=new Set,a=[];for(const o of e.value)n.has(o.value)||(n.add(o.value),a.push(o));return new ge(a)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof Z)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const n=e.builtins.get(s.value);if(n instanceof Ne)return n.value([],r);if(n instanceof he)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new Z(e.value.trim());case"indent":return new Z(e.value.split(`
13
13
  `).map((n,a)=>a===0||n.length===0?n:" "+n).join(`
14
- `));case"join":case"string":return e;case"int":{const n=parseInt(e.value,10);return new he(isNaN(n)?0:n)}case"float":{const n=parseFloat(e.value);return new $e(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof he||e instanceof $e)switch(s.value){case"abs":return e instanceof he?new he(Math.abs(e.value)):new $e(Math.abs(e.value));case"int":return new he(Math.floor(e.value));case"float":return new $e(e.value);case"string":return new Z(e.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof Ze)switch(s.value){case"items":return new ge(Array.from(e.value.entries()).map(([n,a])=>new ge([new Z(n),a])));case"length":return new he(e.value.size);default:{const n=e.builtins.get(s.value);if(n)return n instanceof Ne?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(e instanceof oe)switch(s.value){case"bool":return new oe(e.value);case"int":return new he(e.value?1:0);case"float":return new $e(e.value?1:0);case"string":return new Z(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const s=t;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);const n=s.callee.value;if(n==="tojson"){const[,a]=this.evaluateArguments(s.args,r),o=a.get("indent")??new Re;if(!(o instanceof he||o instanceof Re))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new oe(!1);if(!(i instanceof oe))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new oe(!1);if(!(l instanceof oe))throw new Error("If set, sort_keys must be a boolean");const c=a.get("separators")??new Re;let d=null;if(c instanceof ge||c instanceof gf){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");const[h,_]=c.value;if(!(h instanceof Z)||!(_ instanceof Z))throw new Error("separators must be a tuple of two strings");d=[h.value,_.value]}else if(!(c instanceof Re))throw new Error("If set, separators must be a tuple of two strings");return new Z(Hr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let a;if(e instanceof Z)a=Array.from(e.value);else if(e instanceof ge)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(s.args,r),l=o.at(0)??i.get("separator")??new Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(a.join(l.value))}else if(n==="int"||n==="float"){const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("default")??(n==="int"?new he(0):new $e(0));if(e instanceof Z){const l=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:n==="int"?new he(l):new $e(l)}else{if(e instanceof he||e instanceof $e)return e;if(e instanceof oe)return n==="int"?new he(e.value?1:0):new $e(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){const[a,o]=this.evaluateArguments(s.args,r),i=a[0]??new Z(""),l=a[1]??o.get("boolean")??new oe(!1);if(!(l instanceof oe))throw new Error("`default` filter flag must be a boolean");return e instanceof De||l.value&&!e.__bool__().value?i:e}if(e instanceof ge){switch(n){case"sort":{const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("reverse")??new oe(!1);if(!(i instanceof oe))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new oe(!1);if(!(l instanceof oe))throw new Error("case_sensitive must be a boolean");const c=a.at(2)??o.get("attribute")??new Re;if(!(c instanceof Z||c instanceof he||c instanceof Re))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(c instanceof Re)return h;const _=c instanceof he?String(c.value):c.value;return wf(h,_)};return new ge(e.value.slice().sort((h,_)=>{const p=d(h),w=d(_),v=vi(p,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=n==="selectattr";if(e.value.some(h=>!(h instanceof Ze)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,l]=s.args.map(h=>this.evaluate(h,r));let c;if(i){const h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);c=h}else c=(...h)=>h[0].__bool__().value;const d=e.value.filter(h=>{const _=h.value.get(o.value),p=_?c(_,l):!1;return a?p:!p});return new ge(d)}case"map":{const[,a]=this.evaluateArguments(s.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof Z))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(c=>{if(!(c instanceof Ze))throw new Error("items in map must be an object");const d=wf(c,o.value);return d instanceof De?i??new De:d});return new ge(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof Z){switch(n){case"indent":{const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new oe(!1),c=a.at(2)??o.get("blank")??new oe(!1),d=e.value.split(`
14
+ `));case"join":case"string":return e;case"int":{const n=parseInt(e.value,10);return new he(isNaN(n)?0:n)}case"float":{const n=parseFloat(e.value);return new $e(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof he||e instanceof $e)switch(s.value){case"abs":return e instanceof he?new he(Math.abs(e.value)):new $e(Math.abs(e.value));case"int":return new he(Math.floor(e.value));case"float":return new $e(e.value);case"string":return new Z(e.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof et)switch(s.value){case"items":return new ge(Array.from(e.value.entries()).map(([n,a])=>new ge([new Z(n),a])));case"length":return new he(e.value.size);default:{const n=e.builtins.get(s.value);if(n)return n instanceof Ne?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(e instanceof ie)switch(s.value){case"bool":return new ie(e.value);case"int":return new he(e.value?1:0);case"float":return new $e(e.value?1:0);case"string":return new Z(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const s=t;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);const n=s.callee.value;if(n==="tojson"){const[,a]=this.evaluateArguments(s.args,r),o=a.get("indent")??new Re;if(!(o instanceof he||o instanceof Re))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new ie(!1);if(!(i instanceof ie))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new ie(!1);if(!(l instanceof ie))throw new Error("If set, sort_keys must be a boolean");const c=a.get("separators")??new Re;let d=null;if(c instanceof ge||c instanceof wf){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");const[h,_]=c.value;if(!(h instanceof Z)||!(_ instanceof Z))throw new Error("separators must be a tuple of two strings");d=[h.value,_.value]}else if(!(c instanceof Re))throw new Error("If set, separators must be a tuple of two strings");return new Z(Hr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let a;if(e instanceof Z)a=Array.from(e.value);else if(e instanceof ge)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(s.args,r),l=o.at(0)??i.get("separator")??new Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(a.join(l.value))}else if(n==="int"||n==="float"){const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("default")??(n==="int"?new he(0):new $e(0));if(e instanceof Z){const l=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:n==="int"?new he(l):new $e(l)}else{if(e instanceof he||e instanceof $e)return e;if(e instanceof ie)return n==="int"?new he(e.value?1:0):new $e(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){const[a,o]=this.evaluateArguments(s.args,r),i=a[0]??new Z(""),l=a[1]??o.get("boolean")??new ie(!1);if(!(l instanceof ie))throw new Error("`default` filter flag must be a boolean");return e instanceof De||l.value&&!e.__bool__().value?i:e}if(e instanceof ge){switch(n){case"sort":{const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("reverse")??new ie(!1);if(!(i instanceof ie))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new ie(!1);if(!(l instanceof ie))throw new Error("case_sensitive must be a boolean");const c=a.at(2)??o.get("attribute")??new Re;if(!(c instanceof Z||c instanceof he||c instanceof Re))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(c instanceof Re)return h;const _=c instanceof he?String(c.value):c.value;return vf(h,_)};return new ge(e.value.slice().sort((h,_)=>{const p=d(h),w=d(_),v=vi(p,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=n==="selectattr";if(e.value.some(h=>!(h instanceof et)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);const[o,i,l]=s.args.map(h=>this.evaluate(h,r));let c;if(i){const h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);c=h}else c=(...h)=>h[0].__bool__().value;const d=e.value.filter(h=>{const _=h.value.get(o.value),p=_?c(_,l):!1;return a?p:!p});return new ge(d)}case"map":{const[,a]=this.evaluateArguments(s.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof Z))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(c=>{if(!(c instanceof et))throw new Error("items in map must be an object");const d=vf(c,o.value);return d instanceof De?i??new De:d});return new ge(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof Z){switch(n){case"indent":{const[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new ie(!1),c=a.at(2)??o.get("blank")??new ie(!1),d=e.value.split(`
15
15
  `),h=" ".repeat(i.value),_=d.map((p,w)=>!l.value&&w===0||!c.value&&p.length===0?p:h+p);return new Z(_.join(`
16
- `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Ne))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(s.args,r);return a.value([...o,new en(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof Ze){const a=e.builtins.get(n);if(a&&a instanceof Ne){const[o,i]=this.evaluateArguments(s.args,r);return i.size>0&&o.push(new en(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const n=s(r);return new oe(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new De}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new oe(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const s of e){const n=this.evaluate(s,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new Z(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,s]=this.evaluateArguments(e.args,t);s.size>0&&r.push(new en(s));const n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof ge||e instanceof Z))throw new Error("Slice object must be an array or string");const s=this.evaluate(t.start,r),n=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(s instanceof he||s instanceof De))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof De))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof he||a instanceof De))throw new Error("Slice step must be numeric or undefined");return e instanceof ge?new ge(ff(e.value,s.value,n.value,a.value)):new Z(ff(Array.from(e.value),s.value,n.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);s=this.evaluate(e.property,t)}else s=new Z(e.property.value);let n;if(r instanceof Ze){if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ge||r instanceof Z)if(s instanceof he)n=r.value.at(s.value),r instanceof Z&&(n=new Z(r.value.at(s.value)));else if(s instanceof Z)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof Kt?n:new De}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const s=e.assignee.value;t.setVariable(s,r)}else if(e.assignee.type==="TupleLiteral"){const s=e.assignee;if(!(r instanceof ge))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let a=0;a<s.value.length;++a){const o=s.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,n[a])}}else if(e.assignee.type==="MemberExpression"){const s=e.assignee,n=this.evaluate(s.object,t);if(!(n instanceof Ze))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Re}evaluateIf(e,t){const r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const r=new Qr(t);let s,n;if(e.iterable.type==="SelectExpression"){const c=e.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(e.iterable,r);if(!(n instanceof ge||n instanceof Ze))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof Ze&&(n=n.keys());const a=[],o=[];for(let c=0;c<n.value.length;++c){const d=new Qr(r),h=n.value[c];let _;if(e.loopvar.type==="Identifier")_=p=>p.setVariable(e.loopvar.value,h);else if(e.loopvar.type==="TupleLiteral"){const p=e.loopvar;if(h.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${h.type}`);const w=h;if(p.value.length!==w.value.length)throw new Error(`Too ${p.value.length>w.value.length?"few":"many"} items to unpack`);_=v=>{for(let y=0;y<p.value.length;++y){if(p.value[y].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${p.value[y].type}`);v.setVariable(p.value[y].value,w.value[y])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);s&&(_(d),!this.evaluate(s,d).__bool__().value)||(a.push(h),o.push(_))}let i="",l=!0;for(let c=0;c<a.length;++c){const d=new Map([["index",new he(c+1)],["index0",new he(c)],["revindex",new he(a.length-c)],["revindex0",new he(a.length-c-1)],["first",new oe(c===0)],["last",new oe(c===a.length-1)],["length",new he(a.length)],["previtem",c>0?a[c-1]:new De],["nextitem",c<a.length-1?a[c+1]:new De]]);r.setVariable("loop",new Ze(d)),o[c](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof pf)continue;if(h instanceof _f)break;throw h}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new Z(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Ne((r,s)=>{var o;const n=new Qr(s);r=r.slice();let a;((o=r.at(-1))==null?void 0:o.type)==="KeywordArgumentsValue"&&(a=r.pop());for(let i=0;i<e.args.length;++i){const l=e.args[i],c=r[i];if(l.type==="Identifier"){const d=l;if(!c)throw new Error(`Missing positional argument: ${d.value}`);n.setVariable(d.value,c)}else if(l.type==="KeywordArgumentExpression"){const d=l,h=c??(a==null?void 0:a.value.get(d.key.value))??this.evaluate(d.value,n);n.setVariable(d.key.value,h)}else throw new Error(`Unknown argument type: ${l.type}`)}return this.evaluateBlock(e.body,n)})),new Re}evaluateCallStatement(e,t){const r=new Ne((i,l)=>{const c=new Qr(l);if(e.callerArgs)for(let d=0;d<e.callerArgs.length;++d){const h=e.callerArgs[d];if(h.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${h.type}`);c.setVariable(h.value,i[d]??new De)}return this.evaluateBlock(e.body,c)}),[s,n]=this.evaluateArguments(e.call.args,t);s.push(new en(n));const a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);const o=new Qr(t);return o.setVariable("caller",r),a.value(s,o)}evaluateFilterStatement(e,t){const r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new De;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new _f;case"Continue":throw new pf;case"IntegerLiteral":return new he(e.value);case"FloatLiteral":return new $e(e.value);case"StringLiteral":return new Z(e.value);case"ArrayLiteral":return new ge(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new gf(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[s,n]of e.value){const a=this.evaluate(s,t);if(!(a instanceof Z))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(n,t))}return new Ze(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Re;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function ia(e){switch(typeof e){case"number":return Number.isInteger(e)?new he(e):new $e(e);case"string":return new Z(e);case"boolean":return new oe(e);case"undefined":return new De;case"object":return e===null?new Re:Array.isArray(e)?new ge(e.map(ia)):new Ze(new Map(Object.entries(e).map(([t,r])=>[t,ia(r)])));case"function":return new Ne((t,r)=>{const s=e(...t.map(n=>n.value))??null;return ia(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Xe=`
17
- `,FM="{%- ",LM=" -%}";function IM(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 OM(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Ut(e.body,0,r).replace(/\n$/,"")}function st(...e){return FM+e.join(" ")+LM}function Ut(e,t,r){return e.map(s=>NM(s,t,r)).join(Xe)}function NM(e,t,r){const s=r.repeat(t);switch(e.type){case"Program":return Ut(e.body,t,r);case"If":return DM(e,t,r);case"For":return zM(e,t,r);case"Set":return BM(e,t,r);case"Macro":return RM(e,t,r);case"Break":return s+st("break");case"Continue":return s+st("continue");case"CallStatement":return GM(e,t,r);case"FilterStatement":return $M(e,t,r);case"Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+ve(e)+" -}}"}}function DM(e,t,r){const s=r.repeat(t),n=[];let a=e;for(;a&&(n.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=s+st("if",ve(n[0].test))+Xe+Ut(n[0].body,t+1,r);for(let i=1;i<n.length;++i)o+=Xe+s+st("elif",ve(n[i].test))+Xe+Ut(n[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=Xe+s+st("else")+Xe+Ut(a.alternate,t+1,r)),o+=Xe+s+st("endif"),o}function zM(e,t,r){const s=r.repeat(t);let n="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;n=`${ve(o.lhs)} if ${ve(o.test)}`}else n=ve(e.iterable);let a=s+st("for",ve(e.loopvar),"in",n)+Xe+Ut(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Xe+s+st("else")+Xe+Ut(e.defaultBlock,t+1,r)),a+=Xe+s+st("endfor"),a}function BM(e,t,r){const s=r.repeat(t),n=ve(e.assignee),a=e.value?ve(e.value):"",o=s+st("set",`${n}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Xe+Ut(e.body,t+1,r)+Xe+s+st("endset")}function RM(e,t,r){const s=r.repeat(t),n=e.args.map(ve).join(", ");return s+st("macro",`${e.name.value}(${n})`)+Xe+Ut(e.body,t+1,r)+Xe+s+st("endmacro")}function GM(e,t,r){const s=r.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ve).join(", ")})`:"",a=ve(e.call);let o=s+st(`call${n}`,a)+Xe;return o+=Ut(e.body,t+1,r)+Xe,o+=s+st("endcall"),o}function $M(e,t,r){const s=r.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:ve(e.filter);let a=s+st("filter",n)+Xe;return a+=Ut(e.body,t+1,r)+Xe,a+=s+st("endfilter"),a}function ve(e,t=-1){switch(e.type){case"SpreadExpression":return`*${ve(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":{const r=e,s=IM(r),n=ve(r.left,s),a=ve(r.right,s+1),o=`${n} ${r.operator.value} ${a}`;return s<t?`(${o})`:o}case"UnaryExpression":{const r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+ve(r.argument,1/0)}case"CallExpression":{const r=e,s=r.args.map(ve).join(", ");return`${ve(r.callee)}(${s})`}case"MemberExpression":{const r=e;let s=ve(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ve(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{const r=e,s=ve(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ve(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{const r=e;return`${ve(r.lhs)} if ${ve(r.test)}`}case"TestExpression":{const r=e;return`${ve(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const r=e.value.map(ve),s=e.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([s,n])=>`${ve(s)}: ${ve(n)}`).join(", ")}}`;case"SliceExpression":{const r=e,s=r.start?ve(r.start):"",n=r.stop?ve(r.stop):"",a=r.step?`:${ve(r.step)}`:"";return`${s}:${n}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${ve(r.value)}`}case"Ternary":{const r=e,s=`${ve(r.trueExpr)} if ${ve(r.condition,0)} else ${ve(r.falseExpr)}`;return t>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var VM=class{constructor(e){k(this,"parsed");const t=J0(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=bM(t)}render(e){const t=new Qr;if(SM(t),e)for(const[n,a]of Object.entries(e))t.set(n,a);return new PM(t).run(this.parsed).value}format(e){return OM(this.parsed,(e==null?void 0:e.indent)||" ")}},UM={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"},la=class Iv{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=Tt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=Tt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const s=Tt.createReadStream(t);this.body=new ReadableStream({start(n){s.on("data",a=>n.enqueue(a)),s.on("end",()=>n.close()),s.on("error",a=>n.error(a))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",UM[t]??"application/octet-stream")}clone(){let t=new Iv(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await Tt.promises.readFile(this.filePath)).buffer}async blob(){const t=await Tt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await Tt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},ca=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(fe.IS_CRYPTO_AVAILABLE){const o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;const t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,s=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))s.push(o&4294967295);s.length||s.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let n=1,a=0;for(let o=Math.max(624,s.length);o>0;--o,++n,++a)n>=624&&(t[0]=t[623],n=1),a>=s.length&&(a=0),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1664525))+s[a]+a>>>0;for(let o=623;o>0;--o,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1566083941))-n>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const s=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^s>>>1^(s&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const s=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(s)*n,this._gauss_next=Math.sin(s)*n}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let s=this._int32()>>>32-r;for(;s>t;)s=this._int32()>>>32-r;const n=e[t];e[t]=e[s],e[s]=n}}choices(e,t){return e[vf(this._random_fn,t)]}};function vf(e,t){let r=0;for(let n=0;n<t.length;++n)r+=t[n];let s=e()*r;for(let n=0;n<t.length;++n)if(s-=t[n],s<0)return n;return t.length-1}var Zt=new ca,yi=Object.freeze({Random:ca,seed:Zt.seed.bind(Zt),random:Zt.random.bind(Zt),gauss:Zt.gauss.bind(Zt),shuffle:Zt.shuffle.bind(Zt),choices:Zt.choices.bind(Zt)}),jM=e=>vf(yi.random,e),qM=new ca,yf=class{constructor(e){this.path=e}async match(e){let t=Yt.join(this.path,e),r=new la(t);if(r.exists)return r}async put(e,t,r=void 0){const s=Yt.join(this.path,e),n=fe.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=qM._int32().toString(36),o=s+`.tmp.${n}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let c=0;await Tt.promises.mkdir(Yt.dirname(s),{recursive:!0});const d=Tt.createWriteStream(o),h=t.body.getReader();for(;;){const{done:_,value:p}=await h.read();if(_)break;await new Promise((v,y)=>{d.write(p,M=>{if(M){y(M);return}v()})}),c+=p.length;const w=l?c/l*100:0;r==null||r({progress:w,loaded:c,total:l})}await new Promise((_,p)=>{d.close(w=>w?p(w):_())}),await Tt.promises.rename(o,s)}catch(i){try{await Tt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=Yt.join(this.path,e);try{return await Tt.promises.unlink(t),!0}catch{return!1}}},WM={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"},bf=100,HM=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function ua(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function us(e,t=null,r=null){let s;try{s=new URL(e)}catch{return!1}return!(t&&!t.includes(s.protocol)||r&&!r.includes(s.hostname))}function QM(e){return!(!HM.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function XM(e,t,r){if(!r)return null;const s=WM[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}async function YM(e,t,r){const s=e.headers.get("Content-Length");let n=s?parseInt(s,10):r??0;s===null&&!r&&ue.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(n),o=0;const i=e.body.getReader();async function l(){const{done:c,value:d}=await i.read();if(c)return;const h=o+d.length;if(h>n){n=h;const p=new Uint8Array(n);p.set(a),a=p}a.set(d,o),o=h;const _=o/n*100;return t({progress:_,loaded:o,total:n}),l()}return await l(),a}function Mf(e){return us(e,["blob:"])}function xf(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof{url:self.location.href}<"u"&&self.location.href)t=self.location.href;else return e;return new URL(e,t).href}var kf="SHA-256",JM="experimental_transformers-hash-cache",Tf=e=>({algorithm:kf,value:e}),Ef=(cu=class{constructor(){yo(this,vn,null);k(this,"_getHashCache",()=>(_t(this,vn)??bo(this,vn,caches.open(JM)),_t(this,vn)));k(this,"match",async e=>{const t=await this._getFileHash(e);if(t)try{const[r]=await navigator.crossOriginStorage.requestFileHandles([Tf(t)]),s=await r.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}});k(this,"put",async(e,t)=>{const r=await this._getFileHash(e);if(r){const s=await t.blob();await this._storeBlobInCOS(s,r)}else this._processAndStore(e,t.body)});k(this,"_storeBlobInCOS",async(e,t)=>{const[r]=await navigator.crossOriginStorage.requestFileHandles([Tf(t)],{create:!0}),s=await r.createWritable();await s.write(e),await s.close()});k(this,"_processAndStore",async(e,t)=>{try{const r=[];for await(const a of t)r.push(a);const s=new Blob(r),n=await this._getBlobHash(s);await this._storeBlobInCOS(s,n);try{await(await this._getHashCache()).put(e,new Response(n))}catch{}}catch{}});k(this,"delete",async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}});k(this,"_getFileHash",async e=>{try{const t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();const s=await this._getLfsFileHash(e);return s?(await t.put(e,new Response(s)),s):null}catch{return null}});k(this,"_getLfsFileHash",async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const s=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return s?s[1]:null}catch{return null}});k(this,"_getBlobHash",async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(kf,t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")})}},vn=new WeakMap,k(cu,"isAvailable",()=>typeof navigator<"u"&&"crossOriginStorage"in navigator),cu);async function bi(e=null){let t=null;if(be.useCustomCache){if(!be.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!be.customCache.match||!be.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=be.customCache}if(!t&&be.experimental_useCrossOriginStorage&&Ef.isAvailable()&&(t=new Ef),!t&&be.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(be.cacheKey)}catch(r){ue.warn("An error occurred while opening the browser cache:",r)}}if(!t&&be.useFSCache){if(!fe.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new yf(e??be.cacheDir)}return t}async function KM(e,...t){for(let r of t)try{let s=await e.match(r);if(s)return s}catch{continue}}var ZM=(yg=class{constructor(e){yo(this,yn);yo(this,ft);bo(this,yn,e),bo(this,ft,new Map)}get(e){if(!_t(this,ft).has(e))return;const t=_t(this,ft).get(e);return _t(this,ft).delete(e),_t(this,ft).set(e,t),t}put(e,t){_t(this,ft).has(e)&&_t(this,ft).delete(e),_t(this,ft).set(e,t),_t(this,ft).size>_t(this,yn)&&_t(this,ft).delete(_t(this,ft).keys().next().value)}delete(e){return _t(this,ft).delete(e)}clear(){_t(this,ft).clear()}},yn=new WeakMap,ft=new WeakMap,yg),ex=100,Mi=new ZM(ex);function Af(e,t){const r=Mi.get(e);if(r!==void 0)return r;const s=t().then(n=>n,n=>(Mi.delete(e),Promise.reject(n)));return Mi.put(e,s),s}async function tx(e){if(!us(e,["http:","https:"]))return null;const t=Cf(e);return t.set("Range","bytes=0-0"),be.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function tn(e,t,r={}){const s=JSON.stringify([e,t,r==null?void 0:r.revision,r==null?void 0:r.cache_dir,r==null?void 0:r.local_files_only]);return Af(s,()=>rx(e,t,r))}async function rx(e,t,r){var c;const s=await bi(r==null?void 0:r.cache_dir),{localPath:n,remoteURL:a,proposedCacheKey:o,validModelId:i}=Sf(e,t,r,s),l=await Pf(s,n,o);if(l!==void 0&&typeof l!="string"){const d=l.headers.get("content-length"),h=l.headers.get("content-type");return{exists:!0,size:d?parseInt(d,10):void 0,contentType:h||void 0,fromCache:!0}}if(be.allowLocalModels&&!us(n,["http:","https:"]))try{const h=await rn(n);if(typeof h!="string"&&h.status!==404){const _=h.headers.get("content-length"),p=h.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:p||void 0,fromCache:!1}}}catch{}if(be.allowRemoteModels&&!r.local_files_only&&i)try{const d=await tx(a);if(d&&d.status>=200&&d.status<300){let h;const _=d.headers.get("content-type");if(d.status===206){const p=d.headers.get("content-range");if(p){const w=p.match(/bytes \d+-\d+\/(\d+)/);w&&(h=parseInt(w[1],10))}}else if(d.status===200)try{await((c=d.body)==null?void 0:c.cancel())}catch{}if(h===void 0){const p=d.headers.get("content-length");h=p?parseInt(p,10):void 0}return{exists:!0,size:h,contentType:_||void 0,fromCache:!1}}}catch(d){ue.warn(`Unable to fetch file metadata for "${a}": ${d}`)}return{exists:!1,fromCache:!1}}async function rn(e){return be.useFS&&!us(e,["http:","https:","blob:"])?new la(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):be.fetch(e,{headers:Cf(e)})}function Cf(e){var s;const t=typeof process<"u"&&((s=process==null?void 0:process.release)==null?void 0:s.name)==="node",r=new Headers;if(t){const n=!!(cr!=null&&cr.TESTING_REMOTELY),a=be.version;if(r.set("User-Agent",`transformers.js/${a}; is_ci/${n};`),us(e,["http:","https:"],["huggingface.co","hf.co"])){const i=(cr==null?void 0:cr.HF_TOKEN)??(cr==null?void 0:cr.HF_ACCESS_TOKEN);i&&r.set("Authorization",`Bearer ${i}`)}}return r}function Sf(e,t,r={},s=null){const n=r.revision??"main",a=ua(e,t),o=QM(e),i=o?ua(be.localModelPath,a):a,l=ua(be.remoteHost,be.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),c=s instanceof yf?n==="main"?a:ua(e,n,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function Pf(e,t,r){if(e)return await KM(e,t,r)}async function sx(e,t,r,s,n,a,o={}){if(await r.match(s)===void 0)if(a){if(typeof n!="string"){const i=new Headers(n.headers);i.set("content-length",a.byteLength.toString()),await r.put(s,new Response(a,{headers:i})).catch(l=>{ue.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>Pr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(s,n,i)}}async function nx(e,t,r=!0,s={},n=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=Sf(e,t,s,a);let h,_=!1,p;p=await Pf(a,i,c);const w=p!==void 0;if(w)h=c;else{if(be.allowLocalModels)if(us(o,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!be.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{p=await rn(i),h=i}catch(T){ue.warn(`Unable to load from local path "${i}": "${T}"`)}if(p===void 0||typeof p!="string"&&p.status===404){if(s.local_files_only||!be.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await rn(l),p.status!==200)return XM(p.status,l,r);h=c}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200}Pr(s.progress_callback,{status:"download",name:e,file:t});let v;if(!(fe.IS_NODE_ENV&&n)){let M;if(typeof p!="string")if(!s.progress_callback)M=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))M=new Uint8Array(await p.arrayBuffer()),Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M.length,total:M.length});else{let T;const A=p.headers.get("content-length");if(A)T=parseInt(A,10);else try{const C=await tn(e,t,s);C.size&&(T=C.size)}catch{}M=await YM(p,C=>{Pr(s.progress_callback,{status:"progress",name:e,file:t,...C})},T)}v=M}if(_&&h&&typeof p!="string"&&await sx(e,t,a,h,p,v,s),fe.IS_NODE_ENV&&n&&s.progress_callback&&typeof p!="string"){const M=parseInt(p.headers.get("content-length"),10)||0;Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M,total:M})}if(Pr(s.progress_callback,{status:"done",name:e,file:t}),v){if(!fe.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return v}if(p instanceof la)return p.filePath;const y=await(a==null?void 0:a.match(h));if(y instanceof la)return y.filePath;if(y instanceof Response)return new Uint8Array(await y.arrayBuffer());if(typeof y=="string")return y;throw new Error("Unable to get model file path or buffer.")}var da=new Map;async function ha(e,t,r=!0,s={},n=!1){if(!be.allowLocalModels){if(s.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(!be.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Pr(s.progress_callback,{status:"initiate",name:e,file:t});const a=`${e}::${t}`;let o=da.get(a);if(!o){const i=await bi(s==null?void 0:s.cache_dir);o=nx(e,t,r,s,n,i).then(l=>(da.delete(a),l),l=>{throw da.delete(a),l}),da.set(a,o)}return await o}async function xi(e,t,r=!0,s={}){const n=await ha(e,t,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function er(e,t,r=!0,s={}){const n=await xi(e,t,r,s);return n===null?{}:JSON.parse(n)}function ax(e,[t,r,s],[n,a],o="bilinear",i=!1){const l=a/s,c=n/r,d=new e.constructor(n*a*t),h=r*s,_=n*a;for(let p=0;p<n;++p)for(let w=0;w<a;++w){const v=p*a+w,y=(w+.5)/l-.5,M=(p+.5)/c-.5;let T=Math.floor(y),A=Math.floor(M);const C=Math.min(T+1,s-1),S=Math.min(A+1,r-1);T=Math.max(T,0),A=Math.max(A,0);const N=y-T,x=M-A,R=(1-N)*(1-x),z=N*(1-x),$=(1-N)*x,Q=N*x,H=A*s,D=S*s,I=H+T,te=H+C,W=D+T,ee=D+C;for(let G=0;G<t;++G){const L=G*h;d[G*_+v]=R*e[L+I]+z*e[L+te]+$*e[L+W]+Q*e[L+ee]}}return d}function ox(e,t,r){const s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=t[r[i]],l*=s[i];const a=r.map((i,l)=>n[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);o[l]=e[i]}return[o,s]}function nt(e){const t=je(e)[0],r=e.map(a=>Math.exp(a-t)),s=r.reduce((a,o)=>a+o,0);return r.map(a=>a/s)}function ix(e){const t=je(e)[0];let r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);const s=Math.log(r);return e.map(a=>a-t-s)}function ki(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}function je(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]>t&&(t=e[s],r=s);return[t,r]}function Ff(e){return e>0&&(e&e-1)===0}var Lf=class{constructor(e){if(this.size=e|0,this.size<=1||!Ff(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;r<this.table.length;r+=2){const s=Math.PI*r/this.size;this.table[r]=Math.cos(s),this.table[r+1]=-Math.sin(s)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let s=0;s<this._width;s+=2){const n=this._width-s-2;this._bitrev[r]|=(r>>>s&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const r=t||new Array(e.length>>>1);for(let s=0;s<e.length;s+=2)r[s>>>1]=e[s];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let s=0;s<r.length;s+=2)r[s]=e[s>>>1],r[s+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size}_transform4(e,t,r){const s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const h=c[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<s;i+=o,++l){const h=c[l];this._singleTransform4(t,e,i,h,a,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;const h=o>>>2;for(i=0;i<s;i+=o){const _=i+h-1;for(let p=i,w=0;p<_;p+=2,w+=a){const v=p,y=v+h,M=y+h,T=M+h,A=e[v],C=e[v+1],S=e[y],N=e[y+1],x=e[M],R=e[M+1],z=e[T],$=e[T+1],Q=d[w],H=r*d[w+1],D=S*Q-N*H,I=S*H+N*Q,te=d[2*w],W=r*d[2*w+1],ee=x*te-R*W,G=x*W+R*te,L=d[3*w],V=r*d[3*w+1],X=z*L-$*V,J=z*V+$*L,we=A+ee,re=C+G,Fe=A-ee,qe=C-G,bt=D+X,It=I+J,Ot=r*(D-X),Qe=r*(I-J);e[v]=we+bt,e[v+1]=re+It,e[y]=Fe+Qe,e[y+1]=qe-Ot,e[M]=we-bt,e[M+1]=re-It,e[T]=Fe-Qe,e[T+1]=qe+Ot}}}}_singleTransform2(e,t,r,s,n){const a=e[s],o=e[s+1],i=e[s+n],l=e[s+n+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+1],d=e[s+n],h=e[s+n+1],_=e[s+o],p=e[s+o+1],w=e[s+i],v=e[s+i+1],y=l+_,M=c+p,T=l-_,A=c-p,C=d+w,S=h+v,N=a*(d-w),x=a*(h-v);t[r]=y+C,t[r+1]=M+S,t[r+2]=T+x,t[r+3]=A-N,t[r+4]=y-C,t[r+5]=M-S,t[r+6]=T-x,t[r+7]=A+N}_realTransform4(e,t,r){const s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<s;i+=o,++l){const _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;const _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<s;i+=o)for(let v=0,y=0;v<=w;v+=2,y+=a){const M=i+v,T=M+p,A=T+p,C=A+p,S=e[M],N=e[M+1],x=e[T],R=e[T+1],z=e[A],$=e[A+1],Q=e[C],H=e[C+1],D=S,I=N,te=d[y],W=r*d[y+1],ee=x*te-R*W,G=x*W+R*te,L=d[2*y],V=r*d[2*y+1],X=z*L-$*V,J=z*V+$*L,we=d[3*y],re=r*d[3*y+1],Fe=Q*we-H*re,qe=Q*re+H*we,bt=D+X,It=I+J,Ot=D-X,Qe=I-J,pt=ee+Fe,Me=G+qe,ce=r*(ee-Fe),Pe=r*(G-qe);if(e[M]=bt+pt,e[M+1]=It+Me,e[T]=Ot+Pe,e[T+1]=Qe-ce,v===0){e[A]=bt-pt,e[A+1]=It-Me;continue}if(v===w)continue;const mt=i+p-v,nr=i+_-v;e[mt]=Ot-r*Pe,e[mt+1]=-Qe-r*ce,e[nr]=bt-r*pt,e[nr+1]=-It+r*Me}}const h=s>>>1;for(let _=2;_<h;_+=2)e[s-_]=e[_],e[s-_+1]=-e[_+1]}_singleRealTransform2(e,t,r,s,n){const a=e[s],o=e[s+n];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+n],d=e[s+o],h=e[s+i],_=l+d,p=l-d,w=c+h,v=a*(c-h);t[r]=_+w,t[r+1]=0,t[r+2]=p,t[r+3]=-v,t[r+4]=_-w,t[r+5]=0,t[r+6]=p,t[r+7]=v}},lx=class{constructor(e){const t=2*(e-1),r=2*(2*e-1),s=2**Math.ceil(Math.log2(r));this.bufferSize=s,this._a=t;const n=new Float64Array(r),a=new Float64Array(s);this._chirpBuffer=new Float64Array(s),this._buffer1=new Float64Array(s),this._buffer2=new Float64Array(s),this._outBuffer1=new Float64Array(s),this._outBuffer2=new Float64Array(s);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){const d=(c+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),p=2*c;n[p]=h*Math.cos(_),n[p+1]=h*Math.sin(_),a[p]=n[p],a[p+1]=-n[p+1]}this._slicedChirpBuffer=n.subarray(t,r),this._f=new Lf(s>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const s=this._buffer1,n=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(r)for(let d=0;d<l.length;d+=2){const h=d+1,_=d>>1,p=t[_];s[d]=p*l[d],s[h]=p*l[h]}else for(let d=0;d<l.length;d+=2){const h=d+1;s[d]=t[d]*l[d]-t[h]*l[h],s[h]=t[d]*l[h]+t[h]*l[d]}this._f.transform(a,s);for(let d=0;d<i.length;d+=2){const h=d+1;n[d]=a[d]*i[d]-a[h]*i[h],n[h]=a[d]*i[h]+a[h]*i[d]}this._f.inverseTransform(o,n);for(let d=0;d<o.length;d+=2){const h=o[d+c],_=o[d+c+1],p=l[d],w=l[d+1];e[d]=h*p-_*w,e[d+1]=h*w+_*p}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},cx=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Ff(e),this.isPowerOfTwo?(this.fft=new Lf(e),this.outputBufferSize=2*e):(this.fft=new lx(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function ux(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const r=new e.constructor(e.length),s=new e.constructor(t),n=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-n;i<=n;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),s[o++]=e[l]}s.sort(),r[a]=s[n]}return r}function sn(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function dx(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function hx(e){const t=e.length,r=e[0].length,s=[t+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;const a=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let d=1;d<s[1];++d)for(let h=1;h<s[0];++h){const _=n[h-1][d-1],p=n[h-1][d],w=n[h][d-1];let v,y;_<p&&_<w?(v=_,y=0):p<_&&p<w?(v=p,y=1):(v=w,y=2),n[h][d]=e[h-1][d-1]+v,a[h][d]=y}for(let d=0;d<s[1];++d)a[0][d]=2;for(let d=0;d<s[0];++d)a[d][0]=1;let o=t,i=r,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var fx=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0;const d=(l&32768)<<16,h=(l&31744)>>10;let _=l&1023;if(h===31)c=d|2139095040|_<<13;else if(h===0)if(_===0)c=d;else{let p=113;for(;(_&1024)===0;)_<<=1,--p;_&=-1025,c=d|p<<23|_<<13}else c=d|h+112<<23|_<<13;o[0]=c,e[l]=i[0]}}const r=t.length,s=e,n=new Float32Array(r);for(let a=0;a<r;++a)n[a]=s[t[a]];return n}})(),If={};os(If,{default:()=>_x});var _x={};async function Of(e){const t=e.split("/").pop();let r;try{if(r=await bi(),r){const n=await r.match(e);if(n)return n}}catch(n){ue.warn(`Failed to load ${t} from cache:`,n)}const s=await be.fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone())}catch(n){ue.warn(`Failed to cache ${t}:`,n)}return s}async function px(e){const t=await Of(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ue.warn("Failed to read WASM binary:",r),null}}async function mx(e){if(fe.IS_SERVICE_WORKER_ENV||fe.IS_CHROME_AVAILABLE)return e;const t=await Of(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ue.warn("Failed to read WASM factory:",r),null}}var gx=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 Nf(e){return e<=Bt.DEBUG?0:e<=Bt.INFO?2:e<=Bt.WARNING||e<=Bt.ERROR?3:4}var wx={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ft=[],Ti,Fr,Df=Symbol.for("onnxruntime");if(Df in globalThis)Fr=globalThis[Df];else if(fe.IS_NODE_ENV){switch(Fr=If,process.platform){case"win32":Ft.push("dml");break;case"linux":process.arch==="x64"&&Ft.push("cuda");break;case"darwin":Ft.push("coreml");break}Ft.push("webgpu"),Ft.push("cpu"),Ti=["cpu"]}else Fr=iy,fe.IS_WEBNN_AVAILABLE&&Ft.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),fe.IS_WEBGPU_AVAILABLE&&Ft.push("webgpu"),Ft.push("wasm"),Ti=["wasm"];var vx=Fr.InferenceSession;function yx(e=null){if(!e)return Ti;switch(e){case"auto":return Ft;case"gpu":return Ft.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(Ft.includes(e))return[gx[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Ft.join(", ")}.`)}var zf=Promise.resolve(),ds=null;async function bx(){var t,r,s,n,a;if(ds)return ds;if(!(be.useWasmCache&&typeof((t=Ie==null?void 0:Ie.wasm)==null?void 0:t.wasmPaths)=="object"&&((s=(r=Ie==null?void 0:Ie.wasm)==null?void 0:r.wasmPaths)==null?void 0:s.wasm)&&((a=(n=Ie==null?void 0:Ie.wasm)==null?void 0:n.wasmPaths)==null?void 0:a.mjs))){if(fe.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return ds=Promise.resolve(),ds}return ds=(async()=>{const o=Ie.wasm.wasmPaths;let i=!1;await Promise.all([o.wasm&&!Mf(o.wasm)?(async()=>{try{const l=await px(xf(o.wasm));l&&(Ie.wasm.wasmBinary=l,i=!0)}catch(l){ue.warn("Failed to pre-load WASM binary:",l)}})():Promise.resolve(),o.mjs&&!Mf(o.mjs)?(async()=>{try{const l=await mx(xf(o.mjs));l&&(Ie.wasm.wasmPaths.mjs=l)}catch(l){ue.warn("Failed to pre-load WASM factory:",l)}})():Promise.resolve()]),i||(Ie.wasm.wasmPaths.mjs=o.mjs)})(),ds}async function Bf(e,t,r){await bx();const s=Nf(be.logLevel??Bt.WARNING),n=()=>vx.create(e,{logSeverityLevel:s,...t}),a=await(fe.IS_WEB_ENV?zf=zf.then(n):n());return a.config=r,a}var Rf=Promise.resolve();async function Gf(e,t){const r=()=>e.run(t);return fe.IS_WEB_ENV?Rf=Rf.then(r):r()}function $f(e){return e instanceof Fr.Tensor}var Ie=Fr==null?void 0:Fr.env;function Ei(){var e;return(e=Ie==null?void 0:Ie.wasm)==null?void 0:e.proxy}if(Ie){let e=function(t){const r=Nf(t);Ie.logLevel=wx[r]};if(Ie.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&((bg=Ie.versions)!=null&&bg.web)&&!Ie.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ie.versions.web}/dist/`;Ie.wasm.wasmPaths=fe.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}Ie.wasm.proxy=!1}Ie.webgpu&&(Ie.webgpu.powerPreference="high-performance"),e(be.logLevel??Bt.WARNING),be.backends.onnx={...Ie,setLogLevel:e}}var Lr=async(e,t,r)=>{const s=await Bf(new Uint8Array(e),t);return(async n=>{const a=Ei(),o=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await Gf(s,o);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},hs=(uu=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Lr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Lr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Lr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Lr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Lr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Lr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Lr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Lr([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}},k(uu,"session_options",{}),uu),Mx=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"}),Ai=fe.IS_NODE_ENV?"cpu":"wasm";function Vf(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Ai}).`),Ai):Ai}var xx=(function(){let e;return async function(){if(e===void 0)if(!fe.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),We=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),Uf=We.fp32,jf=Object.freeze({[Mx.wasm]:We.q8}),Ci=Object.freeze({[We.fp32]:"",[We.fp16]:"_fp16",[We.int8]:"_int8",[We.uint8]:"_uint8",[We.q8]:"_quantized",[We.q4]:"_q4",[We.q2]:"_q2",[We.q1]:"_q1",[We.q4f16]:"_q4f16",[We.q2f16]:"_q2f16",[We.q1f16]:"_q1f16",[We.bnb4]:"_bnb4"});function qf(e,t,r,{configDtype:s=null,warn:n}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===We.auto){if(s){const l=typeof s=="string"?s:s==null?void 0:s[t];if(l&&l!==We.auto&&We.hasOwnProperty(l))return l}i=jf[r]??Uf}else a&&We.hasOwnProperty(a)?i=a:i=jf[r]??Uf;return o&&n&&n(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var fs=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),U=class Ue{constructor(...t){k(this,"ort_tensor");return $f(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new wy(t[0],t[1],t[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const s=r.reduce((n,a)=>n*a);for(let n=0;n<t;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(t){const[r,...s]=this.dims;if(t=tr(t,r),s.length>0){const n=s.reduce((a,o)=>a*o);return this._subarray(t,n,s)}else return new Ue(this.type,[this.data[t]],s)}indexOf(t){const r=this.data;for(let s=0;s<r.length;++s)if(r[s]==t)return s;return-1}_subarray(t,r,s){const n=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new Ue(this.type,o,s)}item(){const t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return kx(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]=t(r[s],s,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]-=t;return this}clone(){return new Ue(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],s=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=tr(h,this.dims[d],d),s.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[_,p]=h;if(_=_===null?0:tr(_,this.dims[d],d,!1),p=p===null?this.dims[d]:tr(p,this.dims[d],d,!1),_>p)throw new Error(`Invalid slice: ${h}`);const w=[Math.max(_,0),Math.min(p,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${h}`)}const n=s.map(([d,h])=>h-d),a=n.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride();let c=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){c=!1;break}if(c){const d=s[0][0]*l[0],h=s[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,h));else if(Array.isArray(o)){const _=o.slice(d,h);for(let p=0;p<_.length;++p)i[p]=_[p]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let h=0;for(let _=n.length-1,p=d;_>=0;--_){const w=n[_];h+=(p%w+s[_][0])*l[_],p=Math.floor(p/w)}i[d]=o[h]}return new Ue(this.type,i,r)}permute(...t){return Tx(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,s=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const n=this.data,a=n instanceof BigInt64Array||n instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a?(o=(h,_)=>h+_,i=0n):(o=(h,_)=>h+_**t,i=0),r===null){let h=n.reduce(o,i);return t!==1&&(h=h**(1/t)),new Ue(this.type,[h],[])}const[l,c,d]=nn(o,this,r,s);if(t!==1)for(let h=0;h<c.length;++h)c[h]=c[h]**(1/t);return new Ue(l,c,d)}normalize_(t=2,r=1){r=tr(r,this.dims.length);const s=this.norm(t,r,!0),n=this.data,a=s.data;for(let o=0;o<n.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){const h=this.dims[l];if(l!==r){const _=c%h;i+=_*d,d*=this.dims[l]}c=Math.floor(c/h)}n[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Pi(this.dims)}squeeze(t=null){return new Ue(this.type,this.data,Qf(this.dims,t))}squeeze_(t=null){return this.dims=Qf(this.dims,t),this}unsqueeze(t){return new Ue(this.type,this.data,Xf(this.dims,t))}unsqueeze_(t){return this.dims=Xf(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,t),n=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...s,n.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let n=0;n<t.length;++n)if(t[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}const s=this.data;if(r!==-1){const n=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=s.length/n}return new Ue(this.type,s,t)}neg_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>t?1:0;return new Ue("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<t?1:0;return new Ue("bool",r,this.dims)}clamp_(t,r){const s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return Si(this,t,r)}min(t=null,r=!1){if(t===null){const o=ki(this.data)[0];return new Ue(this.type,[o],[])}const[s,n,a]=nn((o,i)=>Math.min(o,i),this,t,r,1/0);return new Ue(s,n,a)}max(t=null,r=!1){if(t===null){const o=je(this.data)[0];return new Ue(this.type,[o],[])}const[s,n,a]=nn((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Ue(s,n,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=ki(this.data)[1];return new Ue("int64",[BigInt(s)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=je(this.data)[1];return new Ue("int64",[BigInt(s)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(d=>d===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,h=Array(d).fill(1).concat(this.dims);return new Ue(this.type,this.data.slice(),h)}const r=t.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((d,h)=>d*t[h]),a=n.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=Pi(s),c=Pi(n);for(let d=0;d<a;++d){let h=d,_=0;for(let p=0;p<n.length;++p){const w=Math.floor(h/c[p]);h=h%c[p];const v=w%s[p];_+=v*l[p]}i[d]=o[_]}return new Ue(this.type,i,n)}tile(...t){if(t.length<this.dims.length){const r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!fs.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r;const s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Ue(t,fx(this.data),this.dims);return new Ue(t,fs[t].from(this.data,r),this.dims)}};function kx(e,t){const r=e.length,s=t.reduce((a,o)=>a*o);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let a=t.length-1;a>=0;a--)n=n.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return n[0]}function Tx(e,t){const[r,s]=ox(e.data,e.dims,t);return new U(e.type,r,s)}function Wf(e,[t,r],s="bilinear",n=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=ax(e.data,[a,o,i],[t,r],s,n);return new U(e.type,l,[a,t,r])}async function jt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(t.length===2)s=[...e.dims.slice(0,2),...t];else if(t.length===3)s=[e.dims[0],...t];else if(t.length===4)s=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await hs.nearest_interpolate_4d;else if(r==="bilinear")n=await hs.bilinear_interpolate_4d;else if(r==="bicubic")n=await hs.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new U("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:e,s:a})}async function Ex(e,t){return await(await hs.matmul)({a:e,b:t})}async function _s(e,t){const r=await hs.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new U("int64",[BigInt(t)],[1])})}var fa=e=>new U("int64",e,[e.length]);async function Hf(e,t,r,s,n){return await(await hs.slice)({x:e,s:fa(t),e:fa(r),a:fa(s),t:fa(new Array(s.length).fill(1))})}function Ax(e,t){const r=e.data,s=t.data,n=[e.dims[0],e.dims[2]],a=new r.constructor(n[0]*n[1]),[o,i,l]=e.dims;let c=0;for(let d=0;d<o;++d){const h=d*l*i;for(let _=0;_<l;++_){let p=0,w=0;const v=d*i,y=h+_;for(let T=0;T<i;++T){const A=Number(s[v+T]);w+=A,p+=r[y+T*l]*A}const M=p/w;a[c++]=M}}return new U(e.type,a,n)}function Qf(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,s)=>r!==1||!t.includes(s))),e}function Xf(e,t){return t=tr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function tr(e,t,r=null,s=!0){if(e<-t||e>=t){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function ze(e,t=0){t=tr(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const s=r.reduce((o,i)=>o*i,1),n=new e[0].data.constructor(s),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;n.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){const{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let h=0;for(let _=c.length-1,p=d,w=1;_>=0;--_){const v=c[_];let y=p%v;_===t&&(y+=o),h+=y*w,w*=r[_],p=Math.floor(p/v)}n[h]=l[d]}o+=c[t]}}return new U(a,n,r)}function dr(e,t=0){return ze(e.map(r=>r.unsqueeze(t)),t)}function nn(e,t,r,s=!1,n=null){const a=t.data,o=t.dims;r=tr(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);n!==null&&l.fill(n);for(let c=0;c<a.length;++c){let d=0;for(let h=o.length-1,_=c,p=1;h>=0;--h){const w=o[h];if(h!==r){const v=_%w;d+=v*p,p*=i[h]}_=Math.floor(_/w)}l[d]=e(l[d],a[c],c,d)}return s||i.splice(r,1),[t.type,l,i]}function Cx(e,t=null,r=1,s=!1){const n=e.data,a=e.dims;if(t===null){const p=n.reduce((M,T)=>M+T,0)/n.length,w=Math.sqrt(n.reduce((M,T)=>M+(T-p)**2,0)/(n.length-r)),v=new U(e.type,[p],[]);return[new U(e.type,[w],[]),v]}t=tr(t,a.length);const o=Si(e,t,s),i=o.data,[l,c,d]=nn((_,p,w,v)=>_+(p-i[v])**2,e,t,s);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return[new U(l,c,d),o]}function Si(e,t=null,r=!1){const s=e.dims,n=e.data;if(t===null){const l=n.reduce((c,d)=>c+d,0);return new U(e.type,[l/n.length],[])}t=tr(t,s.length);const[a,o,i]=nn((l,c)=>l+c,e,t,r);if(s[t]!==1)for(let l=0;l<o.length;++l)o[l]/=s[t];return new U(a,o,i)}function Pi(e){const t=new Array(e.length);for(let r=e.length-1,s=1;r>=0;--r)t[r]=s,s*=e[r];return t}function Fi(e,t,r,s){const n=e.reduce((a,o)=>a*o,1);return new U(r,new s(n).fill(t),e)}function ct(e,t){let r,s;if(typeof t=="number")r="float32",s=Float32Array;else if(typeof t=="bigint")r="int64",s=BigInt64Array;else if(typeof t=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Fi(e,t,r,s)}function Li(e,t){return ct(e.dims,t)}function yt(e){return Fi(e,1n,"int64",BigInt64Array)}function Yf(e){return yt(e.dims)}function Jf(e){return Fi(e,0n,"int64",BigInt64Array)}function Kf(e){return Jf(e.dims)}function Sx(e){const t=e.reduce((r,s)=>r*s,1);return new U("float32",Float32Array.from({length:t},()=>yi.gauss()),e)}function Px(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const r=t==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,a=e.data,o=new n(a.length/8);for(let i=0;i<a.length;++i){const l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,r&&d===0&&(o[c]-=128)}return new U(s,o,[e.dims[0],e.dims[1]/8])}async function Zf(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await tn(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function e_(e,t){const r=await Zf(e);return await Promise.all(r.map(s=>er(e,s,!0,t)))}function Ii(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Fx=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Lx(e,t,r,s){for(const n of Object.keys(e)){const a=t-e[n].length,o=r(n),i=new Array(a).fill(o);e[n]=s==="right"?Jt(e[n],i):Jt(i,e[n])}}function Ix(e,t){for(const r of Object.keys(e))e[r].length=t}function Xr(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const s=e[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function Ox(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var le=class extends vt{constructor(t,r){super();k(this,"return_token_type_ids",!1);k(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new H0(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Xr(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Xr(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Xr(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Xr(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Xr(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Xr(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const n=Object.create(null);for(const{name:a,template:o}of this.chat_template){if(typeof a!="string"||typeof o!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[a]=o}this.chat_template=n}this._compiled_template_cache=new Map;const s=Ox(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){const i=await e_(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,r={}){const{text_pair:s=null,add_special_tokens:n=!0,padding:a=!1,return_token_type_ids:o=null}=r;let{truncation:i=null,max_length:l=null}=r;const c=r.return_tensor??!0,d=Array.isArray(t);let h;if(d){if(t.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(t.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=t.map((p,w)=>this._encode_plus(p,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:o}))}else h=t.map(p=>this._encode_plus(p,{add_special_tokens:n,return_token_type_ids:o}))}else{if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(t,{text_pair:s,add_special_tokens:n,return_token_type_ids:o})]}if(l===null?l=this.model_max_length:i===null&&(a===!0?(ue.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):a===!1&&(ue.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)),a===!0&&(l=Math.min(je(h.map(p=>p.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),a||i)for(let p=0;p<h.length;++p)h[p].input_ids.length!==l&&(h[p].input_ids.length>l?i&&Ix(h[p],l):a&&Lx(h[p],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));const _={};if(c){if(!(a&&i)&&h.some(w=>{var v;for(const y of Object.keys(w))if(w[y].length!==((v=h[0][y])==null?void 0:v.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const p=[h.length,h[0].input_ids.length];for(const w of Object.keys(h[0]))_[w]=new U("int64",BigInt64Array.from(h.flatMap(v=>v[w]).map(BigInt)),p)}else{for(const p of Object.keys(h[0]))_[p]=h.map(w=>w[p]);if(!d)for(const p of Object.keys(_))_[p]=_[p][0]}return _}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){const{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:s})}encode(t,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(t,r={}){return t instanceof U&&(t=t.tolist()),t.map(s=>this.decode(s,r))}decode(t,r={}){if(t instanceof U&&(t=Ii(t)),!Array.isArray(t)||t.length===0||!Oy(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const s=this.chat_template;if(t!==null&&Object.hasOwn(s,t))t=s[t];else if(t===null)if(r!==null&&"tool_use"in s)t=s.tool_use;else if("default"in s)t=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(t===null)if(this.chat_template)t=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return t}apply_chat_template(t,r={}){let{tools:s=null,documents:n=null,chat_template:a=null,add_generation_prompt:o=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:d=null,return_tensor:h=!0,return_dict:_=!0,tokenizer_kwargs:p={},...w}=r;if(a=this.get_chat_template({chat_template:a,tools:s}),typeof a!="string")throw Error(`chat_template must be a string, but got ${typeof a}`);let v=this._compiled_template_cache.get(a);v===void 0&&(v=new VM(a),this._compiled_template_cache.set(a,v));const y=Object.create(null);for(const T of Fx){const A=Xr(this.config,T);A&&(y[T]=A)}const M=v.render({messages:t,add_generation_prompt:o,tools:s,documents:n,...y,...w});if(i){const T=this._call(M,{add_special_tokens:!1,padding:l,truncation:c,max_length:d,return_tensor:h,...p});return _?T:T.input_ids}return M}};function Oi(e,t,r,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const n=s.src_lang,a=s.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(n);break}}return s.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var t_={};os(t_,{AlbertTokenizer:()=>Nx,AutoTokenizer:()=>Te,BartTokenizer:()=>Dx,BertTokenizer:()=>zx,BlenderbotSmallTokenizer:()=>Bx,BlenderbotTokenizer:()=>Rx,BloomTokenizer:()=>Gx,CLIPTokenizer:()=>Vx,CamembertTokenizer:()=>$x,CodeGenTokenizer:()=>jx,CodeLlamaTokenizer:()=>Ux,CohereAsrTokenizer:()=>Wx,CohereTokenizer:()=>qx,ConvBertTokenizer:()=>Hx,DebertaTokenizer:()=>Xx,DebertaV2Tokenizer:()=>Qx,DistilBertTokenizer:()=>Yx,ElectraTokenizer:()=>Jx,EsmTokenizer:()=>Kx,FalconTokenizer:()=>Zx,GPT2Tokenizer:()=>r1,GPTNeoXTokenizer:()=>t1,GemmaTokenizer:()=>e1,HerbertTokenizer:()=>s1,LlamaTokenizer:()=>n1,M2M100Tokenizer:()=>a1,MBart50Tokenizer:()=>i1,MBartTokenizer:()=>r_,MPNetTokenizer:()=>u1,MarianTokenizer:()=>o1,MgpstrTokenizer:()=>l1,MobileBertTokenizer:()=>c1,NllbTokenizer:()=>d1,NougatTokenizer:()=>h1,PreTrainedTokenizer:()=>le,Qwen2Tokenizer:()=>f1,RoFormerTokenizer:()=>p1,RobertaTokenizer:()=>_1,SiglipTokenizer:()=>m1,SpeechT5Tokenizer:()=>g1,SqueezeBertTokenizer:()=>w1,T5Tokenizer:()=>v1,TokenizersBackend:()=>le,VitsTokenizer:()=>b1,Wav2Vec2CTCTokenizer:()=>M1,WhisperTokenizer:()=>A1,XLMRobertaTokenizer:()=>C1,XLMTokenizer:()=>S1});var Nx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Dx=class extends le{},zx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Bx=class extends le{},Rx=class extends le{},Gx=class extends le{},$x=class extends le{},Vx=class extends le{},Ux=class extends le{},jx=class extends le{},qx=class extends le{},Wx=class extends le{},Hx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Qx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Xx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Yx=class extends le{},Jx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Kx=class extends le{},Zx=class extends le{},e1=class extends le{},t1=class extends le{},r1=class extends le{},s1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},n1=class extends le{constructor(){super(...arguments);k(this,"padding_side","left")}},a1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},o1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),ue.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[s,n]=r;return this.supported_language_codes.includes(s)||ue.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Jt([s],super._encode_text(n))}}},r_=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},i1=class extends r_{},l1=class extends le{},c1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},u1=class extends le{},d1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},h1=class extends le{},f1=class extends le{},_1=class extends le{},p1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},m1=class extends le{},g1=class extends le{},w1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},v1=class extends le{},y1=class extends $t{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},b1=class extends le{constructor(e,t){super(e,t),this._tokenizer.decoder=new y1({type:"VitsDecoder"})}},M1=class extends le{},s_=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],_a=new Map(s_),x1=new Map([...s_.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function k1(e){e=e.toLowerCase();let t=x1.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),_a.has(e))t=e;else{const n=e.length===2?_a.keys():_a.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}var T1="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",n_=new RegExp(`^[${T1}]+$`,"gu"),E1=.1,A1=class extends le{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:n=!0}={}){if(s===null)throw Error("Must specify time_precision");let a=null;const o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let c=i(),d=0;const h=this.timestamp_begin,p=h+1500;let w=[],v=[],y=!1,M=null;const T=new Set(this.all_special_ids);for(const S of e){const N=S.tokens,x=o?S.token_timestamps:null;let R=null,z=h;if("stride"in S){const[H,D,I]=S.stride;if(d-=D,M=H-I,D&&(z=D/s+h),I)for(let te=N.length-1;te>=0;--te){const W=Number(N[te]);if(W>=h){if(R!==null&&(W-h)*s<M)break;R=W}}}let $=[],Q=[];for(let H=0;H<N.length;++H){const D=Number(N[H]);if(T.has(D)){const I=this.decode([D]),te=_a.get(I.slice(2,-2));if(te!==void 0){if(a!==null&&te!==a&&!t){w.push($);const W=this.findLongestCommonSequence(w)[0],ee=this.decode(W);c.text=ee,l.push(c),w=[],$=[],c=i()}a=c.language=te}}else if(D>=h&&D<=p){const I=(D-h)*s+d,te=sn(I,2);if(R!==null&&D>=R)y=!0;else if(y||w.length>0&&D<z)y=!1;else if(c.timestamp[0]===null)c.timestamp[0]=te;else if(te!==c.timestamp[0]){c.timestamp[1]=te,w.push($),o&&v.push(Q);const[W,ee]=this.findLongestCommonSequence(w,v),G=this.decode(W);if(c.text=G,o&&(c.words=this.collateWordTimestamps(W,ee,a),c.words.length>0&&c.timestamp[1]!==null))for(const L of c.words)L.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=L.timestamp[0]&&(L.timestamp[1]=c.timestamp[1]);l.push(c),w=[],$=[],v=[],Q=[],c=i()}}else if($.push(D),o){let I=sn(x[H]+d,2),te;if(H+1<x.length){te=sn(x[H+1]+d,2);const W=this.decode([D]);n_.test(W)&&(te=sn(Math.min(I+s,te),2))}else te=null;Q.push([I,te])}}if("stride"in S){const[H,D,I]=S.stride;d+=H-I}$.length>0?(w.push($),o&&v.push(Q)):w.every(H=>H.length===0)&&(c=i(),w=[],$=[],v=[],Q=[])}if(w.length>0){if(n&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[S,N]=this.findLongestCommonSequence(w,v),x=this.decode(S);c.text=x,o&&(c.words=this.collateWordTimestamps(S,N,a)),l.push(c)}let A=Object.create(null);const C=l.map(S=>S.text).join("");if(t||r){for(let S=0;S<l.length;++S){const N=l[S];t||delete N.timestamp,r||delete N.language}if(o){const S=[];for(const N of l)for(const x of N.words)S.push(x);A={chunks:S}}else A={chunks:l}}return[C,A]}findLongestCommonSequence(e,t=null){let r=e[0],s=r.length,n=[];const a=Array.isArray(t)&&t.length>0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,h=[s,s,0,0];const _=c.length;for(let A=1;A<s+_;++A){const C=Math.max(0,s-A),S=Math.min(s,s+_-A),N=r.slice(C,S),x=Math.max(0,A-s),R=Math.min(_,A),z=c.slice(x,R);if(N.length!==z.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let $;a?$=N.filter((D,I)=>D===z[I]&&i[C+I][0]-E1<=t[l][x+I][0]).length:$=N.filter((D,I)=>D===z[I]).length;const Q=A/1e4,H=$/A+Q;$>1&&H>d&&(d=H,h=[C,S,x,R])}const[p,w,v,y]=h,M=Math.floor((w+p)/2);let T=Math.floor((y+v)/2);if(a&&d===0&&s>0){const A=i[s-1][0],C=t[l].findIndex(S=>S[0]>=A);T=C===-1?c.length:C}n.push(...r.slice(0,M)),r=c.slice(T),s=r.length,a&&(o.push(...i.slice(0,M)),i=t[l].slice(T))}return n.push(...r),a?(o.push(...i),[n,o]):[n,[]]}collateWordTimestamps(e,t,r){const[s,n,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<s.length;++i){const l=a[i];o.push({text:s[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,s=`"'.。,,!!??::”)]}、`){t=t??"english";let n,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,a,o]=this.splitTokensOnUnicode(e):[n,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,a,o,r,s)}decode(e,t){let r;return t!=null&&t.decode_with_timestamps?(e instanceof U&&(e=Ii(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){const r=(t==null?void 0:t.time_precision)??.02,s=this.all_special_ids.at(-1)+1;let n=[[]];for(let a of e)if(a=Number(a),a>=s){const o=((a-s)*r).toFixed(2);n.push(`<|${o}|>`),n.push([])}else n[n.length-1].push(a);return n=n.map(a=>typeof a=="string"?a:super.decode(a,t)),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],n=[],a=[];let o=[],i=[],l=0;for(let c=0;c<e.length;++c){const d=e[c];o.push(d),i.push(c);const h=this.decode(o,{decode_with_timestamps:!0});(!h.includes(r)||t[l+h.indexOf(r)]===r)&&(s.push(h),n.push(o),a.push(i),o=[],i=[],l+=h.length)}return[s,n,a]}splitTokensOnSpaces(e){const[t,r,s]=this.splitTokensOnUnicode(e),n=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],c=r[i],d=s[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=n_.test(p);if(h||_||w||n.length===0)n.push(l),a.push(c),o.push(d);else{const v=n.length-1;n[v]+=l,a[v].push(...c),o[v].push(...d)}}return[n,a,o]}mergePunctuations(e,t,r,s,n){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(r);let l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&s.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=Jt(o[l],o[c]),i[c]=Jt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&n.includes(a[c])?(a[l]+=a[c],o[l]=Jt(o[l],o[c]),i[l]=Jt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},C1=class extends le{},S1=class extends le{constructor(t,r){super(t,r);k(this,"return_token_type_ids",!0);ue.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Te=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:a="main"}={}){var d;const[o,i]=await e_(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a}),l=((d=i.tokenizer_class)==null?void 0:d.replace(/Fast$/,""))??"PreTrainedTokenizer";let c=t_[l];return c||(ue.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=le),new c(o,i)}},pa="https://github.com/huggingface/transformers.js/issues/new/choose",Ni="preprocessor_config.json",an=Ni,a_="processor_config.json",o_="chat_template.jinja",Ee=(bn=class extends vt{constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([this.uses_processor_config?er(e,a_,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?xi(e,o_,!0,t):null]);return new this(r,s,n)}},k(bn,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),k(bn,"uses_processor_config",!1),k(bn,"uses_chat_template_file",!1),bn),Di={};os(Di,{ChatterboxProcessor:()=>nk,CohereAsrProcessor:()=>ok,Florence2Processor:()=>iT,Gemma3Processor:()=>lT,Gemma3nProcessor:()=>cT,Gemma4Processor:()=>uT,Glm46VProcessor:()=>dT,GraniteSpeechProcessor:()=>hT,GroundingDinoProcessor:()=>_T,Idefics3Processor:()=>U_,JinaCLIPProcessor:()=>vT,Lfm2VlProcessor:()=>yT,LlavaProcessor:()=>bT,MgpstrProcessor:()=>MT,MoonshineProcessor:()=>xT,OwlViTProcessor:()=>kT,PaliGemmaProcessor:()=>ET,Phi3VProcessor:()=>CT,PixtralProcessor:()=>ST,Processor:()=>Ee,PyAnnoteProcessor:()=>PT,Qwen2VLProcessor:()=>Hi,Qwen2_5_VLProcessor:()=>W_,Qwen3VLProcessor:()=>FT,Sam2Processor:()=>Q_,Sam2VideoProcessor:()=>LT,SamProcessor:()=>H_,SmolVLMProcessor:()=>U_,SpeechT5Processor:()=>IT,UltravoxProcessor:()=>OT,VLChatProcessor:()=>wT,VoxtralProcessor:()=>BT,VoxtralRealtimeProcessor:()=>$T,Wav2Vec2Processor:()=>VT,Wav2Vec2ProcessorWithLM:()=>UT,WhisperProcessor:()=>jT});var ut=class extends vt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await er(e,Ni,!0,t);return new this(r)}};function at(e,t){var r;if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${((r=e==null?void 0:e.constructor)==null?void 0:r.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 zi={};os(zi,{ASTFeatureExtractor:()=>j1,ChatterboxFeatureExtractor:()=>q1,ClapFeatureExtractor:()=>W1,CohereAsrFeatureExtractor:()=>Q1,DacFeatureExtractor:()=>__,EncodecFeatureExtractor:()=>h_,FeatureExtractor:()=>ut,Gemma3nAudioFeatureExtractor:()=>p_,Gemma4AudioFeatureExtractor:()=>m_,GraniteSpeechFeatureExtractor:()=>X1,MoonshineFeatureExtractor:()=>Y1,ParakeetFeatureExtractor:()=>f_,PyAnnoteFeatureExtractor:()=>g_,SeamlessM4TFeatureExtractor:()=>J1,SnacFeatureExtractor:()=>K1,SpeechT5FeatureExtractor:()=>Z1,VoxtralRealtimeFeatureExtractor:()=>rk,Wav2Vec2FeatureExtractor:()=>ek,WeSpeakerFeatureExtractor:()=>tk,WhisperFeatureExtractor:()=>sk});var P1=()=>{},F1=P1;async function i_(e,t){if(fe.IS_BROWSER_ENV){if(fe.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(fe.IS_FS_AVAILABLE)t.stream(),Tt.createWriteStream(e),await F1();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function L1(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const r=await(await rn(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});typeof t>"u"&&ue.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);const n=await s.decodeAudioData(r);let a;if(n.numberOfChannels===2){const o=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<n.length;++c)a[c]=o*(i[c]+l[c])/2}else a=n.getChannelData(0);return a}var I1=L1;function l_(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,s=2*Math.PI/(e-1),n=new Float64Array(e);for(let a=0;a<e;++a)n[a]=t-r*Math.cos(a*s);return n}function c_(e){return l_(e,.5)}function O1(e){return l_(e,.54)}var N1={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,s=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*s:3*e/200};function Bi(e,t="htk"){const r=N1[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}var D1={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?t*Math.exp(s*(e-r)):200*e/3};function z1(e,t="htk"){const r=D1[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}function B1(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),s=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const n=t.length-2,a=Array.from({length:n},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<n;++l){const c=-i[l]/r[l],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,d))}}return a}function u_(e,t,r){const s=(t-e)/(r-1);return Float64Array.from({length:r},(n,a)=>e+s*a)}function rr(e,t,r,s,n,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);const l=Bi(r,o),c=Bi(s,o),d=u_(l,c,t+2);let h=z1(d,o),_;if(i){const w=n/((e-1)*2);_=Bi(Float64Array.from({length:e},(v,y)=>y*w),o),h=d}else _=u_(0,Math.floor(n/2),e);const p=B1(_,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){const v=p[w],y=2/(h[w+2]-h[w]);for(let M=0;M<e;++M)v[M]*=y}return p}function R1(e,t,r){const s=new e.constructor(e.length+t+r),n=e.length-1;for(let a=0;a<e.length;++a)s[t+a]=e[a];for(let a=1;a<=t;++a)s[t-a]=e[ra(a,n)];for(let a=1;a<=r;++a)s[n+t+a]=e[ra(n-a,n)];return s}function d_(e,t,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);const a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(s,e[o])-a);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");const o=je(e)[0]-n;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function G1(e,t=1,r=1e-5,s=null){return d_(e,20,t,r,s)}function $1(e,t=1,r=1e-10,s=null){return d_(e,10,t,r,s)}async function sr(e,t,r,s,{fft_length:n=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:h=null,mel_floor:_=1e-10,log_mel:p=null,max_log_mel:w=null,reference:v=1,min_value:y=1e-10,db_range:M=null,remove_dc_offset:T=null,min_num_frames:A=null,max_num_frames:C=null,do_pad:S=!0,transpose:N=!1,mel_offset:x=0,mel_floor_mode:R="clamp"}={}){const z=t.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(z!==r)throw new Error(`Length of the window (${z}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(a===null&&h!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){const X=Math.floor(r/2);switch(i){case"reflect":{e=R1(e,X,X);break}case"constant":{const J=new e.constructor(e.length+2*X);J.set(e,X),e=J;break}case"semicausal":{const J=new e.constructor(e.length+X);J.set(e,X),e=J;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let $=Math.floor(1+Math.floor((e.length-r)/s));A!==null&&$<A&&($=A);const Q=l?Math.floor(n/2)+1:n;let H=$,D=$;C!==null&&(C>$?S&&(D=C):D=H=C);const I=new cx(n),te=new Float64Array(n),W=new Float64Array(I.outputBufferSize),ee=new Float32Array(Q*D);for(let X=0;X<H;++X){const J=X*s,we=Math.min(e.length-J,r);we!==r&&te.fill(0,0,r);for(let re=0;re<we;++re)te[re]=e[J+re];if(T){let re=0;for(let qe=0;qe<we;++qe)re+=te[qe];const Fe=re/we;for(let qe=0;qe<we;++qe)te[qe]-=Fe}if(c!==null){for(let re=we-1;re>=1;--re)te[re]-=c*te[re-1];te[0]*=1-c}for(let re=0;re<t.length;++re)te[re]*=t[re];I.realTransform(W,te);for(let re=0;re<Q;++re){const Fe=re<<1;ee[re*D+X]=W[Fe]**2+W[Fe+1]**2}}if(a!==null&&a!==2){const X=a/2;for(let J=0;J<ee.length;++J)ee[J]**=X}const G=h.length;let L=await Ex(new U("float32",h.flat(),[G,Q]),new U("float32",ee,[Q,D]));N&&(L=L.transpose(1,0));const V=L.data;if(R==="add")for(let X=0;X<V.length;++X)V[X]=x+V[X]+_;else for(let X=0;X<V.length;++X)V[X]=x+Math.max(_,V[X]);if(a!==null&&p!==null){const X=Math.min(V.length,H*G);switch(p){case"log":for(let J=0;J<X;++J)V[J]=Math.log(V[J]);break;case"log10":for(let J=0;J<X;++J)V[J]=Math.log10(V[J]);break;case"log10_max_norm":{for(let re=0;re<X;++re)V[re]=Math.log10(V[re]);const we=(w??je(V)[0])-8;for(let re=0;re<X;++re)V[re]=(Math.max(V[re],we)+4)/4;break}case"dB":if(a===1)G1(V,v,y,M);else if(a===2)$1(V,v,y,M);else throw new Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return L}function hr(e,t,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){const a=r?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=c_(a);break;case"hamming":o=O1(a);break;case"povey":o=c_(a).map(c=>Math.pow(c,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),s===null||e===s)return o;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);const i=new Float64Array(s),l=n?Math.floor((s-e)/2):0;return i.set(o,l),i}function V1(e,t){const r=e.reduce((a,o)=>a+o.length,0),s=new ArrayBuffer(44),n=new DataView(s);return ma(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),ma(n,8,"WAVE"),ma(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,t*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),ma(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...e.map(a=>a.buffer)],{type:"audio/wav"})}function ma(e,t,r){for(let s=0;s<r.length;++s)e.setUint8(t+s,r.charCodeAt(s))}var U1=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];const e=this.audio.reduce((s,n)=>s+n.length,0),t=new Float32Array(e);let r=0;for(const s of this.audio)t.set(s,r),r+=s.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),V1(e,this.sampling_rate)}async save(e){return i_(e,this.toBlob())}},j1=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){at(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,s=t.data;for(let n=0;n<s.length;++n)s[n]=(s[n]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},h_=class extends ut{async _call(e){at(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const r=[1,t,e.length/t];return{input_values:new U("float32",e,r)}}},q1=class extends ut{async _call(e){at(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new U("float32",e,t)}}},W1=class extends ut{constructor(e){super(e),this.mel_filters=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=hr(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,s){let n;const a=e.length-t;if(a>0)if(r==="rand_trunc"){const o=Math.floor(yi.random()*(a+1));e=e.subarray(o,o+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let o=new Float64Array(t);if(o.set(e),s==="repeat")for(let i=e.length;i<t;i+=e.length)o.set(e.subarray(0,Math.min(e.length,t-i)),i);else if(s==="repeatpad")for(let i=e.length;i<-a;i+=e.length)o.set(e,i);e=o}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return sr(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return at(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},H1=1e-5,f_=class extends ut{constructor(e){var s;super(e),(s=this.config).mel_filters??(s.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));const t=hr(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await sr(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){at(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),s=t.data;s.fill(0,r*t.dims[1]);const[n,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d<r;++d){const h=d*a;for(let _=0;_<a;++_){const p=s[h+_];o[_]+=p,i[_]+=p*p}}const l=r>1?r-1:1;for(let d=0;d<a;++d){const h=o[d]/r,_=(i[d]-r*h*h)/l,w=1/(Math.sqrt(_)+H1);for(let v=0;v<r;++v){const y=v*a+d;s[y]=(s[y]-h)*w}}const c=new BigInt64Array(n);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new U("int64",c,[1,n])}}},Q1=class extends f_{_apply_dither(e){const t=this.config.dither??0;if(t<=0)return e;const r=new ca(e.length);for(let s=0;s<e.length;++s)e[s]+=t*r.gauss();return e}split_audio(e){const t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,s=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,a=Math.max(1,Math.round(t*n)),o=Math.max(1,Math.round(r*n));if(e.length<=a)return[e];const i=[];let l=0;const c=e.length;for(;l<c;){if(l+a>=c){i.push(e.slice(l,c));break}const d=Math.max(l,l+a-o),h=Math.min(l+a,c);let _;h<=d?_=l+a:_=this._find_split_point_energy(e,d,h,s),_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_}return i}_find_split_point_energy(e,t,r,s){const n=r-t;if(n<=s)return Math.floor((t+r)/2);let a=1/0,o=t;const i=n-s;for(let l=0;l<=i;l+=s){let c=0;for(let d=0;d<s;++d){const h=e[t+l+d];c+=h*h}c=Math.sqrt(c/s),c<a&&(a=c,o=t+l)}return o}async _call(e){at(e,"CohereAsrFeatureExtractor");const t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},__=class extends h_{},p_=class extends ut{constructor(e){super(e);const{fft_length:t,feature_size:r,min_frequency:s,max_frequency:n,sampling_rate:a,frame_length:o}=this.config,i=rr(Math.floor(1+t/2),r,s,n,a,null,"htk",!1);this.mel_filters=i,this.window=hr(o,"hann")}async _extract_fbank_features(e,t){return sr(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:r=!0,padding:s=!0,pad_to_multiple_of:n=128}={}){if(at(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),s&&e.length%n!==0){const i=n-e.length%n,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=ct([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},m_=class extends p_{async _extract_fbank_features(e,t){const{frame_length:r,hop_length:s,fft_length:n}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/s)+1;return sr(e,this.window,r,s,{fft_length:n,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){at(e,"Gemma4AudioFeatureExtractor");const r=e.length,s=await super._call(e,t),{input_features:n}=s,[,a,o]=n.dims,{frame_length:i,hop_length:l}=this.config,c=Math.floor(i/2),d=i+1,h=new Uint8Array(r+c+(t.pad_to_multiple_of??128));h.fill(1,c,c+r);const _=new Uint8Array(a);for(let w=0;w<a;++w)_[w]=h[w*l+d-1]?1:0;const p=n.data;for(let w=0;w<a;++w)_[w]||p.fill(0,w*o,(w+1)*o);return s.input_features_mask=new U("bool",_,[1,a]),s}},X1=class extends ut{constructor(e){super(e);const{n_fft:t,win_length:r,n_mels:s,sample_rate:n}=e.melspec_kwargs;this.mel_filters=rr(Math.floor(1+t/2),s,0,n/2,n,null,"htk");const a=hr(r,"hann");this.window=new Float64Array(t);const o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){at(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:r,n_mels:s}=this.config.melspec_kwargs,n=1+Math.floor((e.length-1)/r),a=n-n%2;return{input_features:(await sr(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*s).unsqueeze_(0)}}},Y1=class extends ut{async _call(e){at(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new U("float32",e,t)}}},g_=class extends ut{async _call(e){at(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new U("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const r=t/this.samples_to_frames(t)/this.config.sampling_rate,s=[];for(const n of e.tolist()){const a=[];let o=-1;for(let i=0;i<n.length;++i){const l=nt(n[i]),[c,d]=je(l),[h,_]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,end:_,score:c})):(a.at(-1).end=_,a.at(-1).score+=c)}s.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return s}},J1=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:s=!0,return_attention_mask:n=!0}={}){at(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(s){const[p,w]=a.dims,v=a.data;for(let y=0;y<w;++y){let M=0;for(let S=0;S<p;++S)M+=v[S*w+y];const T=M/p;let A=0;for(let S=0;S<p;++S)A+=(v[S*w+y]-T)**2;A/=p-1;const C=Math.sqrt(A+1e-7);for(let S=0;S<p;++S){const N=S*w+y;v[N]=(v[N]-T)/C}}}let o;if(t){const[p,w]=a.dims,v=a.data,y=p%r;if(y>0){const M=new Float32Array(w*(p+y));M.set(v),M.fill(this.config.padding_value,v.length);const T=p+y;a=new U(a.type,M,[T,w]),n&&(o=new U("int64",new BigInt64Array(T),[1,T]),o.data.fill(1n,0,p))}}const[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const h=a.view(1,Math.floor(i/c),l*c),_={input_features:h};if(n){const p=h.dims[1],w=new BigInt64Array(p);if(o){const v=o.data;for(let y=1,M=0;y<i;y+=c,++M)w[M]=v[y]}else w.fill(1n);_.attention_mask=new U("int64",w,[1,p])}return _}},K1=class extends __{},Z1=class extends ut{},ek=class extends ut{_zero_mean_unit_var_norm(e){const r=e.reduce((n,a)=>n+a,0)/e.length,s=e.reduce((n,a)=>n+(a-r)**2,0)/e.length;return e.map(n=>(n-r)/Math.sqrt(s+1e-7))}async _call(e){at(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new U("float32",t,r),attention_mask:new U("int64",new BigInt64Array(t.length).fill(1n),r)}}},tk=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){at(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,s=t.data,[n,a,o]=t.dims;for(let i=0;i<n;++i){const l=i*a*o,c=i*o;for(let d=0;d<a;++d){const h=l+d*o;for(let _=0;_<o;++_)s[h+_]-=r[c+_]}}}return{input_features:t}}},rk=class extends ut{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=hr(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){const{n_fft:r,hop_length:s,mel_filters:n,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/s:(e.length-r)/s);return await sr(e,this.window,r,s,{power:2,mel_filters:n,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return at(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},sk=class extends ut{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=hr(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await sr(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){at(e,"WhisperFeatureExtractor");let r;const s=t??this.config.n_samples;return e.length>s?(e.length>this.config.n_samples&&ue.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,s)):(r=new Float32Array(s),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Lt=class{static async from_pretrained(e,t={}){const r=await er(e,Ni,!0,t),s=r.feature_extractor_type,n=zi[s];if(!n)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${pa}.`);return new n(r)}},nk=(Wa=class extends Ee{async _call(e,t=null){const r=this.tokenizer(e),s=t?await this.feature_extractor(t):{};return{...r,...s}}},k(Wa,"tokenizer_class",Te),k(Wa,"feature_extractor_class",Lt),Wa),ak=new Set(["ja","zh"]),ok=(Mn=class extends Ee{get_decoder_prompt_ids(e="en"){const t=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){const r=e.filter(a=>a&&a.trim());if(r.length===0)return"";const s=ak.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(s)}async _call(e){return await this.feature_extractor(e)}},k(Mn,"tokenizer_class",Te),k(Mn,"feature_extractor_class",Lt),k(Mn,"uses_processor_config",!0),Mn),Ri={},Yr,w_,Ir;if(fe.IS_WEB_ENV)Yr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Ir=self.createImageBitmap,w_=self.ImageData;else if(Ri)Ir=async e=>{const r=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new qt(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var ik={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},lk=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),qt=class lr{constructor(t,r,s,n){this.data=t,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof lr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!fe.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const s=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new lr(s,t.width,t.height,4)}static async fromURL(t){const r=await rn(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const s=await r.blob();return this.fromBlob(s)}static async fromBlob(t){if(fe.IS_WEB_ENV){const r=await Ir(t),s=Yr(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=Ri(await t.arrayBuffer());return await Ir(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new lr(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){const n=this.data[r],a=this.data[r+1],o=this.data[r+2];t[s++]=Math.round(.2989*n+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2],t[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);const r=this.data,s=t.data,n=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(n*4);for(let o=0,i=0,l=0;o<n;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=s[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<n;++a)r[4*a+3]=s[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:s=2}={}){if(this.width===t&&this.height===r)return this;let n=ik[s]??s;const a=Wh(t),o=Wh(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),fe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Yr(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new lr(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(ue.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Ir(i)}}async pad([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),t===0&&r===0&&s===0&&n===0)return this;if(fe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+s+n,c=Yr(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,s,this.width,this.height),new lr(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:r,top:s,bottom:n});return await Ir(a)}}async crop([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),t===0&&r===0&&s===this.width-1&&n===this.height-1)return this;const a=s-t+1,o=n-r+1;if(fe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Yr(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new lr(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{const i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await Ir(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;const s=(this.width-t)/2,n=(this.height-r)/2;if(fe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=Yr(t,r).getContext("2d");let l=0,c=0,d=0,h=0;return s>=0?l=s:d=-s,n>=0?c=n:h=-n,i.drawImage(o,l,c,t,r,d,h,t,r),new lr(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(s>=0&&n>=0)a=a.extract({left:Math.floor(s),top:Math.floor(n),width:t,height:r});else if(s<=0&&n<=0){const o=Math.floor(-n),i=Math.floor(-s);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;n<0?(o[0]=Math.floor(-n),o[1]=r-this.height-o[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=t-this.width-l[0]):c=Math.floor(s),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await Ir(a)}}async toBlob(t="image/png",r=1){if(!fe.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new U("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!fe.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Yr(t.width,t.height),s=new w_(t.data,t.width,t.height);return r.getContext("2d").putImageData(s,0,0),r}split(){const{data:t,width:r,height:s,channels:n}=this,a=t.constructor,o=t.length/n,i=Array.from({length:n},()=>new a(o));for(let l=0;l<o;++l){const c=n*l;for(let d=0;d<n;++d)i[d][l]=t[c+d]}return i.map(l=>new lr(l,r,s,1))}_update(t,r,s,n=null){return this.data=t,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new lr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(fe.IS_WEB_ENV){if(fe.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),s=lk.get(r)??"image/png",n=await this.toBlob(s);return i_(t,n)}else if(fe.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(fe.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Ri(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};qt.read.bind(qt);function v_(e,t,r=0,s=null){const n=e/t;let a=dx(n)*t;return s!==null&&a>s&&(a=Math.floor(n)*t),a<r&&(a=Math.ceil(n)*t),a}function y_([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function b_([e,t,r,s]){return[e-r/2,t-s/2,e+r/2,t+s/2]}function ga(e,t=.5,r=null,s=!1){const n=e.logits,a=e.pred_boxes,[o,i,l]=n.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let d=0;d<o;++d){let h=r!==null?r[d]:null,_={boxes:[],classes:[],scores:[]},p=n[d],w=a[d];for(let v=0;v<i;++v){let y=p[v],M=[],T;if(s){T=y.sigmoid().data;for(let A=0;A<T.length;++A)T[A]>t&&M.push(A)}else{let A=je(y.data)[1];if(A===l-1||(T=nt(y.data),T[A]<t))continue;M.push(A)}for(const A of M){let C=w[v].data;C=b_(C),h!==null&&(C=C.map((S,N)=>S*h[(N+1)%2])),_.boxes.push(C),_.classes.push(A),_.scores.push(T[A])}}c.push(_)}return c}function M_(e,t=null){const r=e.logits,s=r.dims[0];if(t!==null&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const n=[];for(let a=0;a<s;++a){const o=t!==null?t[a]:null;let i=r[a];o!==null&&(i=Wf(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new U("int32",new Int32Array(l*c),[l,c]),h=i[0].data,_=d.data;for(let v=1;v<i.dims[0];++v){const y=i[v].data;for(let M=0;M<y.length;++M)y[M]>h[M]&&(h[M]=y[M],_[M]=v)}const p=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const y=_[v];p[y]=y}const w=p.filter(v=>v!==void 0);n.push({segmentation:d,labels:w})}return n}function ck(e,t,r,s){const n=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=je(l.data)[1];if(d===s)continue;const _=nt(l.data)[d];_>r&&(n.push(c),a.push(_),o.push(d))}return[n,a,o]}function uk(e,t,r,s=.5,n=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let d=0;d<e.length;++d)e[d]===r&&(a.push(d),++o),l[d]>=s&&++i;let c=o>0&&i>0;return c&&(c=o/i>n),[c,a]}function dk(e,t,r,s,n,a=null,o=null){const[i,l]=o??e[0].dims,c=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=Wf(e[v],o,"bilinear",!1);const h=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let y=t[v];const M=e[v].data;for(let T=0;T<M.length;++T)M[T]*=y,M[T]>_[T]&&(h[T]=v,_[T]=M[T])}let p=0;const w=c.data;for(let v=0;v<r.length;++v){const y=r[v],[M,T]=uk(h,e,v,s,n);if(M){++p;for(const A of T)w[A]=p;d.push({id:p,label_id:y,score:t[v]})}}return[c,d]}function Gi(e,t,r=28,s=3136,n=784*1280,a=1){if(e<r||t<r){const l=Math.max(r/e,r/t);e=Math.round(e*l),t=Math.round(t*l)}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>n){const l=Math.sqrt(a*e*t/n);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r)}else if(a*o*i<s){const l=Math.sqrt(s/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function x_(e,t=.5,r=.5,s=.8,n=null,a=null){n===null&&(ue.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);const o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,h]=o.dims;if(h-=1,a!==null&&a.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let p=0;p<c;++p){let w=a!==null?a[p]:null,v=o[p],y=l[p],[M,T,A]=ck(v,y,t,h);if(A.length===0){let[N,x]=w??y.dims.slice(-2),R=new U("int32",new Int32Array(N*x).fill(-1),[N,x]);_.push({segmentation:R,segments_info:[]});continue}let[C,S]=dk(M,T,A,r,s,n,w);_.push({segmentation:C,segments_info:S})}return _}function k_(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var de=class extends vt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){const s=e.height,n=e.width,a=t.height,o=t.width;let i=Math.min(s,a),l=Math.min(n,o);return i===s&&l===n?e:(s>n?l=Math.floor(n*i/s):n>s&&(i=Math.floor(s*l/n)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),s=ki(r.data)[0],a=je(r.data)[0]-s;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,c=0,d=0;const h=r.data;for(let _=0;_<r.height;++_){const p=_*r.width;for(let w=0;w<r.width;++w)(h[p+w]-s)/a<o&&(i=Math.min(i,w),l=Math.min(l,_),c=Math.max(c,w),d=Math.max(d,_))}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:s="constant",center:n=!1,constant_values:a=0}={}){const[o,i,l]=t;let c,d;if(typeof r=="number"?(c=r,d=r):r==="square"?c=d=Math.max(o,i):(c=r.width,d=r.height),c!==i||d!==o){const h=new Float32Array(c*d*l);if(Array.isArray(a))for(let w=0;w<h.length;++w)h[w]=a[w%l];else a!==0&&h.fill(a);const[_,p]=n?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+p)*c,y=w*i;for(let M=0;M<i;++M){const T=(v+M+_)*l,A=(y+M)*l;for(let C=0;C<l;++C)h[T+C]=e[A+C]}}if(s==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const w=o-1,v=i-1;for(let y=0;y<d;++y){const M=y*c,T=ra(y,w)*i;for(let A=0;A<c;++A){if(y<o&&A<i)continue;const C=(M+A)*l,S=(T+ra(A,v))*l;for(let N=0;N<l;++N)h[C+N]=e[S+N]}}}e=h,t=[d,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[r,s]=e.size;let n,a;if(this.do_thumbnail){const{height:o,width:i}=t;n=Math.min(o,i)}else Number.isInteger(t)?(n=t,a=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,a=t.longest_edge);if(n!==void 0||a!==void 0){const o=n===void 0?1:Math.max(n/r,n/s),i=r*o,l=s*o,c=a===void 0?1:Math.min(a/i,a/l);let d=Math.floor(Number((i*c).toFixed(2))),h=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=y_([d,h],this.size_divisibility)),[d,h]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/s,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=v_(l*s,this.config.ensure_multiple_of),o=v_(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return y_([r,s],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:s=null,do_convert_grayscale:n=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(s??this.do_convert_rgb?e=e.rgb():n&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,p;Number.isInteger(this.crop_size)?(_=this.crop_size,p=this.crop_size):(_=this.crop_size.width,p=this.crop_size.height),e=await e.center_crop(_,p)}const l=[e.height,e.width];let c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let p=this.image_std;if(Array.isArray(this.image_std)||(p=new Array(e.channels).fill(p)),_.length!==e.channels||p.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${p.length}) must match the number of channels in the image (${e.channels}).`);for(let w=0;w<c.length;w+=e.channels)for(let v=0;v<e.channels;++v)c[w+v]=(c[w+v]-_[v])/p[v]}if(r??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,p=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:_,height:p})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){const p=c[_];c[_]=c[_+2],c[_+2]=p}}const h=new U("float32",c,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:h}}async _call(e,...t){Array.isArray(e)||(e=[e]);const r=await Promise.all(e.map(n=>this.preprocess(n)));return{pixel_values:dr(r.map(n=>n.pixel_values),0),original_sizes:r.map(n=>n.original_size),reshaped_input_sizes:r.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await er(e,an,!0,t);return new this(r)}},wa={};os(wa,{BeitFeatureExtractor:()=>hk,BitImageProcessor:()=>fk,CHMv2ImageProcessor:()=>pk,CLIPFeatureExtractor:()=>mk,CLIPImageProcessor:()=>T_,ChineseCLIPFeatureExtractor:()=>_k,ConvNextFeatureExtractor:()=>gk,ConvNextImageProcessor:()=>E_,DINOv3ViTImageProcessor:()=>yk,DPTFeatureExtractor:()=>Mk,DPTImageProcessor:()=>S_,DeiTFeatureExtractor:()=>wk,DeiTImageProcessor:()=>A_,DetrFeatureExtractor:()=>vk,DetrImageProcessor:()=>C_,DonutFeatureExtractor:()=>bk,DonutImageProcessor:()=>$i,EfficientNetImageProcessor:()=>xk,GLPNFeatureExtractor:()=>Ck,Gemma3ImageProcessor:()=>kk,Gemma4ImageProcessor:()=>P_,Glm46VImageProcessor:()=>Ak,GroundingDinoImageProcessor:()=>Sk,Idefics3ImageProcessor:()=>L_,ImageFeatureExtractor:()=>de,ImageProcessor:()=>de,JinaCLIPImageProcessor:()=>Fk,Lfm2VlImageProcessor:()=>Dk,LlavaOnevisionImageProcessor:()=>zk,Mask2FormerImageProcessor:()=>Rk,MaskFormerFeatureExtractor:()=>Bk,MaskFormerImageProcessor:()=>Vi,MobileNetV1FeatureExtractor:()=>Gk,MobileNetV1ImageProcessor:()=>O_,MobileNetV2FeatureExtractor:()=>$k,MobileNetV2ImageProcessor:()=>N_,MobileNetV3FeatureExtractor:()=>Vk,MobileNetV3ImageProcessor:()=>D_,MobileNetV4FeatureExtractor:()=>Uk,MobileNetV4ImageProcessor:()=>z_,MobileViTFeatureExtractor:()=>jk,MobileViTImageProcessor:()=>B_,NougatImageProcessor:()=>qk,OwlViTFeatureExtractor:()=>Wk,OwlViTImageProcessor:()=>Ui,Owlv2ImageProcessor:()=>Hk,Phi3VImageProcessor:()=>Xk,PixtralImageProcessor:()=>Yk,PvtImageProcessor:()=>Jk,Qwen2VLImageProcessor:()=>F_,RTDetrImageProcessor:()=>Kk,Sam2ImageProcessor:()=>Wi,Sam3ImageProcessor:()=>Wi,SamImageProcessor:()=>Wi,SapiensFeatureExtractor:()=>Zk,SapiensImageProcessor:()=>R_,SegformerFeatureExtractor:()=>eT,SegformerImageProcessor:()=>G_,SiglipImageProcessor:()=>tT,SmolVLMImageProcessor:()=>L_,Swin2SRImageProcessor:()=>rT,VLMImageProcessor:()=>Pk,ViTFeatureExtractor:()=>sT,ViTImageProcessor:()=>$_,VitMatteImageProcessor:()=>nT,VitPoseImageProcessor:()=>aT,YolosFeatureExtractor:()=>oT,YolosImageProcessor:()=>V_});var hk=class extends de{},fk=class extends de{},_k=class extends de{},pk=class extends de{},T_=class extends de{},mk=class extends T_{},E_=class extends de{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var r;const t=(r=this.size)==null?void 0:r.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const s=Math.floor(t/this.crop_pct),[n,a]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},gk=class extends E_{},A_=class extends de{},wk=class extends A_{},C_=class extends de{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],s=ct(r,1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return ga(...e)}post_process_panoptic_segmentation(...e){return x_(...e)}post_process_instance_segmentation(...e){return k_(...e)}},vk=class extends C_{},yk=class extends de{},$i=class extends de{pad_image(e,t,r,s={}){const[n,a,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const c=i.map((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...s})}},bk=class extends $i{},S_=class extends de{},Mk=class extends S_{},xk=class extends de{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},kk=class extends de{};function Tk(e,t,r,s,n){const a=s*r**2,o=Math.sqrt(a/(e*t)),i=n*r;let l=Math.floor(o*e/i)*i,c=Math.floor(o*t/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);const d=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(t/e)*i,d)):c===0&&(c=i,l=Math.min(Math.floor(e/t)*i,d)),[l,c]}function Ek(e,t,r,s,n,a,o){const i=Math.floor(t/n),l=Math.floor(r/n),c=i*l,d=n*n*s,h=new Float32Array(a*d);let _=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)for(let M=0;M<n;++M){const T=(v*n+M)*r*s+y*n*s;for(let A=0;A<n;++A){const C=T+A*s;for(let S=0;S<s;++S)h[_++]=e[C+S]}}const p=new BigInt64Array(a*2).fill(-1n);let w=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)p[w++]=BigInt(y),p[w++]=BigInt(v);return{patches:new U("float32",h,[a,d]),positions:new U("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var P_=class extends vt{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);const{patch_size:t,pooling_kernel_size:r}=this,s=this.max_soft_tokens*r**2,n=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){const[_,p]=Tk(i.height,i.width,t,s,r);(_!==i.height||p!==i.width)&&(i=await i.resize(p,_,{resample:this.resample}))}const l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;const{patches:c,positions:d,num_soft_tokens:h}=Ek(l,i.height,i.width,i.channels,t,s,r);n.push(c),a.push(d),o.push(h)}return{pixel_values:dr(n,0),image_position_ids:dr(a,0),num_soft_tokens_per_image:o}}},F_=class extends de{constructor(e){var t,r;super(e),this.min_pixels=e.min_pixels??((t=e.size)==null?void 0:t.shortest_edge),this.max_pixels=e.max_pixels??((r=e.size)==null?void 0:r.longest_edge),this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size;return Gi(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:s,reshaped_input_sizes:n}=await super._call(e,...t);let a=r;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=ze(Array.from({length:o},()=>a),0));const c=a.dims[0]/o,d=a.dims[1],h=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),p=a.view(c,o,d,Math.floor(h/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*h*_,d*o*l*l),w=new U("int64",[c,h,_],[1,3]);return{pixel_values:p,image_grid_thw:w,original_sizes:s,reshaped_input_sizes:n}}},Ak=class extends F_{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,s=this.config.temporal_patch_size??2;return Gi(e.height,e.width,r,this.min_pixels,this.max_pixels,s)}},Ck=class extends de{},Sk=class extends de{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,s=yt([r[0],r[2],r[3]]);return{...t,pixel_mask:s}}},L_=class extends de{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,s]=e.dims.slice(-2);const n=s/r;return s>=r?(s=Math.ceil(s/t)*t,r=Math.floor(s/n),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,s=Math.floor(r*n),s=Math.ceil(s/t)*t),{height:r,width:s}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let s;if(!Array.isArray(e))s=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?s=e:s=[e]}let n=[],a=[],o=[];const i=[],l=[];for(const y of s){let M=await Promise.all(y.map(C=>this.preprocess(C)));i.push(...M.map(C=>C.original_size)),l.push(...M.map(C=>C.reshaped_input_size)),M.forEach(C=>C.pixel_values.unsqueeze_(0));const{longest_edge:T}=this.max_image_size;let A;if(t??this.do_image_splitting){let C=new Array(M.length),S=new Array(M.length);A=await Promise.all(M.map(async(N,x)=>{const R=this.get_resize_for_vision_encoder(N.pixel_values,T),z=await jt(N.pixel_values,{size:[R.height,R.width]}),{frames:$,num_splits_h:Q,num_splits_w:H}=await this.split_image(z,this.max_image_size);return C[x]=Q,S[x]=H,ze($,0)})),a.push(C),o.push(S)}else{const C=[T,T];A=await Promise.all(M.map(S=>jt(S.pixel_values,{size:C}))),a.push(new Array(M.length).fill(0)),o.push(new Array(M.length).fill(0))}n.push(ze(A,0))}const c=n.length,[d,h,_,p]=n[0].dims;let w,v;if(c===1)w=n[0].unsqueeze_(0),v=ct([c,d,_,p],!0);else{const y=Math.max(...n.map(A=>A.dims.at(0)));v=ct([c,y,_,p],!0);const M=v.data,T=y*_*p;for(let A=0;A<c;++A){const C=n[A].dims[0];if(C<y){n[A]=ze([n[A],ct([y-C,h,_,p],0)],0);const S=A*T+C*_*p,N=(A+1)*T;M.fill(!1,S,N)}}w=dr(n,0)}return{pixel_values:w,pixel_attention_mask:v,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){const r=t,s=t,n=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>r||o>s){i=Math.ceil(a/r),l=Math.ceil(o/s);const c=Math.ceil(a/i),d=Math.ceil(o/l);for(let p=0;p<i;++p)for(let w=0;w<l;++w){let v,y,M,T;p===i-1?(y=a-c,T=a):(y=p*c,T=(p+1)*c),w===l-1?(v=o-d,M=o):(v=w*d,M=(w+1)*d);const S=await Hf(e,[y,v],[T,M],[2,3]);n.push(S)}const h=r,_=s;(a!==h||o!==_)&&(e=await jt(e,{size:[h,_]}))}return n.push(e),{frames:n,num_splits_h:i,num_splits_w:l}}},Pk=class extends de{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor)}pad_image(e,t,r,s){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...s})}},Fk=class extends de{constructor(e){const{resize_mode:t,fill_color:r,interpolation:s,size:n,...a}=e,o=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},i=s==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:n,do_normalize:!0})}};function I_(e,t){return Math.round(e/t)*t}function Lk(e,t,r,s,n){let a=1/0,o=[1,1];const i=r*s;for(const l of t){const c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*n*n*l[0]*l[1]&&(o=l)}return o}function Ik(e,t){const r=[],s=new Set;for(let n=e;n<=t;++n)for(let a=1;a<=n;++a)for(let o=1;o<=n;++o){const i=a*o;if(i>=e&&i<=t){const l=a<<16|o;s.has(l)||(s.add(l),r.push([a,o]))}}return r.sort((n,a)=>n[0]*n[1]-a[0]*a[1])}function Ok(e,t){const[r,s,n,a]=e.dims,o=Math.floor(n/t),i=Math.floor(a/t),l=t*t*s,c=e.data,d=new Float32Array(r*o*i*l),h=n*a;for(let _=0;_<r;++_){const p=_*s*h,w=_*o*i*l;for(let v=0;v<o;++v)for(let y=0;y<i;++y){let M=w+(v*i+y)*l;for(let T=0;T<t;++T){const A=(v*t+T)*a+y*t;for(let C=0;C<t;++C){const S=A+C;for(let N=0;N<s;++N)d[M++]=c[p+N*h+S]}}}}return new U("float32",d,[r,o*i,l])}function Nk(e,t){const[,r,s]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,r);let a=e;if(r<t){const o=new Float32Array(t*s);o.set(e.data),a=new U("float32",o,[1,t,s])}return{padded:a,mask:new U("int64",n,[t])}}var Dk=class extends de{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;const t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r)}_is_image_too_large(e,t){const r=this.encoder_patch_size*this.downsample_factor,s=Math.max(this.encoder_patch_size,I_(e,r)),n=Math.max(this.encoder_patch_size,I_(t,r));return s*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=Ik(this.min_tiles,this.max_tiles),[s,n]=Lk(t/e,r,t,e,this.tile_size);return{grid_width:s,grid_height:n,target_width:this.tile_size*s,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];const s=[],n=[],a=[],o=[],i=[],l=[];for(const d of r){const h=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(const{pixel_values:_}of h){const[,p,w]=_.dims,v=_.unsqueeze_(0),y=this.encoder_patch_size*this.downsample_factor,M=y**2,[T,A]=Gi(Math.max(y,p),Math.max(y,w),y,this.min_image_tokens*M,this.max_image_tokens*M).map(z=>Math.max(y,z));let C,S=1,N=1;const x=this._is_image_too_large(p,w),R=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(x&&R){const{grid_width:z,grid_height:$,target_width:Q,target_height:H}=this._get_grid_layout(p,w);S=$,N=z;const D=await jt(v,{size:[H,Q]});C=[];for(let I=0;I<$;++I)for(let te=0;te<z;++te){const W=I*this.tile_size,ee=te*this.tile_size;C.push(D.slice(null,null,[W,W+this.tile_size],[ee,ee+this.tile_size]))}this.use_thumbnail&&z*$!==1&&C.push(await jt(v,{size:[A,T]}))}else C=[await jt(v,{size:[A,T]})];for(const z of C){const[,,$,Q]=z.dims,H=Ok(z,this.encoder_patch_size),{padded:D,mask:I}=Nk(H,this.max_num_patches);s.push(D),n.push(I),a.push([Math.floor($/this.encoder_patch_size),Math.floor(Q/this.encoder_patch_size)])}o.push(S),i.push(N),l.push([A,T])}}const c={pixel_values:ze(s,0),pixel_attention_mask:dr(n,0),spatial_shapes:new U("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(c.image_rows=o,c.image_cols=i,c.image_sizes=l),c}},zk=class extends de{},Vi=class extends de{post_process_panoptic_segmentation(...e){return x_(...e)}post_process_instance_segmentation(...e){return k_(...e)}},Bk=class extends Vi{},Rk=class extends Vi{},O_=class extends de{},Gk=class extends O_{},N_=class extends de{},$k=class extends N_{},D_=class extends de{},Vk=class extends D_{},z_=class extends de{},Uk=class extends z_{},B_=class extends de{},jk=class extends B_{},qk=class extends $i{},Ui=class extends de{post_process_object_detection(...e){return ga(...e)}},Wk=class extends Ui{},Hk=class extends Ui{},At=336,Qk=[2,3],{ceil:ji,floor:ps,sqrt:qi}=Math,Xk=class extends de{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){const{num_img_tokens:r}=this.config;return ps((ps(t/At)*ps(e/At)+1)*r+1+(ps(t/At)+1)*qi(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[s,n]=e.size;let a=s/n,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;const i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,s={}){const[n,a]=t,o=At*ji(n/At),i=At*ji(a/At),l=[1,1,1].map((c,d)=>(c-this.image_mean[d])/this.image_std[d]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...s})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??(t=this.config.num_crops),t<4||qi(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,s=await Promise.all(e.map(h=>this.preprocess(h))),n=s.map(h=>h.original_size),a=s.map(h=>h.reshaped_input_size),o=[];for(const{pixel_values:h}of s){h.unsqueeze_(0);const[_,p]=h.dims.slice(-2),w=await jt(h,{size:[At,At],mode:"bicubic"});if(t>0){const v=[],y=qi(t),M=ps(p/y),T=ps(_/y);for(let C=0;C<y;++C)for(let S=0;S<y;++S){let N,x,R,z;C===y-1?(x=_-T,z=_):(x=C*T,z=(C+1)*T),S===y-1?(N=p-M,R=p):(N=S*M,R=(S+1)*M);const H=await Hf(h,[x,N],[z,R],Qk);v.push(H)}const A=await jt(ze(v,0),{size:[At,At],mode:"bicubic"});o.push(ze([w,A],0))}else o.push(w)}const i=dr(o,0),l=a.map(h=>h.map(_=>At*ji(_/At))),c=new U("int64",l.flat(),[r,2]),d=l.map(([h,_])=>this.calc_num_image_tokens_from_image_size(_,h));return{pixel_values:i,original_sizes:n,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},Yk=class extends de{get_resize_output_image_size(e,t){const{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[s,n]=e.size,a=Math.max(s,n)/r;let o=s,i=n;a>1&&(o=Math.floor(s/a),i=Math.floor(n/a));const{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");const d=l*c,h=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[h*d,_*d]}},Jk=class extends de{},Kk=class extends de{post_process_object_detection(...e){return ga(...e)}},Wi=class extends de{reshape_input_points(e,t,r,s=!1){e=structuredClone(e);let n=Hh(e);if(n.length===3)s||(n=[1,...n]),e=[e];else if(n.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){const[o,i]=t[a],[l,c]=r[a],d=[c/i,l/o];for(let h=0;h<e[a].length;++h)for(let _=0;_<e[a][h].length;++_)for(let p=0;p<e[a][h][_].length;++p)e[a][h][_][p]*=d[p%2]}return new U("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let r=Hh(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((s,n)=>s!==t.dims[n]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:s=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),r){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(r,n.input_points)}return s&&(n.input_boxes=this.reshape_input_points(s,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,r,{mask_threshold:s=0,binarize:n=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;l<t.length;++l){const c=t[l],d=r[l];let h=await jt(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await jt(h,{mode:"bilinear",size:c}),n){const _=h.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)_[w]>s&&(p[w]=1);h=new U("bool",p,h.dims)}o.push(h)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:a=1}={}){}},R_=class extends de{post_process_semantic_segmentation(...e){return M_(...e)}},Zk=class extends R_{},G_=class extends de{post_process_semantic_segmentation(...e){return M_(...e)}},eT=class extends G_{},tT=class extends de{},rT=class extends de{pad_image(e,t,r,s={}){const[n,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:n+(r-n%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}},$_=class extends de{},sT=class extends $_{},nT=class extends de{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(a=>this.preprocess(a))),s=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:dr(r.map((a,o)=>ze([a.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},aT=class extends de{post_process_pose_estimation(e,t,{threshold:r=null}={}){const s=e.tolist(),[n,a,o,i]=e.dims,l=[];for(let c=0;c<n;++c){const d=s[c],h=t[c],_=[];for(let p=0;p<h.length;++p){const w=h[p],v=[],y=[],M=[],T=w.at(-2)/i,A=w.at(-1)/o;for(let C=0;C<d.length;++C){let[S,N]=[0,0],x=0,R=-1/0;const z=d[C];for(let Q=0;Q<z.length;++Q){const H=z[Q];for(let D=0;D<H.length;++D){const I=H[D];x+=I,R=Math.max(R,I),S+=(D+.5)*I,N+=Q*I}}if(r!=null&&R<r)continue;const $=[T*S/x,A*N/x];v.push($),M.push(C),y.push(R)}_.push({bbox:w,scores:y,labels:M,keypoints:v})}l.push(_)}return l}},V_=class extends de{post_process_object_detection(...e){return ga(...e)}},oT=class extends V_{},dt=class{static async from_pretrained(e,t={}){const r=await er(e,an,!0,t),s=r.image_processor_type??r.feature_extractor_type;let n=wa[s==null?void 0:s.replace(/Fast$/,"")];return n||(s!==void 0&&ue.warn(`Image processor type '${s}' not found, assuming base ImageProcessor. Please report this at ${pa}.`),n=de),new n(r)}},iT=(Ha=class extends Ee{constructor(e,t,r){super(e,t,r);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const t=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(const[s,n]of this.task_prompts_with_input)if(r.includes(s)){t.push(n.replaceAll("{input}",r).replaceAll(s,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const s=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(s){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=s==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[c,d,...h]of o)i.push(d?d.trim():i.at(-1)??""),l.push(h.map((_,p)=>(Number(_)+.5)/this.size_per_bin*r[p%2]));n={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${s}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=await this.image_processor(e,r),n=t?this.tokenizer(this.construct_prompts(t),r):{};return{...s,...n}}},k(Ha,"tokenizer_class",Te),k(Ha,"image_processor_class",dt),Ha),lT=(Ds=class extends Ee{constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;const{boi_token:s,image_token:n,eoi_token:a}=this.tokenizer.config;this.boi_token=s,this.image_token=n,this.eoi_token=a;const o=n.repeat(this.image_seq_length);this.full_image_sequence=`
16
+ `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Ne))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(s.args,r);return a.value([...o,new Zs(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof et){const a=e.builtins.get(n);if(a&&a instanceof Ne){const[o,i]=this.evaluateArguments(s.args,r);return i.size>0&&o.push(new Zs(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const n=s(r);return new ie(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new De}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ie(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const s of e){const n=this.evaluate(s,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new Z(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,s]=this.evaluateArguments(e.args,t);s.size>0&&r.push(new Zs(s));const n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof ge||e instanceof Z))throw new Error("Slice object must be an array or string");const s=this.evaluate(t.start,r),n=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(s instanceof he||s instanceof De))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof De))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof he||a instanceof De))throw new Error("Slice step must be numeric or undefined");return e instanceof ge?new ge(_f(e.value,s.value,n.value,a.value)):new Z(_f(Array.from(e.value),s.value,n.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);s=this.evaluate(e.property,t)}else s=new Z(e.property.value);let n;if(r instanceof et){if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ge||r instanceof Z)if(s instanceof he)n=r.value.at(s.value),r instanceof Z&&(n=new Z(r.value.at(s.value)));else if(s instanceof Z)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof Kt?n:new De}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const s=e.assignee.value;t.setVariable(s,r)}else if(e.assignee.type==="TupleLiteral"){const s=e.assignee;if(!(r instanceof ge))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let a=0;a<s.value.length;++a){const o=s.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,n[a])}}else if(e.assignee.type==="MemberExpression"){const s=e.assignee,n=this.evaluate(s.object,t);if(!(n instanceof et))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Re}evaluateIf(e,t){const r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const r=new Qr(t);let s,n;if(e.iterable.type==="SelectExpression"){const c=e.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(e.iterable,r);if(!(n instanceof ge||n instanceof et))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof et&&(n=n.keys());const a=[],o=[];for(let c=0;c<n.value.length;++c){const d=new Qr(r),h=n.value[c];let _;if(e.loopvar.type==="Identifier")_=p=>p.setVariable(e.loopvar.value,h);else if(e.loopvar.type==="TupleLiteral"){const p=e.loopvar;if(h.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${h.type}`);const w=h;if(p.value.length!==w.value.length)throw new Error(`Too ${p.value.length>w.value.length?"few":"many"} items to unpack`);_=v=>{for(let y=0;y<p.value.length;++y){if(p.value[y].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${p.value[y].type}`);v.setVariable(p.value[y].value,w.value[y])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);s&&(_(d),!this.evaluate(s,d).__bool__().value)||(a.push(h),o.push(_))}let i="",l=!0;for(let c=0;c<a.length;++c){const d=new Map([["index",new he(c+1)],["index0",new he(c)],["revindex",new he(a.length-c)],["revindex0",new he(a.length-c-1)],["first",new ie(c===0)],["last",new ie(c===a.length-1)],["length",new he(a.length)],["previtem",c>0?a[c-1]:new De],["nextitem",c<a.length-1?a[c+1]:new De]]);r.setVariable("loop",new et(d)),o[c](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof mf)continue;if(h instanceof pf)break;throw h}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new Z(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Ne((r,s)=>{var o;const n=new Qr(s);r=r.slice();let a;((o=r.at(-1))==null?void 0:o.type)==="KeywordArgumentsValue"&&(a=r.pop());for(let i=0;i<e.args.length;++i){const l=e.args[i],c=r[i];if(l.type==="Identifier"){const d=l;if(!c)throw new Error(`Missing positional argument: ${d.value}`);n.setVariable(d.value,c)}else if(l.type==="KeywordArgumentExpression"){const d=l,h=c??(a==null?void 0:a.value.get(d.key.value))??this.evaluate(d.value,n);n.setVariable(d.key.value,h)}else throw new Error(`Unknown argument type: ${l.type}`)}return this.evaluateBlock(e.body,n)})),new Re}evaluateCallStatement(e,t){const r=new Ne((i,l)=>{const c=new Qr(l);if(e.callerArgs)for(let d=0;d<e.callerArgs.length;++d){const h=e.callerArgs[d];if(h.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${h.type}`);c.setVariable(h.value,i[d]??new De)}return this.evaluateBlock(e.body,c)}),[s,n]=this.evaluateArguments(e.call.args,t);s.push(new Zs(n));const a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);const o=new Qr(t);return o.setVariable("caller",r),a.value(s,o)}evaluateFilterStatement(e,t){const r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new De;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new pf;case"Continue":throw new mf;case"IntegerLiteral":return new he(e.value);case"FloatLiteral":return new $e(e.value);case"StringLiteral":return new Z(e.value);case"ArrayLiteral":return new ge(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new wf(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[s,n]of e.value){const a=this.evaluate(s,t);if(!(a instanceof Z))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(n,t))}return new et(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Re;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function ia(e){switch(typeof e){case"number":return Number.isInteger(e)?new he(e):new $e(e);case"string":return new Z(e);case"boolean":return new ie(e);case"undefined":return new De;case"object":return e===null?new Re:Array.isArray(e)?new ge(e.map(ia)):new et(new Map(Object.entries(e).map(([t,r])=>[t,ia(r)])));case"function":return new Ne((t,r)=>{const s=e(...t.map(n=>n.value))??null;return ia(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Xe=`
17
+ `,IM="{%- ",OM=" -%}";function NM(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 DM(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Ut(e.body,0,r).replace(/\n$/,"")}function st(...e){return IM+e.join(" ")+OM}function Ut(e,t,r){return e.map(s=>zM(s,t,r)).join(Xe)}function zM(e,t,r){const s=r.repeat(t);switch(e.type){case"Program":return Ut(e.body,t,r);case"If":return BM(e,t,r);case"For":return RM(e,t,r);case"Set":return GM(e,t,r);case"Macro":return $M(e,t,r);case"Break":return s+st("break");case"Continue":return s+st("continue");case"CallStatement":return VM(e,t,r);case"FilterStatement":return UM(e,t,r);case"Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+ve(e)+" -}}"}}function BM(e,t,r){const s=r.repeat(t),n=[];let a=e;for(;a&&(n.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=s+st("if",ve(n[0].test))+Xe+Ut(n[0].body,t+1,r);for(let i=1;i<n.length;++i)o+=Xe+s+st("elif",ve(n[i].test))+Xe+Ut(n[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=Xe+s+st("else")+Xe+Ut(a.alternate,t+1,r)),o+=Xe+s+st("endif"),o}function RM(e,t,r){const s=r.repeat(t);let n="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;n=`${ve(o.lhs)} if ${ve(o.test)}`}else n=ve(e.iterable);let a=s+st("for",ve(e.loopvar),"in",n)+Xe+Ut(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Xe+s+st("else")+Xe+Ut(e.defaultBlock,t+1,r)),a+=Xe+s+st("endfor"),a}function GM(e,t,r){const s=r.repeat(t),n=ve(e.assignee),a=e.value?ve(e.value):"",o=s+st("set",`${n}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Xe+Ut(e.body,t+1,r)+Xe+s+st("endset")}function $M(e,t,r){const s=r.repeat(t),n=e.args.map(ve).join(", ");return s+st("macro",`${e.name.value}(${n})`)+Xe+Ut(e.body,t+1,r)+Xe+s+st("endmacro")}function VM(e,t,r){const s=r.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ve).join(", ")})`:"",a=ve(e.call);let o=s+st(`call${n}`,a)+Xe;return o+=Ut(e.body,t+1,r)+Xe,o+=s+st("endcall"),o}function UM(e,t,r){const s=r.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:ve(e.filter);let a=s+st("filter",n)+Xe;return a+=Ut(e.body,t+1,r)+Xe,a+=s+st("endfilter"),a}function ve(e,t=-1){switch(e.type){case"SpreadExpression":return`*${ve(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":{const r=e,s=NM(r),n=ve(r.left,s),a=ve(r.right,s+1),o=`${n} ${r.operator.value} ${a}`;return s<t?`(${o})`:o}case"UnaryExpression":{const r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+ve(r.argument,1/0)}case"CallExpression":{const r=e,s=r.args.map(ve).join(", ");return`${ve(r.callee)}(${s})`}case"MemberExpression":{const r=e;let s=ve(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ve(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{const r=e,s=ve(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ve(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{const r=e;return`${ve(r.lhs)} if ${ve(r.test)}`}case"TestExpression":{const r=e;return`${ve(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const r=e.value.map(ve),s=e.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([s,n])=>`${ve(s)}: ${ve(n)}`).join(", ")}}`;case"SliceExpression":{const r=e,s=r.start?ve(r.start):"",n=r.stop?ve(r.stop):"",a=r.step?`:${ve(r.step)}`:"";return`${s}:${n}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${ve(r.value)}`}case"Ternary":{const r=e,s=`${ve(r.trueExpr)} if ${ve(r.condition,0)} else ${ve(r.falseExpr)}`;return t>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var jM=class{constructor(e){k(this,"parsed");const t=Z0(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=xM(t)}render(e){const t=new Qr;if(FM(t),e)for(const[n,a]of Object.entries(e))t.set(n,a);return new LM(t).run(this.parsed).value}format(e){return DM(this.parsed,(e==null?void 0:e.indent)||" ")}},qM={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"},la=class Nv{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=Tt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=Tt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const s=Tt.createReadStream(t);this.body=new ReadableStream({start(n){s.on("data",a=>n.enqueue(a)),s.on("end",()=>n.close()),s.on("error",a=>n.error(a))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",qM[t]??"application/octet-stream")}clone(){let t=new Nv(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 Tt.promises.readFile(this.filePath)).buffer}async blob(){const t=await Tt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await Tt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},ca=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(fe.IS_CRYPTO_AVAILABLE){const o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;const t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,s=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))s.push(o&4294967295);s.length||s.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let n=1,a=0;for(let o=Math.max(624,s.length);o>0;--o,++n,++a)n>=624&&(t[0]=t[623],n=1),a>=s.length&&(a=0),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1664525))+s[a]+a>>>0;for(let o=623;o>0;--o,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1566083941))-n>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const s=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^s>>>1^(s&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const s=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(s)*n,this._gauss_next=Math.sin(s)*n}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let s=this._int32()>>>32-r;for(;s>t;)s=this._int32()>>>32-r;const n=e[t];e[t]=e[s],e[s]=n}}choices(e,t){return e[yf(this._random_fn,t)]}};function yf(e,t){let r=0;for(let n=0;n<t.length;++n)r+=t[n];let s=e()*r;for(let n=0;n<t.length;++n)if(s-=t[n],s<0)return n;return t.length-1}var Zt=new ca,yi=Object.freeze({Random:ca,seed:Zt.seed.bind(Zt),random:Zt.random.bind(Zt),gauss:Zt.gauss.bind(Zt),shuffle:Zt.shuffle.bind(Zt),choices:Zt.choices.bind(Zt)}),WM=e=>yf(yi.random,e),HM=new ca,bf=class{constructor(e){this.path=e}async match(e){let t=Yt.join(this.path,e),r=new la(t);if(r.exists)return r}async put(e,t,r=void 0){const s=Yt.join(this.path,e),n=fe.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=HM._int32().toString(36),o=s+`.tmp.${n}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let c=0;await Tt.promises.mkdir(Yt.dirname(s),{recursive:!0});const d=Tt.createWriteStream(o),h=t.body.getReader();for(;;){const{done:_,value:p}=await h.read();if(_)break;await new Promise((v,y)=>{d.write(p,M=>{if(M){y(M);return}v()})}),c+=p.length;const w=l?c/l*100:0;r==null||r({progress:w,loaded:c,total:l})}await new Promise((_,p)=>{d.close(w=>w?p(w):_())}),await Tt.promises.rename(o,s)}catch(i){try{await Tt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=Yt.join(this.path,e);try{return await Tt.promises.unlink(t),!0}catch{return!1}}},QM={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"},Mf=100,XM=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function ua(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function us(e,t=null,r=null){let s;try{s=new URL(e)}catch{return!1}return!(t&&!t.includes(s.protocol)||r&&!r.includes(s.hostname))}function YM(e){return!(!XM.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function JM(e,t,r){if(!r)return null;const s=QM[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}async function KM(e,t,r){const s=e.headers.get("Content-Length");let n=s?parseInt(s,10):r??0;s===null&&!r&&ue.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(n),o=0;const i=e.body.getReader();async function l(){const{done:c,value:d}=await i.read();if(c)return;const h=o+d.length;if(h>n){n=h;const p=new Uint8Array(n);p.set(a),a=p}a.set(d,o),o=h;const _=o/n*100;return t({progress:_,loaded:o,total:n}),l()}return await l(),a}function xf(e){return us(e,["blob:"])}function kf(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof{url:self.location.href}<"u"&&self.location.href)t=self.location.href;else return e;return new URL(e,t).href}var Tf="SHA-256",ZM="experimental_transformers-hash-cache",Ef=e=>({algorithm:Tf,value:e}),Af=(uu=class{constructor(){yo(this,vn,null);k(this,"_getHashCache",()=>(_t(this,vn)??bo(this,vn,caches.open(ZM)),_t(this,vn)));k(this,"match",async e=>{const t=await this._getFileHash(e);if(t)try{const[r]=await navigator.crossOriginStorage.requestFileHandles([Ef(t)]),s=await r.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}});k(this,"put",async(e,t)=>{const r=await this._getFileHash(e);if(r){const s=await t.blob();await this._storeBlobInCOS(s,r)}else this._processAndStore(e,t.body)});k(this,"_storeBlobInCOS",async(e,t)=>{const[r]=await navigator.crossOriginStorage.requestFileHandles([Ef(t)],{create:!0}),s=await r.createWritable();await s.write(e),await s.close()});k(this,"_processAndStore",async(e,t)=>{try{const r=[];for await(const a of t)r.push(a);const s=new Blob(r),n=await this._getBlobHash(s);await this._storeBlobInCOS(s,n);try{await(await this._getHashCache()).put(e,new Response(n))}catch{}}catch{}});k(this,"delete",async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}});k(this,"_getFileHash",async e=>{try{const t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();const s=await this._getLfsFileHash(e);return s?(await t.put(e,new Response(s)),s):null}catch{return null}});k(this,"_getLfsFileHash",async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const s=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return s?s[1]:null}catch{return null}});k(this,"_getBlobHash",async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(Tf,t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")})}},vn=new WeakMap,k(uu,"isAvailable",()=>typeof navigator<"u"&&"crossOriginStorage"in navigator),uu);async function bi(e=null){let t=null;if(be.useCustomCache){if(!be.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!be.customCache.match||!be.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=be.customCache}if(!t&&be.experimental_useCrossOriginStorage&&Af.isAvailable()&&(t=new Af),!t&&be.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(be.cacheKey)}catch(r){ue.warn("An error occurred while opening the browser cache:",r)}}if(!t&&be.useFSCache){if(!fe.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new bf(e??be.cacheDir)}return t}async function ex(e,...t){for(let r of t)try{let s=await e.match(r);if(s)return s}catch{continue}}var tx=(Mg=class{constructor(e){yo(this,yn);yo(this,ft);bo(this,yn,e),bo(this,ft,new Map)}get(e){if(!_t(this,ft).has(e))return;const t=_t(this,ft).get(e);return _t(this,ft).delete(e),_t(this,ft).set(e,t),t}put(e,t){_t(this,ft).has(e)&&_t(this,ft).delete(e),_t(this,ft).set(e,t),_t(this,ft).size>_t(this,yn)&&_t(this,ft).delete(_t(this,ft).keys().next().value)}delete(e){return _t(this,ft).delete(e)}clear(){_t(this,ft).clear()}},yn=new WeakMap,ft=new WeakMap,Mg),rx=100,Mi=new tx(rx);function Cf(e,t){const r=Mi.get(e);if(r!==void 0)return r;const s=t().then(n=>n,n=>(Mi.delete(e),Promise.reject(n)));return Mi.put(e,s),s}async function sx(e){if(!us(e,["http:","https:"]))return null;const t=Sf(e);return t.set("Range","bytes=0-0"),be.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function en(e,t,r={}){const s=JSON.stringify([e,t,r==null?void 0:r.revision,r==null?void 0:r.cache_dir,r==null?void 0:r.local_files_only]);return Cf(s,()=>nx(e,t,r))}async function nx(e,t,r){var c;const s=await bi(r==null?void 0:r.cache_dir),{localPath:n,remoteURL:a,proposedCacheKey:o,validModelId:i}=Pf(e,t,r,s),l=await Ff(s,n,o);if(l!==void 0&&typeof l!="string"){const d=l.headers.get("content-length"),h=l.headers.get("content-type");return{exists:!0,size:d?parseInt(d,10):void 0,contentType:h||void 0,fromCache:!0}}if(be.allowLocalModels&&!us(n,["http:","https:"]))try{const h=await tn(n);if(typeof h!="string"&&h.status!==404){const _=h.headers.get("content-length"),p=h.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:p||void 0,fromCache:!1}}}catch{}if(be.allowRemoteModels&&!r.local_files_only&&i)try{const d=await sx(a);if(d&&d.status>=200&&d.status<300){let h;const _=d.headers.get("content-type");if(d.status===206){const p=d.headers.get("content-range");if(p){const w=p.match(/bytes \d+-\d+\/(\d+)/);w&&(h=parseInt(w[1],10))}}else if(d.status===200)try{await((c=d.body)==null?void 0:c.cancel())}catch{}if(h===void 0){const p=d.headers.get("content-length");h=p?parseInt(p,10):void 0}return{exists:!0,size:h,contentType:_||void 0,fromCache:!1}}}catch(d){ue.warn(`Unable to fetch file metadata for "${a}": ${d}`)}return{exists:!1,fromCache:!1}}async function tn(e){return be.useFS&&!us(e,["http:","https:","blob:"])?new la(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):be.fetch(e,{headers:Sf(e)})}function Sf(e){var s;const t=typeof process<"u"&&((s=process==null?void 0:process.release)==null?void 0:s.name)==="node",r=new Headers;if(t){const n=!!(cr!=null&&cr.TESTING_REMOTELY),a=be.version;if(r.set("User-Agent",`transformers.js/${a}; is_ci/${n};`),us(e,["http:","https:"],["huggingface.co","hf.co"])){const i=(cr==null?void 0:cr.HF_TOKEN)??(cr==null?void 0:cr.HF_ACCESS_TOKEN);i&&r.set("Authorization",`Bearer ${i}`)}}return r}function Pf(e,t,r={},s=null){const n=r.revision??"main",a=ua(e,t),o=YM(e),i=o?ua(be.localModelPath,a):a,l=ua(be.remoteHost,be.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),c=s instanceof bf?n==="main"?a:ua(e,n,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function Ff(e,t,r){if(e)return await ex(e,t,r)}async function ax(e,t,r,s,n,a,o={}){if(await r.match(s)===void 0)if(a){if(typeof n!="string"){const i=new Headers(n.headers);i.set("content-length",a.byteLength.toString()),await r.put(s,new Response(a,{headers:i})).catch(l=>{ue.warn(`Unable to add response to browser cache: ${l}.`)})}}else{const i=o.progress_callback?l=>Pr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(s,n,i)}}async function ox(e,t,r=!0,s={},n=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=Pf(e,t,s,a);let h,_=!1,p;p=await Ff(a,i,c);const w=p!==void 0;if(w)h=c;else{if(be.allowLocalModels)if(us(o,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!be.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{p=await tn(i),h=i}catch(T){ue.warn(`Unable to load from local path "${i}": "${T}"`)}if(p===void 0||typeof p!="string"&&p.status===404){if(s.local_files_only||!be.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await tn(l),p.status!==200)return JM(p.status,l,r);h=c}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200}Pr(s.progress_callback,{status:"download",name:e,file:t});let v;if(!(fe.IS_NODE_ENV&&n)){let M;if(typeof p!="string")if(!s.progress_callback)M=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))M=new Uint8Array(await p.arrayBuffer()),Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M.length,total:M.length});else{let T;const A=p.headers.get("content-length");if(A)T=parseInt(A,10);else try{const S=await en(e,t,s);S.size&&(T=S.size)}catch{}M=await KM(p,S=>{Pr(s.progress_callback,{status:"progress",name:e,file:t,...S})},T)}v=M}if(_&&h&&typeof p!="string"&&await ax(e,t,a,h,p,v,s),fe.IS_NODE_ENV&&n&&s.progress_callback&&typeof p!="string"){const M=parseInt(p.headers.get("content-length"),10)||0;Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M,total:M})}if(Pr(s.progress_callback,{status:"done",name:e,file:t}),v){if(!fe.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return v}if(p instanceof la)return p.filePath;const y=await(a==null?void 0:a.match(h));if(y instanceof la)return y.filePath;if(y instanceof Response)return new Uint8Array(await y.arrayBuffer());if(typeof y=="string")return y;throw new Error("Unable to get model file path or buffer.")}var da=new Map;async function ha(e,t,r=!0,s={},n=!1){if(!be.allowLocalModels){if(s.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(!be.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Pr(s.progress_callback,{status:"initiate",name:e,file:t});const a=`${e}::${t}`;let o=da.get(a);if(!o){const i=await bi(s==null?void 0:s.cache_dir);o=ox(e,t,r,s,n,i).then(l=>(da.delete(a),l),l=>{throw da.delete(a),l}),da.set(a,o)}return await o}async function xi(e,t,r=!0,s={}){const n=await ha(e,t,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function er(e,t,r=!0,s={}){const n=await xi(e,t,r,s);return n===null?{}:JSON.parse(n)}function ix(e,[t,r,s],[n,a],o="bilinear",i=!1){const l=a/s,c=n/r,d=new e.constructor(n*a*t),h=r*s,_=n*a;for(let p=0;p<n;++p)for(let w=0;w<a;++w){const v=p*a+w,y=(w+.5)/l-.5,M=(p+.5)/c-.5;let T=Math.floor(y),A=Math.floor(M);const S=Math.min(T+1,s-1),C=Math.min(A+1,r-1);T=Math.max(T,0),A=Math.max(A,0);const I=y-T,x=M-A,R=(1-I)*(1-x),z=I*(1-x),$=(1-I)*x,Q=I*x,H=A*s,D=C*s,O=H+T,te=H+S,W=D+T,ee=D+S;for(let G=0;G<t;++G){const L=G*h;d[G*_+v]=R*e[L+O]+z*e[L+te]+$*e[L+W]+Q*e[L+ee]}}return d}function lx(e,t,r){const s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=t[r[i]],l*=s[i];const a=r.map((i,l)=>n[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);o[l]=e[i]}return[o,s]}function nt(e){const t=je(e)[0],r=e.map(a=>Math.exp(a-t)),s=r.reduce((a,o)=>a+o,0);return r.map(a=>a/s)}function cx(e){const t=je(e)[0];let r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);const s=Math.log(r);return e.map(a=>a-t-s)}function ki(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return[t,r]}function je(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]>t&&(t=e[s],r=s);return[t,r]}function Lf(e){return e>0&&(e&e-1)===0}var If=class{constructor(e){if(this.size=e|0,this.size<=1||!Lf(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;r<this.table.length;r+=2){const s=Math.PI*r/this.size;this.table[r]=Math.cos(s),this.table[r+1]=-Math.sin(s)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let s=0;s<this._width;s+=2){const n=this._width-s-2;this._bitrev[r]|=(r>>>s&3)<<n}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const r=t||new Array(e.length>>>1);for(let s=0;s<e.length;s+=2)r[s>>>1]=e[s];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let s=0;s<r.length;s+=2)r[s]=e[s>>>1],r[s+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size}_transform4(e,t,r){const s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const h=c[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<s;i+=o,++l){const h=c[l];this._singleTransform4(t,e,i,h,a,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;const h=o>>>2;for(i=0;i<s;i+=o){const _=i+h-1;for(let p=i,w=0;p<_;p+=2,w+=a){const v=p,y=v+h,M=y+h,T=M+h,A=e[v],S=e[v+1],C=e[y],I=e[y+1],x=e[M],R=e[M+1],z=e[T],$=e[T+1],Q=d[w],H=r*d[w+1],D=C*Q-I*H,O=C*H+I*Q,te=d[2*w],W=r*d[2*w+1],ee=x*te-R*W,G=x*W+R*te,L=d[3*w],V=r*d[3*w+1],X=z*L-$*V,J=z*V+$*L,we=A+ee,re=S+G,Fe=A-ee,qe=S-G,bt=D+X,It=O+J,Ot=r*(D-X),Qe=r*(O-J);e[v]=we+bt,e[v+1]=re+It,e[y]=Fe+Qe,e[y+1]=qe-Ot,e[M]=we-bt,e[M+1]=re-It,e[T]=Fe-Qe,e[T+1]=qe+Ot}}}}_singleTransform2(e,t,r,s,n){const a=e[s],o=e[s+1],i=e[s+n],l=e[s+n+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+1],d=e[s+n],h=e[s+n+1],_=e[s+o],p=e[s+o+1],w=e[s+i],v=e[s+i+1],y=l+_,M=c+p,T=l-_,A=c-p,S=d+w,C=h+v,I=a*(d-w),x=a*(h-v);t[r]=y+S,t[r+1]=M+C,t[r+2]=T+x,t[r+3]=A-I,t[r+4]=y-S,t[r+5]=M-C,t[r+6]=T-x,t[r+7]=A+I}_realTransform4(e,t,r){const s=this._csize;let a=1<<this._width,o=s/a<<1,i,l;const c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){const _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1)}else for(i=0,l=0;i<s;i+=o,++l){const _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;const _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<s;i+=o)for(let v=0,y=0;v<=w;v+=2,y+=a){const M=i+v,T=M+p,A=T+p,S=A+p,C=e[M],I=e[M+1],x=e[T],R=e[T+1],z=e[A],$=e[A+1],Q=e[S],H=e[S+1],D=C,O=I,te=d[y],W=r*d[y+1],ee=x*te-R*W,G=x*W+R*te,L=d[2*y],V=r*d[2*y+1],X=z*L-$*V,J=z*V+$*L,we=d[3*y],re=r*d[3*y+1],Fe=Q*we-H*re,qe=Q*re+H*we,bt=D+X,It=O+J,Ot=D-X,Qe=O-J,pt=ee+Fe,Me=G+qe,ce=r*(ee-Fe),Pe=r*(G-qe);if(e[M]=bt+pt,e[M+1]=It+Me,e[T]=Ot+Pe,e[T+1]=Qe-ce,v===0){e[A]=bt-pt,e[A+1]=It-Me;continue}if(v===w)continue;const mt=i+p-v,nr=i+_-v;e[mt]=Ot-r*Pe,e[mt+1]=-Qe-r*ce,e[nr]=bt-r*pt,e[nr+1]=-It+r*Me}}const h=s>>>1;for(let _=2;_<h;_+=2)e[s-_]=e[_],e[s-_+1]=-e[_+1]}_singleRealTransform2(e,t,r,s,n){const a=e[s],o=e[s+n];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,s,n,a){const o=n*2,i=n*3,l=e[s],c=e[s+n],d=e[s+o],h=e[s+i],_=l+d,p=l-d,w=c+h,v=a*(c-h);t[r]=_+w,t[r+1]=0,t[r+2]=p,t[r+3]=-v,t[r+4]=_-w,t[r+5]=0,t[r+6]=p,t[r+7]=v}},ux=class{constructor(e){const t=2*(e-1),r=2*(2*e-1),s=2**Math.ceil(Math.log2(r));this.bufferSize=s,this._a=t;const n=new Float64Array(r),a=new Float64Array(s);this._chirpBuffer=new Float64Array(s),this._buffer1=new Float64Array(s),this._buffer2=new Float64Array(s),this._outBuffer1=new Float64Array(s),this._outBuffer2=new Float64Array(s);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){const d=(c+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),p=2*c;n[p]=h*Math.cos(_),n[p+1]=h*Math.sin(_),a[p]=n[p],a[p+1]=-n[p+1]}this._slicedChirpBuffer=n.subarray(t,r),this._f=new If(s>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const s=this._buffer1,n=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(r)for(let d=0;d<l.length;d+=2){const h=d+1,_=d>>1,p=t[_];s[d]=p*l[d],s[h]=p*l[h]}else for(let d=0;d<l.length;d+=2){const h=d+1;s[d]=t[d]*l[d]-t[h]*l[h],s[h]=t[d]*l[h]+t[h]*l[d]}this._f.transform(a,s);for(let d=0;d<i.length;d+=2){const h=d+1;n[d]=a[d]*i[d]-a[h]*i[h],n[h]=a[d]*i[h]+a[h]*i[d]}this._f.inverseTransform(o,n);for(let d=0;d<o.length;d+=2){const h=o[d+c],_=o[d+c+1],p=l[d],w=l[d+1];e[d]=h*p-_*w,e[d+1]=h*w+_*p}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},dx=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Lf(e),this.isPowerOfTwo?(this.fft=new If(e),this.outputBufferSize=2*e):(this.fft=new ux(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function hx(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const r=new e.constructor(e.length),s=new e.constructor(t),n=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-n;i<=n;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),s[o++]=e[l]}s.sort(),r[a]=s[n]}return r}function rn(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function fx(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function _x(e){const t=e.length,r=e[0].length,s=[t+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;const a=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let d=1;d<s[1];++d)for(let h=1;h<s[0];++h){const _=n[h-1][d-1],p=n[h-1][d],w=n[h][d-1];let v,y;_<p&&_<w?(v=_,y=0):p<_&&p<w?(v=p,y=1):(v=w,y=2),n[h][d]=e[h-1][d-1]+v,a[h][d]=y}for(let d=0;d<s[1];++d)a[0][d]=2;for(let d=0;d<s[0];++d)a[d][0]=1;let o=t,i=r,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var px=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0;const d=(l&32768)<<16,h=(l&31744)>>10;let _=l&1023;if(h===31)c=d|2139095040|_<<13;else if(h===0)if(_===0)c=d;else{let p=113;for(;(_&1024)===0;)_<<=1,--p;_&=-1025,c=d|p<<23|_<<13}else c=d|h+112<<23|_<<13;o[0]=c,e[l]=i[0]}}const r=t.length,s=e,n=new Float32Array(r);for(let a=0;a<r;++a)n[a]=s[t[a]];return n}})(),Of={};os(Of,{default:()=>mx});var mx={};async function Nf(e){const t=e.split("/").pop();let r;try{if(r=await bi(),r){const n=await r.match(e);if(n)return n}}catch(n){ue.warn(`Failed to load ${t} from cache:`,n)}const s=await be.fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone())}catch(n){ue.warn(`Failed to cache ${t}:`,n)}return s}async function gx(e){const t=await Nf(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ue.warn("Failed to read WASM binary:",r),null}}async function wx(e){if(fe.IS_SERVICE_WORKER_ENV||fe.IS_CHROME_AVAILABLE)return e;const t=await Nf(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ue.warn("Failed to read WASM factory:",r),null}}var vx=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 Df(e){return e<=Bt.DEBUG?0:e<=Bt.INFO?2:e<=Bt.WARNING||e<=Bt.ERROR?3:4}var yx={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ft=[],Ti,Fr,zf=Symbol.for("onnxruntime");if(zf in globalThis)Fr=globalThis[zf];else if(fe.IS_NODE_ENV){switch(Fr=Of,process.platform){case"win32":Ft.push("dml");break;case"linux":process.arch==="x64"&&Ft.push("cuda");break;case"darwin":Ft.push("coreml");break}Ft.push("webgpu"),Ft.push("cpu"),Ti=["cpu"]}else Fr=cy,fe.IS_WEBNN_AVAILABLE&&Ft.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),fe.IS_WEBGPU_AVAILABLE&&Ft.push("webgpu"),Ft.push("wasm"),Ti=["wasm"];var bx=Fr.InferenceSession;function Mx(e=null){if(!e)return Ti;switch(e){case"auto":return Ft;case"gpu":return Ft.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(Ft.includes(e))return[vx[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Ft.join(", ")}.`)}var Bf=Promise.resolve(),ds=null;async function xx(){var t,r,s,n,a;if(ds)return ds;if(!(be.useWasmCache&&typeof((t=Ie==null?void 0:Ie.wasm)==null?void 0:t.wasmPaths)=="object"&&((s=(r=Ie==null?void 0:Ie.wasm)==null?void 0:r.wasmPaths)==null?void 0:s.wasm)&&((a=(n=Ie==null?void 0:Ie.wasm)==null?void 0:n.wasmPaths)==null?void 0:a.mjs))){if(fe.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return ds=Promise.resolve(),ds}return ds=(async()=>{const o=Ie.wasm.wasmPaths;let i=!1;await Promise.all([o.wasm&&!xf(o.wasm)?(async()=>{try{const l=await gx(kf(o.wasm));l&&(Ie.wasm.wasmBinary=l,i=!0)}catch(l){ue.warn("Failed to pre-load WASM binary:",l)}})():Promise.resolve(),o.mjs&&!xf(o.mjs)?(async()=>{try{const l=await wx(kf(o.mjs));l&&(Ie.wasm.wasmPaths.mjs=l)}catch(l){ue.warn("Failed to pre-load WASM factory:",l)}})():Promise.resolve()]),i||(Ie.wasm.wasmPaths.mjs=o.mjs)})(),ds}async function Rf(e,t,r){await xx();const s=Df(be.logLevel??Bt.WARNING),n=()=>bx.create(e,{logSeverityLevel:s,...t}),a=await(fe.IS_WEB_ENV?Bf=Bf.then(n):n());return a.config=r,a}var Gf=Promise.resolve();async function $f(e,t){const r=()=>e.run(t);return fe.IS_WEB_ENV?Gf=Gf.then(r):r()}function Vf(e){return e instanceof Fr.Tensor}var Ie=Fr==null?void 0:Fr.env;function Ei(){var e;return(e=Ie==null?void 0:Ie.wasm)==null?void 0:e.proxy}if(Ie){let e=function(t){const r=Df(t);Ie.logLevel=yx[r]};if(Ie.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&((xg=Ie.versions)!=null&&xg.web)&&!Ie.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ie.versions.web}/dist/`;Ie.wasm.wasmPaths=fe.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}Ie.wasm.proxy=!1}Ie.webgpu&&(Ie.webgpu.powerPreference="high-performance"),e(be.logLevel??Bt.WARNING),be.backends.onnx={...Ie,setLogLevel:e}}var Lr=async(e,t,r)=>{const s=await Rf(new Uint8Array(e),t);return(async n=>{const a=Ei(),o=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await $f(s,o);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},hs=(du=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Lr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Lr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Lr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Lr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Lr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Lr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Lr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Lr([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}},k(du,"session_options",{}),du),kx=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"}),Ai=fe.IS_NODE_ENV?"cpu":"wasm";function Uf(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Ai}).`),Ai):Ai}var Tx=(function(){let e;return async function(){if(e===void 0)if(!fe.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),We=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),jf=We.fp32,qf=Object.freeze({[kx.wasm]:We.q8}),Ci=Object.freeze({[We.fp32]:"",[We.fp16]:"_fp16",[We.int8]:"_int8",[We.uint8]:"_uint8",[We.q8]:"_quantized",[We.q4]:"_q4",[We.q2]:"_q2",[We.q1]:"_q1",[We.q4f16]:"_q4f16",[We.q2f16]:"_q2f16",[We.q1f16]:"_q1f16",[We.bnb4]:"_bnb4"});function Wf(e,t,r,{configDtype:s=null,warn:n}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===We.auto){if(s){const l=typeof s=="string"?s:s==null?void 0:s[t];if(l&&l!==We.auto&&We.hasOwnProperty(l))return l}i=qf[r]??jf}else a&&We.hasOwnProperty(a)?i=a:i=qf[r]??jf;return o&&n&&n(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var sn=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),U=class Ue{constructor(...t){k(this,"ort_tensor");return Vf(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new yy(t[0],t[1],t[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const s=r.reduce((n,a)=>n*a);for(let n=0;n<t;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(t){const[r,...s]=this.dims;if(t=tr(t,r),s.length>0){const n=s.reduce((a,o)=>a*o);return this._subarray(t,n,s)}else return new Ue(this.type,[this.data[t]],s)}indexOf(t){const r=this.data;for(let s=0;s<r.length;++s)if(r[s]==t)return s;return-1}_subarray(t,r,s){const n=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new Ue(this.type,o,s)}item(){const t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return Ex(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]=t(r[s],s,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const r=this.data;for(let s=0;s<r.length;++s)r[s]-=t;return this}clone(){return new Ue(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],s=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=tr(h,this.dims[d],d),s.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[_,p]=h;if(_=_===null?0:tr(_,this.dims[d],d,!1),p=p===null?this.dims[d]:tr(p,this.dims[d],d,!1),_>p)throw new Error(`Invalid slice: ${h}`);const w=[Math.max(_,0),Math.min(p,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${h}`)}const n=s.map(([d,h])=>h-d),a=n.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride();let c=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){c=!1;break}if(c){const d=s[0][0]*l[0],h=s[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,h));else if(Array.isArray(o)){const _=o.slice(d,h);for(let p=0;p<_.length;++p)i[p]=_[p]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let h=0;for(let _=n.length-1,p=d;_>=0;--_){const w=n[_];h+=(p%w+s[_][0])*l[_],p=Math.floor(p/w)}i[d]=o[h]}return new Ue(this.type,i,r)}permute(...t){return Ax(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,s=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const n=this.data,a=n instanceof BigInt64Array||n instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a?(o=(h,_)=>h+_,i=0n):(o=(h,_)=>h+_**t,i=0),r===null){let h=n.reduce(o,i);return t!==1&&(h=h**(1/t)),new Ue(this.type,[h],[])}const[l,c,d]=nn(o,this,r,s);if(t!==1)for(let h=0;h<c.length;++h)c[h]=c[h]**(1/t);return new Ue(l,c,d)}normalize_(t=2,r=1){r=tr(r,this.dims.length);const s=this.norm(t,r,!0),n=this.data,a=s.data;for(let o=0;o<n.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){const h=this.dims[l];if(l!==r){const _=c%h;i+=_*d,d*=this.dims[l]}c=Math.floor(c/h)}n[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Pi(this.dims)}squeeze(t=null){return new Ue(this.type,this.data,Xf(this.dims,t))}squeeze_(t=null){return this.dims=Xf(this.dims,t),this}unsqueeze(t){return new Ue(this.type,this.data,Yf(this.dims,t))}unsqueeze_(t){return this.dims=Yf(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,t),n=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...s,n.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let n=0;n<t.length;++n)if(t[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}const s=this.data;if(r!==-1){const n=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=s.length/n}return new Ue(this.type,s,t)}neg_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>t?1:0;return new Ue("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<t?1:0;return new Ue("bool",r,this.dims)}clamp_(t,r){const s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return Si(this,t,r)}min(t=null,r=!1){if(t===null){const o=ki(this.data)[0];return new Ue(this.type,[o],[])}const[s,n,a]=nn((o,i)=>Math.min(o,i),this,t,r,1/0);return new Ue(s,n,a)}max(t=null,r=!1){if(t===null){const o=je(this.data)[0];return new Ue(this.type,[o],[])}const[s,n,a]=nn((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Ue(s,n,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=ki(this.data)[1];return new Ue("int64",[BigInt(s)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=je(this.data)[1];return new Ue("int64",[BigInt(s)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(d=>d===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,h=Array(d).fill(1).concat(this.dims);return new Ue(this.type,this.data.slice(),h)}const r=t.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((d,h)=>d*t[h]),a=n.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=Pi(s),c=Pi(n);for(let d=0;d<a;++d){let h=d,_=0;for(let p=0;p<n.length;++p){const w=Math.floor(h/c[p]);h=h%c[p];const v=w%s[p];_+=v*l[p]}i[d]=o[_]}return new Ue(this.type,i,n)}tile(...t){if(t.length<this.dims.length){const r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!sn.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r;const s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Ue(t,px(this.data),this.dims);return new Ue(t,sn[t].from(this.data,r),this.dims)}};function Ex(e,t){const r=e.length,s=t.reduce((a,o)=>a*o);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let a=t.length-1;a>=0;a--)n=n.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return n[0]}function Ax(e,t){const[r,s]=lx(e.data,e.dims,t);return new U(e.type,r,s)}function Hf(e,[t,r],s="bilinear",n=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=ix(e.data,[a,o,i],[t,r],s,n);return new U(e.type,l,[a,t,r])}async function jt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(t.length===2)s=[...e.dims.slice(0,2),...t];else if(t.length===3)s=[e.dims[0],...t];else if(t.length===4)s=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await hs.nearest_interpolate_4d;else if(r==="bilinear")n=await hs.bilinear_interpolate_4d;else if(r==="bicubic")n=await hs.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new U("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:e,s:a})}async function Cx(e,t){return await(await hs.matmul)({a:e,b:t})}async function fs(e,t){const r=await hs.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new U("int64",[BigInt(t)],[1])})}var fa=e=>new U("int64",e,[e.length]);async function Qf(e,t,r,s,n){return await(await hs.slice)({x:e,s:fa(t),e:fa(r),a:fa(s),t:fa(new Array(s.length).fill(1))})}function Sx(e,t){const r=e.data,s=t.data,n=[e.dims[0],e.dims[2]],a=new r.constructor(n[0]*n[1]),[o,i,l]=e.dims;let c=0;for(let d=0;d<o;++d){const h=d*l*i;for(let _=0;_<l;++_){let p=0,w=0;const v=d*i,y=h+_;for(let T=0;T<i;++T){const A=Number(s[v+T]);w+=A,p+=r[y+T*l]*A}const M=p/w;a[c++]=M}}return new U(e.type,a,n)}function Xf(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,s)=>r!==1||!t.includes(s))),e}function Yf(e,t){return t=tr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function tr(e,t,r=null,s=!0){if(e<-t||e>=t){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function ze(e,t=0){t=tr(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const s=r.reduce((o,i)=>o*i,1),n=new e[0].data.constructor(s),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;n.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){const{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let h=0;for(let _=c.length-1,p=d,w=1;_>=0;--_){const v=c[_];let y=p%v;_===t&&(y+=o),h+=y*w,w*=r[_],p=Math.floor(p/v)}n[h]=l[d]}o+=c[t]}}return new U(a,n,r)}function dr(e,t=0){return ze(e.map(r=>r.unsqueeze(t)),t)}function nn(e,t,r,s=!1,n=null){const a=t.data,o=t.dims;r=tr(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);n!==null&&l.fill(n);for(let c=0;c<a.length;++c){let d=0;for(let h=o.length-1,_=c,p=1;h>=0;--h){const w=o[h];if(h!==r){const v=_%w;d+=v*p,p*=i[h]}_=Math.floor(_/w)}l[d]=e(l[d],a[c],c,d)}return s||i.splice(r,1),[t.type,l,i]}function Px(e,t=null,r=1,s=!1){const n=e.data,a=e.dims;if(t===null){const p=n.reduce((M,T)=>M+T,0)/n.length,w=Math.sqrt(n.reduce((M,T)=>M+(T-p)**2,0)/(n.length-r)),v=new U(e.type,[p],[]);return[new U(e.type,[w],[]),v]}t=tr(t,a.length);const o=Si(e,t,s),i=o.data,[l,c,d]=nn((_,p,w,v)=>_+(p-i[v])**2,e,t,s);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return[new U(l,c,d),o]}function Si(e,t=null,r=!1){const s=e.dims,n=e.data;if(t===null){const l=n.reduce((c,d)=>c+d,0);return new U(e.type,[l/n.length],[])}t=tr(t,s.length);const[a,o,i]=nn((l,c)=>l+c,e,t,r);if(s[t]!==1)for(let l=0;l<o.length;++l)o[l]/=s[t];return new U(a,o,i)}function Pi(e){const t=new Array(e.length);for(let r=e.length-1,s=1;r>=0;--r)t[r]=s,s*=e[r];return t}function Fi(e,t,r,s){const n=e.reduce((a,o)=>a*o,1);return new U(r,new s(n).fill(t),e)}function ct(e,t){let r,s;if(typeof t=="number")r="float32",s=Float32Array;else if(typeof t=="bigint")r="int64",s=BigInt64Array;else if(typeof t=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Fi(e,t,r,s)}function Li(e,t){return ct(e.dims,t)}function yt(e){return Fi(e,1n,"int64",BigInt64Array)}function Jf(e){return yt(e.dims)}function Kf(e){return Fi(e,0n,"int64",BigInt64Array)}function Zf(e){return Kf(e.dims)}function Fx(e){const t=e.reduce((r,s)=>r*s,1);return new U("float32",Float32Array.from({length:t},()=>yi.gauss()),e)}function Lx(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const r=t==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,a=e.data,o=new n(a.length/8);for(let i=0;i<a.length;++i){const l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,r&&d===0&&(o[c]-=128)}return new U(s,o,[e.dims[0],e.dims[1]/8])}async function e_(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await en(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function t_(e,t){const r=await e_(e);return await Promise.all(r.map(s=>er(e,s,!0,t)))}function Ii(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var Ix=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ox(e,t,r,s){for(const n of Object.keys(e)){const a=t-e[n].length,o=r(n),i=new Array(a).fill(o);e[n]=s==="right"?Jt(e[n],i):Jt(i,e[n])}}function Nx(e,t){for(const r of Object.keys(e))e[r].length=t}function Xr(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const s=e[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function Dx(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var le=class extends vt{constructor(t,r){super();k(this,"return_token_type_ids",!1);k(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new X0(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Xr(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Xr(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Xr(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Xr(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Xr(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Xr(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const n=Object.create(null);for(const{name:a,template:o}of this.chat_template){if(typeof a!="string"||typeof o!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[a]=o}this.chat_template=n}this._compiled_template_cache=new Map;const s=Dx(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){const i=await t_(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,r={}){const{text_pair:s=null,add_special_tokens:n=!0,padding:a=!1,return_token_type_ids:o=null}=r;let{truncation:i=null,max_length:l=null}=r;const c=r.return_tensor??!0,d=Array.isArray(t);let h;if(d){if(t.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(t.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=t.map((p,w)=>this._encode_plus(p,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:o}))}else h=t.map(p=>this._encode_plus(p,{add_special_tokens:n,return_token_type_ids:o}))}else{if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(t,{text_pair:s,add_special_tokens:n,return_token_type_ids:o})]}if(l===null?l=this.model_max_length:i===null&&(a===!0?(ue.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):a===!1&&(ue.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)),a===!0&&(l=Math.min(je(h.map(p=>p.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),a||i)for(let p=0;p<h.length;++p)h[p].input_ids.length!==l&&(h[p].input_ids.length>l?i&&Nx(h[p],l):a&&Ox(h[p],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));const _={};if(c){if(!(a&&i)&&h.some(w=>{var v;for(const y of Object.keys(w))if(w[y].length!==((v=h[0][y])==null?void 0:v.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const p=[h.length,h[0].input_ids.length];for(const w of Object.keys(h[0]))_[w]=new U("int64",BigInt64Array.from(h.flatMap(v=>v[w]).map(BigInt)),p)}else{for(const p of Object.keys(h[0]))_[p]=h.map(w=>w[p]);if(!d)for(const p of Object.keys(_))_[p]=_[p][0]}return _}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){const{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:s})}encode(t,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(t,r={}){return t instanceof U&&(t=t.tolist()),t.map(s=>this.decode(s,r))}decode(t,r={}){if(t instanceof U&&(t=Ii(t)),!Array.isArray(t)||t.length===0||!Dy(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const s=this.chat_template;if(t!==null&&Object.hasOwn(s,t))t=s[t];else if(t===null)if(r!==null&&"tool_use"in s)t=s.tool_use;else if("default"in s)t=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(t===null)if(this.chat_template)t=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return t}apply_chat_template(t,r={}){let{tools:s=null,documents:n=null,chat_template:a=null,add_generation_prompt:o=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:d=null,return_tensor:h=!0,return_dict:_=!0,tokenizer_kwargs:p={},...w}=r;if(a=this.get_chat_template({chat_template:a,tools:s}),typeof a!="string")throw Error(`chat_template must be a string, but got ${typeof a}`);let v=this._compiled_template_cache.get(a);v===void 0&&(v=new jM(a),this._compiled_template_cache.set(a,v));const y=Object.create(null);for(const T of Ix){const A=Xr(this.config,T);A&&(y[T]=A)}const M=v.render({messages:t,add_generation_prompt:o,tools:s,documents:n,...y,...w});if(i){const T=this._call(M,{add_special_tokens:!1,padding:l,truncation:c,max_length:d,return_tensor:h,...p});return _?T:T.input_ids}return M}};function Oi(e,t,r,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const n=s.src_lang,a=s.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(n);break}}return s.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var r_={};os(r_,{AlbertTokenizer:()=>zx,AutoTokenizer:()=>Te,BartTokenizer:()=>Bx,BertTokenizer:()=>Rx,BlenderbotSmallTokenizer:()=>Gx,BlenderbotTokenizer:()=>$x,BloomTokenizer:()=>Vx,CLIPTokenizer:()=>jx,CamembertTokenizer:()=>Ux,CodeGenTokenizer:()=>Wx,CodeLlamaTokenizer:()=>qx,CohereAsrTokenizer:()=>Qx,CohereTokenizer:()=>Hx,ConvBertTokenizer:()=>Xx,DebertaTokenizer:()=>Jx,DebertaV2Tokenizer:()=>Yx,DistilBertTokenizer:()=>Kx,ElectraTokenizer:()=>Zx,EsmTokenizer:()=>e1,FalconTokenizer:()=>t1,GPT2Tokenizer:()=>n1,GPTNeoXTokenizer:()=>s1,GemmaTokenizer:()=>r1,HerbertTokenizer:()=>a1,LlamaTokenizer:()=>o1,M2M100Tokenizer:()=>i1,MBart50Tokenizer:()=>c1,MBartTokenizer:()=>s_,MPNetTokenizer:()=>h1,MarianTokenizer:()=>l1,MgpstrTokenizer:()=>u1,MobileBertTokenizer:()=>d1,NllbTokenizer:()=>f1,NougatTokenizer:()=>_1,PreTrainedTokenizer:()=>le,Qwen2Tokenizer:()=>p1,RoFormerTokenizer:()=>g1,RobertaTokenizer:()=>m1,SiglipTokenizer:()=>w1,SpeechT5Tokenizer:()=>v1,SqueezeBertTokenizer:()=>y1,T5Tokenizer:()=>b1,TokenizersBackend:()=>le,VitsTokenizer:()=>x1,Wav2Vec2CTCTokenizer:()=>k1,WhisperTokenizer:()=>S1,XLMRobertaTokenizer:()=>P1,XLMTokenizer:()=>F1});var zx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Bx=class extends le{},Rx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Gx=class extends le{},$x=class extends le{},Vx=class extends le{},Ux=class extends le{},jx=class extends le{},qx=class extends le{},Wx=class extends le{},Hx=class extends le{},Qx=class extends le{},Xx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Yx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Jx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},Kx=class extends le{},Zx=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},e1=class extends le{},t1=class extends le{},r1=class extends le{},s1=class extends le{},n1=class extends le{},a1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},o1=class extends le{constructor(){super(...arguments);k(this,"padding_side","left")}},i1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},l1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),ue.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[s,n]=r;return this.supported_language_codes.includes(s)||ue.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Jt([s],super._encode_text(n))}}},s_=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},c1=class extends s_{},u1=class extends le{},d1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},h1=class extends le{},f1=class extends le{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Oi(this,e,t,r)}},_1=class extends le{},p1=class extends le{},m1=class extends le{},g1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},w1=class extends le{},v1=class extends le{},y1=class extends le{constructor(){super(...arguments);k(this,"return_token_type_ids",!0)}},b1=class extends le{},M1=class extends $t{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},x1=class extends le{constructor(e,t){super(e,t),this._tokenizer.decoder=new M1({type:"VitsDecoder"})}},k1=class extends le{},n_=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],_a=new Map(n_),T1=new Map([...n_.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function E1(e){e=e.toLowerCase();let t=T1.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),_a.has(e))t=e;else{const n=e.length===2?_a.keys():_a.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}var A1="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",a_=new RegExp(`^[${A1}]+$`,"gu"),C1=.1,S1=class extends le{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:n=!0}={}){if(s===null)throw Error("Must specify time_precision");let a=null;const o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let c=i(),d=0;const h=this.timestamp_begin,p=h+1500;let w=[],v=[],y=!1,M=null;const T=new Set(this.all_special_ids);for(const C of e){const I=C.tokens,x=o?C.token_timestamps:null;let R=null,z=h;if("stride"in C){const[H,D,O]=C.stride;if(d-=D,M=H-O,D&&(z=D/s+h),O)for(let te=I.length-1;te>=0;--te){const W=Number(I[te]);if(W>=h){if(R!==null&&(W-h)*s<M)break;R=W}}}let $=[],Q=[];for(let H=0;H<I.length;++H){const D=Number(I[H]);if(T.has(D)){const O=this.decode([D]),te=_a.get(O.slice(2,-2));if(te!==void 0){if(a!==null&&te!==a&&!t){w.push($);const W=this.findLongestCommonSequence(w)[0],ee=this.decode(W);c.text=ee,l.push(c),w=[],$=[],c=i()}a=c.language=te}}else if(D>=h&&D<=p){const O=(D-h)*s+d,te=rn(O,2);if(R!==null&&D>=R)y=!0;else if(y||w.length>0&&D<z)y=!1;else if(c.timestamp[0]===null)c.timestamp[0]=te;else if(te!==c.timestamp[0]){c.timestamp[1]=te,w.push($),o&&v.push(Q);const[W,ee]=this.findLongestCommonSequence(w,v),G=this.decode(W);if(c.text=G,o&&(c.words=this.collateWordTimestamps(W,ee,a),c.words.length>0&&c.timestamp[1]!==null))for(const L of c.words)L.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=L.timestamp[0]&&(L.timestamp[1]=c.timestamp[1]);l.push(c),w=[],$=[],v=[],Q=[],c=i()}}else if($.push(D),o){let O=rn(x[H]+d,2),te;if(H+1<x.length){te=rn(x[H+1]+d,2);const W=this.decode([D]);a_.test(W)&&(te=rn(Math.min(O+s,te),2))}else te=null;Q.push([O,te])}}if("stride"in C){const[H,D,O]=C.stride;d+=H-O}$.length>0?(w.push($),o&&v.push(Q)):w.every(H=>H.length===0)&&(c=i(),w=[],$=[],v=[],Q=[])}if(w.length>0){if(n&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[C,I]=this.findLongestCommonSequence(w,v),x=this.decode(C);c.text=x,o&&(c.words=this.collateWordTimestamps(C,I,a)),l.push(c)}let A=Object.create(null);const S=l.map(C=>C.text).join("");if(t||r){for(let C=0;C<l.length;++C){const I=l[C];t||delete I.timestamp,r||delete I.language}if(o){const C=[];for(const I of l)for(const x of I.words)C.push(x);A={chunks:C}}else A={chunks:l}}return[S,A]}findLongestCommonSequence(e,t=null){let r=e[0],s=r.length,n=[];const a=Array.isArray(t)&&t.length>0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,h=[s,s,0,0];const _=c.length;for(let A=1;A<s+_;++A){const S=Math.max(0,s-A),C=Math.min(s,s+_-A),I=r.slice(S,C),x=Math.max(0,A-s),R=Math.min(_,A),z=c.slice(x,R);if(I.length!==z.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let $;a?$=I.filter((D,O)=>D===z[O]&&i[S+O][0]-C1<=t[l][x+O][0]).length:$=I.filter((D,O)=>D===z[O]).length;const Q=A/1e4,H=$/A+Q;$>1&&H>d&&(d=H,h=[S,C,x,R])}const[p,w,v,y]=h,M=Math.floor((w+p)/2);let T=Math.floor((y+v)/2);if(a&&d===0&&s>0){const A=i[s-1][0],S=t[l].findIndex(C=>C[0]>=A);T=S===-1?c.length:S}n.push(...r.slice(0,M)),r=c.slice(T),s=r.length,a&&(o.push(...i.slice(0,M)),i=t[l].slice(T))}return n.push(...r),a?(o.push(...i),[n,o]):[n,[]]}collateWordTimestamps(e,t,r){const[s,n,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<s.length;++i){const l=a[i];o.push({text:s[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,s=`"'.。,,!!??::”)]}、`){t=t??"english";let n,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,a,o]=this.splitTokensOnUnicode(e):[n,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,a,o,r,s)}decode(e,t){let r;return t!=null&&t.decode_with_timestamps?(e instanceof U&&(e=Ii(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){const r=(t==null?void 0:t.time_precision)??.02,s=this.all_special_ids.at(-1)+1;let n=[[]];for(let a of e)if(a=Number(a),a>=s){const o=((a-s)*r).toFixed(2);n.push(`<|${o}|>`),n.push([])}else n[n.length-1].push(a);return n=n.map(a=>typeof a=="string"?a:super.decode(a,t)),n.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],n=[],a=[];let o=[],i=[],l=0;for(let c=0;c<e.length;++c){const d=e[c];o.push(d),i.push(c);const h=this.decode(o,{decode_with_timestamps:!0});(!h.includes(r)||t[l+h.indexOf(r)]===r)&&(s.push(h),n.push(o),a.push(i),o=[],i=[],l+=h.length)}return[s,n,a]}splitTokensOnSpaces(e){const[t,r,s]=this.splitTokensOnUnicode(e),n=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],c=r[i],d=s[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=a_.test(p);if(h||_||w||n.length===0)n.push(l),a.push(c),o.push(d);else{const v=n.length-1;n[v]+=l,a[v].push(...c),o[v].push(...d)}}return[n,a,o]}mergePunctuations(e,t,r,s,n){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(r);let l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&s.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=Jt(o[l],o[c]),i[c]=Jt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&n.includes(a[c])?(a[l]+=a[c],o[l]=Jt(o[l],o[c]),i[l]=Jt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},P1=class extends le{},F1=class extends le{constructor(t,r){super(t,r);k(this,"return_token_type_ids",!0);ue.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Te=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:a="main"}={}){var d;const[o,i]=await t_(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a}),l=((d=i.tokenizer_class)==null?void 0:d.replace(/Fast$/,""))??"PreTrainedTokenizer";let c=r_[l];return c||(ue.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=le),new c(o,i)}},pa="https://github.com/huggingface/transformers.js/issues/new/choose",Ni="preprocessor_config.json",an=Ni,o_="processor_config.json",i_="chat_template.jinja",Ee=(bn=class extends vt{constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([this.uses_processor_config?er(e,o_,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?xi(e,i_,!0,t):null]);return new this(r,s,n)}},k(bn,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),k(bn,"uses_processor_config",!1),k(bn,"uses_chat_template_file",!1),bn),Di={};os(Di,{ChatterboxProcessor:()=>ok,CohereAsrProcessor:()=>lk,Florence2Processor:()=>cT,Gemma3Processor:()=>uT,Gemma3nProcessor:()=>dT,Gemma4Processor:()=>hT,Glm46VProcessor:()=>fT,GraniteSpeechProcessor:()=>_T,GroundingDinoProcessor:()=>mT,Idefics3Processor:()=>j_,JinaCLIPProcessor:()=>bT,Lfm2VlProcessor:()=>MT,LlavaProcessor:()=>xT,MgpstrProcessor:()=>kT,MoonshineProcessor:()=>TT,OwlViTProcessor:()=>ET,PaliGemmaProcessor:()=>CT,Phi3VProcessor:()=>PT,PixtralProcessor:()=>FT,Processor:()=>Ee,PyAnnoteProcessor:()=>LT,Qwen2VLProcessor:()=>Hi,Qwen2_5_VLProcessor:()=>H_,Qwen3VLProcessor:()=>IT,Sam2Processor:()=>X_,Sam2VideoProcessor:()=>OT,SamProcessor:()=>Q_,SmolVLMProcessor:()=>j_,SpeechT5Processor:()=>NT,UltravoxProcessor:()=>DT,VLChatProcessor:()=>yT,VoxtralProcessor:()=>GT,VoxtralRealtimeProcessor:()=>UT,Wav2Vec2Processor:()=>jT,Wav2Vec2ProcessorWithLM:()=>qT,WhisperProcessor:()=>WT});var ut=class extends vt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await er(e,Ni,!0,t);return new this(r)}};function at(e,t){var r;if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${((r=e==null?void 0:e.constructor)==null?void 0:r.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 zi={};os(zi,{ASTFeatureExtractor:()=>W1,ChatterboxFeatureExtractor:()=>H1,ClapFeatureExtractor:()=>Q1,CohereAsrFeatureExtractor:()=>Y1,DacFeatureExtractor:()=>p_,EncodecFeatureExtractor:()=>f_,FeatureExtractor:()=>ut,Gemma3nAudioFeatureExtractor:()=>m_,Gemma4AudioFeatureExtractor:()=>g_,GraniteSpeechFeatureExtractor:()=>J1,MoonshineFeatureExtractor:()=>K1,ParakeetFeatureExtractor:()=>__,PyAnnoteFeatureExtractor:()=>w_,SeamlessM4TFeatureExtractor:()=>Z1,SnacFeatureExtractor:()=>ek,SpeechT5FeatureExtractor:()=>tk,VoxtralRealtimeFeatureExtractor:()=>nk,Wav2Vec2FeatureExtractor:()=>rk,WeSpeakerFeatureExtractor:()=>sk,WhisperFeatureExtractor:()=>ak});var L1=()=>{},I1=L1;async function l_(e,t){if(fe.IS_BROWSER_ENV){if(fe.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(fe.IS_FS_AVAILABLE)t.stream(),Tt.createWriteStream(e),await I1();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function O1(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const r=await(await tn(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});typeof t>"u"&&ue.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);const n=await s.decodeAudioData(r);let a;if(n.numberOfChannels===2){const o=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<n.length;++c)a[c]=o*(i[c]+l[c])/2}else a=n.getChannelData(0);return a}var N1=O1;function c_(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,s=2*Math.PI/(e-1),n=new Float64Array(e);for(let a=0;a<e;++a)n[a]=t-r*Math.cos(a*s);return n}function u_(e){return c_(e,.5)}function D1(e){return c_(e,.54)}var z1={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,s=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*s:3*e/200};function Bi(e,t="htk"){const r=z1[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}var B1={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?t*Math.exp(s*(e-r)):200*e/3};function R1(e,t="htk"){const r=B1[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}function G1(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),s=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const n=t.length-2,a=Array.from({length:n},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=s[o];for(let l=0;l<n;++l){const c=-i[l]/r[l],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,d))}}return a}function d_(e,t,r){const s=(t-e)/(r-1);return Float64Array.from({length:r},(n,a)=>e+s*a)}function rr(e,t,r,s,n,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);const l=Bi(r,o),c=Bi(s,o),d=d_(l,c,t+2);let h=R1(d,o),_;if(i){const w=n/((e-1)*2);_=Bi(Float64Array.from({length:e},(v,y)=>y*w),o),h=d}else _=d_(0,Math.floor(n/2),e);const p=G1(_,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){const v=p[w],y=2/(h[w+2]-h[w]);for(let M=0;M<e;++M)v[M]*=y}return p}function $1(e,t,r){const s=new e.constructor(e.length+t+r),n=e.length-1;for(let a=0;a<e.length;++a)s[t+a]=e[a];for(let a=1;a<=t;++a)s[t-a]=e[ra(a,n)];for(let a=1;a<=r;++a)s[n+t+a]=e[ra(n-a,n)];return s}function h_(e,t,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);const a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(s,e[o])-a);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");const o=je(e)[0]-n;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function V1(e,t=1,r=1e-5,s=null){return h_(e,20,t,r,s)}function U1(e,t=1,r=1e-10,s=null){return h_(e,10,t,r,s)}async function sr(e,t,r,s,{fft_length:n=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:h=null,mel_floor:_=1e-10,log_mel:p=null,max_log_mel:w=null,reference:v=1,min_value:y=1e-10,db_range:M=null,remove_dc_offset:T=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:C=!0,transpose:I=!1,mel_offset:x=0,mel_floor_mode:R="clamp"}={}){const z=t.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(z!==r)throw new Error(`Length of the window (${z}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(a===null&&h!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){const X=Math.floor(r/2);switch(i){case"reflect":{e=$1(e,X,X);break}case"constant":{const J=new e.constructor(e.length+2*X);J.set(e,X),e=J;break}case"semicausal":{const J=new e.constructor(e.length+X);J.set(e,X),e=J;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let $=Math.floor(1+Math.floor((e.length-r)/s));A!==null&&$<A&&($=A);const Q=l?Math.floor(n/2)+1:n;let H=$,D=$;S!==null&&(S>$?C&&(D=S):D=H=S);const O=new dx(n),te=new Float64Array(n),W=new Float64Array(O.outputBufferSize),ee=new Float32Array(Q*D);for(let X=0;X<H;++X){const J=X*s,we=Math.min(e.length-J,r);we!==r&&te.fill(0,0,r);for(let re=0;re<we;++re)te[re]=e[J+re];if(T){let re=0;for(let qe=0;qe<we;++qe)re+=te[qe];const Fe=re/we;for(let qe=0;qe<we;++qe)te[qe]-=Fe}if(c!==null){for(let re=we-1;re>=1;--re)te[re]-=c*te[re-1];te[0]*=1-c}for(let re=0;re<t.length;++re)te[re]*=t[re];O.realTransform(W,te);for(let re=0;re<Q;++re){const Fe=re<<1;ee[re*D+X]=W[Fe]**2+W[Fe+1]**2}}if(a!==null&&a!==2){const X=a/2;for(let J=0;J<ee.length;++J)ee[J]**=X}const G=h.length;let L=await Cx(new U("float32",h.flat(),[G,Q]),new U("float32",ee,[Q,D]));I&&(L=L.transpose(1,0));const V=L.data;if(R==="add")for(let X=0;X<V.length;++X)V[X]=x+V[X]+_;else for(let X=0;X<V.length;++X)V[X]=x+Math.max(_,V[X]);if(a!==null&&p!==null){const X=Math.min(V.length,H*G);switch(p){case"log":for(let J=0;J<X;++J)V[J]=Math.log(V[J]);break;case"log10":for(let J=0;J<X;++J)V[J]=Math.log10(V[J]);break;case"log10_max_norm":{for(let re=0;re<X;++re)V[re]=Math.log10(V[re]);const we=(w??je(V)[0])-8;for(let re=0;re<X;++re)V[re]=(Math.max(V[re],we)+4)/4;break}case"dB":if(a===1)V1(V,v,y,M);else if(a===2)U1(V,v,y,M);else throw new Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return L}function hr(e,t,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){const a=r?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=u_(a);break;case"hamming":o=D1(a);break;case"povey":o=u_(a).map(c=>Math.pow(c,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),s===null||e===s)return o;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);const i=new Float64Array(s),l=n?Math.floor((s-e)/2):0;return i.set(o,l),i}function j1(e,t){const r=e.reduce((a,o)=>a+o.length,0),s=new ArrayBuffer(44),n=new DataView(s);return ma(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),ma(n,8,"WAVE"),ma(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,t*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),ma(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...e.map(a=>a.buffer)],{type:"audio/wav"})}function ma(e,t,r){for(let s=0;s<r.length;++s)e.setUint8(t+s,r.charCodeAt(s))}var q1=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];const e=this.audio.reduce((s,n)=>s+n.length,0),t=new Float32Array(e);let r=0;for(const s of this.audio)t.set(s,r),r+=s.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),j1(e,this.sampling_rate)}async save(e){return l_(e,this.toBlob())}},W1=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){at(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,s=t.data;for(let n=0;n<s.length;++n)s[n]=(s[n]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},f_=class extends ut{async _call(e){at(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const r=[1,t,e.length/t];return{input_values:new U("float32",e,r)}}},H1=class extends ut{async _call(e){at(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new U("float32",e,t)}}},Q1=class extends ut{constructor(e){super(e),this.mel_filters=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=hr(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,s){let n;const a=e.length-t;if(a>0)if(r==="rand_trunc"){const o=Math.floor(yi.random()*(a+1));e=e.subarray(o,o+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let o=new Float64Array(t);if(o.set(e),s==="repeat")for(let i=e.length;i<t;i+=e.length)o.set(e.subarray(0,Math.min(e.length,t-i)),i);else if(s==="repeatpad")for(let i=e.length;i<-a;i+=e.length)o.set(e,i);e=o}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return sr(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return at(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},X1=1e-5,__=class extends ut{constructor(e){var s;super(e),(s=this.config).mel_filters??(s.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));const t=hr(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await sr(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){at(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),s=t.data;s.fill(0,r*t.dims[1]);const[n,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d<r;++d){const h=d*a;for(let _=0;_<a;++_){const p=s[h+_];o[_]+=p,i[_]+=p*p}}const l=r>1?r-1:1;for(let d=0;d<a;++d){const h=o[d]/r,_=(i[d]-r*h*h)/l,w=1/(Math.sqrt(_)+X1);for(let v=0;v<r;++v){const y=v*a+d;s[y]=(s[y]-h)*w}}const c=new BigInt64Array(n);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new U("int64",c,[1,n])}}},Y1=class extends __{_apply_dither(e){const t=this.config.dither??0;if(t<=0)return e;const r=new ca(e.length);for(let s=0;s<e.length;++s)e[s]+=t*r.gauss();return e}split_audio(e){const t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,s=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,a=Math.max(1,Math.round(t*n)),o=Math.max(1,Math.round(r*n));if(e.length<=a)return[e];const i=[];let l=0;const c=e.length;for(;l<c;){if(l+a>=c){i.push(e.slice(l,c));break}const d=Math.max(l,l+a-o),h=Math.min(l+a,c);let _;h<=d?_=l+a:_=this._find_split_point_energy(e,d,h,s),_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_}return i}_find_split_point_energy(e,t,r,s){const n=r-t;if(n<=s)return Math.floor((t+r)/2);let a=1/0,o=t;const i=n-s;for(let l=0;l<=i;l+=s){let c=0;for(let d=0;d<s;++d){const h=e[t+l+d];c+=h*h}c=Math.sqrt(c/s),c<a&&(a=c,o=t+l)}return o}async _call(e){at(e,"CohereAsrFeatureExtractor");const t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},p_=class extends f_{},m_=class extends ut{constructor(e){super(e);const{fft_length:t,feature_size:r,min_frequency:s,max_frequency:n,sampling_rate:a,frame_length:o}=this.config,i=rr(Math.floor(1+t/2),r,s,n,a,null,"htk",!1);this.mel_filters=i,this.window=hr(o,"hann")}async _extract_fbank_features(e,t){return sr(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:t=48e4,truncation:r=!0,padding:s=!0,pad_to_multiple_of:n=128}={}){if(at(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),s&&e.length%n!==0){const i=n-e.length%n,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=ct([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},g_=class extends m_{async _extract_fbank_features(e,t){const{frame_length:r,hop_length:s,fft_length:n}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/s)+1;return sr(e,this.window,r,s,{fft_length:n,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:o})}async _call(e,t={}){at(e,"Gemma4AudioFeatureExtractor");const r=e.length,s=await super._call(e,t),{input_features:n}=s,[,a,o]=n.dims,{frame_length:i,hop_length:l}=this.config,c=Math.floor(i/2),d=i+1,h=new Uint8Array(r+c+(t.pad_to_multiple_of??128));h.fill(1,c,c+r);const _=new Uint8Array(a);for(let w=0;w<a;++w)_[w]=h[w*l+d-1]?1:0;const p=n.data;for(let w=0;w<a;++w)_[w]||p.fill(0,w*o,(w+1)*o);return s.input_features_mask=new U("bool",_,[1,a]),s}},J1=class extends ut{constructor(e){super(e);const{n_fft:t,win_length:r,n_mels:s,sample_rate:n}=e.melspec_kwargs;this.mel_filters=rr(Math.floor(1+t/2),s,0,n/2,n,null,"htk");const a=hr(r,"hann");this.window=new Float64Array(t);const o=Math.floor((t-r)/2);this.window.set(a,o)}async _call(e){at(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:r,n_mels:s}=this.config.melspec_kwargs,n=1+Math.floor((e.length-1)/r),a=n-n%2;return{input_features:(await sr(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*s).unsqueeze_(0)}}},K1=class extends ut{async _call(e){at(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new U("float32",e,t)}}},w_=class extends ut{async _call(e){at(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new U("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const r=t/this.samples_to_frames(t)/this.config.sampling_rate,s=[];for(const n of e.tolist()){const a=[];let o=-1;for(let i=0;i<n.length;++i){const l=nt(n[i]),[c,d]=je(l),[h,_]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,end:_,score:c})):(a.at(-1).end=_,a.at(-1).score+=c)}s.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return s}},Z1=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:s=!0,return_attention_mask:n=!0}={}){at(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(s){const[p,w]=a.dims,v=a.data;for(let y=0;y<w;++y){let M=0;for(let C=0;C<p;++C)M+=v[C*w+y];const T=M/p;let A=0;for(let C=0;C<p;++C)A+=(v[C*w+y]-T)**2;A/=p-1;const S=Math.sqrt(A+1e-7);for(let C=0;C<p;++C){const I=C*w+y;v[I]=(v[I]-T)/S}}}let o;if(t){const[p,w]=a.dims,v=a.data,y=p%r;if(y>0){const M=new Float32Array(w*(p+y));M.set(v),M.fill(this.config.padding_value,v.length);const T=p+y;a=new U(a.type,M,[T,w]),n&&(o=new U("int64",new BigInt64Array(T),[1,T]),o.data.fill(1n,0,p))}}const[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const h=a.view(1,Math.floor(i/c),l*c),_={input_features:h};if(n){const p=h.dims[1],w=new BigInt64Array(p);if(o){const v=o.data;for(let y=1,M=0;y<i;y+=c,++M)w[M]=v[y]}else w.fill(1n);_.attention_mask=new U("int64",w,[1,p])}return _}},ek=class extends p_{},tk=class extends ut{},rk=class extends ut{_zero_mean_unit_var_norm(e){const r=e.reduce((n,a)=>n+a,0)/e.length,s=e.reduce((n,a)=>n+(a-r)**2,0)/e.length;return e.map(n=>(n-r)/Math.sqrt(s+1e-7))}async _call(e){at(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new U("float32",t,r),attention_mask:new U("int64",new BigInt64Array(t.length).fill(1n),r)}}},sk=class extends ut{constructor(e){super(e);const t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=hr(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),sr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){at(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,s=t.data,[n,a,o]=t.dims;for(let i=0;i<n;++i){const l=i*a*o,c=i*o;for(let d=0;d<a;++d){const h=l+d*o;for(let _=0;_<o;++_)s[h+_]-=r[c+_]}}}return{input_features:t}}},nk=class extends ut{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=hr(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){const{n_fft:r,hop_length:s,mel_filters:n,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/s:(e.length-r)/s);return await sr(e,this.window,r,s,{power:2,mel_filters:n,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:!1})}async _call(e,{center:t=!0}={}){return at(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},ak=class extends ut{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=hr(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await sr(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){at(e,"WhisperFeatureExtractor");let r;const s=t??this.config.n_samples;return e.length>s?(e.length>this.config.n_samples&&ue.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,s)):(r=new Float32Array(s),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Lt=class{static async from_pretrained(e,t={}){const r=await er(e,Ni,!0,t),s=r.feature_extractor_type,n=zi[s];if(!n)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${pa}.`);return new n(r)}},ok=(Wa=class extends Ee{async _call(e,t=null){const r=this.tokenizer(e),s=t?await this.feature_extractor(t):{};return{...r,...s}}},k(Wa,"tokenizer_class",Te),k(Wa,"feature_extractor_class",Lt),Wa),ik=new Set(["ja","zh"]),lk=(Mn=class extends Ee{get_decoder_prompt_ids(e="en"){const t=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){const r=e.filter(a=>a&&a.trim());if(r.length===0)return"";const s=ik.has(t)?"":" ";return[r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(s)}async _call(e){return await this.feature_extractor(e)}},k(Mn,"tokenizer_class",Te),k(Mn,"feature_extractor_class",Lt),k(Mn,"uses_processor_config",!0),Mn),Ri={},Yr,v_,Ir;if(fe.IS_WEB_ENV)Yr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Ir=self.createImageBitmap,v_=self.ImageData;else if(Ri)Ir=async e=>{const r=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new qt(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var ck={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},uk=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),qt=class lr{constructor(t,r,s,n){this.data=t,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof lr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!fe.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const s=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new lr(s,t.width,t.height,4)}static async fromURL(t){const r=await tn(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const s=await r.blob();return this.fromBlob(s)}static async fromBlob(t){if(fe.IS_WEB_ENV){const r=await Ir(t),s=Yr(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=Ri(await t.arrayBuffer());return await Ir(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new lr(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){const n=this.data[r],a=this.data[r+1],o=this.data[r+2];t[s++]=Math.round(.2989*n+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2],t[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);const r=this.data,s=t.data,n=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(n*4);for(let o=0,i=0,l=0;o<n;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=s[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<n;++a)r[4*a+3]=s[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:s=2}={}){if(this.width===t&&this.height===r)return this;let n=ck[s]??s;const a=Hh(t),o=Hh(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),fe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Yr(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new lr(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(ue.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Ir(i)}}async pad([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),t===0&&r===0&&s===0&&n===0)return this;if(fe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+s+n,c=Yr(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,s,this.width,this.height),new lr(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:r,top:s,bottom:n});return await Ir(a)}}async crop([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),t===0&&r===0&&s===this.width-1&&n===this.height-1)return this;const a=s-t+1,o=n-r+1;if(fe.IS_WEB_ENV){const i=this.channels,l=this.toCanvas(),c=Yr(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new lr(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{const i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await Ir(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;const s=(this.width-t)/2,n=(this.height-r)/2;if(fe.IS_WEB_ENV){const a=this.channels,o=this.toCanvas(),i=Yr(t,r).getContext("2d");let l=0,c=0,d=0,h=0;return s>=0?l=s:d=-s,n>=0?c=n:h=-n,i.drawImage(o,l,c,t,r,d,h,t,r),new lr(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(s>=0&&n>=0)a=a.extract({left:Math.floor(s),top:Math.floor(n),width:t,height:r});else if(s<=0&&n<=0){const o=Math.floor(-n),i=Math.floor(-s);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;n<0?(o[0]=Math.floor(-n),o[1]=r-this.height-o[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=t-this.width-l[0]):c=Math.floor(s),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await Ir(a)}}async toBlob(t="image/png",r=1){if(!fe.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new U("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!fe.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Yr(t.width,t.height),s=new v_(t.data,t.width,t.height);return r.getContext("2d").putImageData(s,0,0),r}split(){const{data:t,width:r,height:s,channels:n}=this,a=t.constructor,o=t.length/n,i=Array.from({length:n},()=>new a(o));for(let l=0;l<o;++l){const c=n*l;for(let d=0;d<n;++d)i[d][l]=t[c+d]}return i.map(l=>new lr(l,r,s,1))}_update(t,r,s,n=null){return this.data=t,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new lr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(fe.IS_WEB_ENV){if(fe.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),s=uk.get(r)??"image/png",n=await this.toBlob(s);return l_(t,n)}else if(fe.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(fe.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Ri(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};qt.read.bind(qt);function y_(e,t,r=0,s=null){const n=e/t;let a=fx(n)*t;return s!==null&&a>s&&(a=Math.floor(n)*t),a<r&&(a=Math.ceil(n)*t),a}function b_([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function M_([e,t,r,s]){return[e-r/2,t-s/2,e+r/2,t+s/2]}function ga(e,t=.5,r=null,s=!1){const n=e.logits,a=e.pred_boxes,[o,i,l]=n.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let d=0;d<o;++d){let h=r!==null?r[d]:null,_={boxes:[],classes:[],scores:[]},p=n[d],w=a[d];for(let v=0;v<i;++v){let y=p[v],M=[],T;if(s){T=y.sigmoid().data;for(let A=0;A<T.length;++A)T[A]>t&&M.push(A)}else{let A=je(y.data)[1];if(A===l-1||(T=nt(y.data),T[A]<t))continue;M.push(A)}for(const A of M){let S=w[v].data;S=M_(S),h!==null&&(S=S.map((C,I)=>C*h[(I+1)%2])),_.boxes.push(S),_.classes.push(A),_.scores.push(T[A])}}c.push(_)}return c}function x_(e,t=null){const r=e.logits,s=r.dims[0];if(t!==null&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const n=[];for(let a=0;a<s;++a){const o=t!==null?t[a]:null;let i=r[a];o!==null&&(i=Hf(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new U("int32",new Int32Array(l*c),[l,c]),h=i[0].data,_=d.data;for(let v=1;v<i.dims[0];++v){const y=i[v].data;for(let M=0;M<y.length;++M)y[M]>h[M]&&(h[M]=y[M],_[M]=v)}const p=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const y=_[v];p[y]=y}const w=p.filter(v=>v!==void 0);n.push({segmentation:d,labels:w})}return n}function dk(e,t,r,s){const n=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=je(l.data)[1];if(d===s)continue;const _=nt(l.data)[d];_>r&&(n.push(c),a.push(_),o.push(d))}return[n,a,o]}function hk(e,t,r,s=.5,n=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let d=0;d<e.length;++d)e[d]===r&&(a.push(d),++o),l[d]>=s&&++i;let c=o>0&&i>0;return c&&(c=o/i>n),[c,a]}function fk(e,t,r,s,n,a=null,o=null){const[i,l]=o??e[0].dims,c=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=Hf(e[v],o,"bilinear",!1);const h=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let y=t[v];const M=e[v].data;for(let T=0;T<M.length;++T)M[T]*=y,M[T]>_[T]&&(h[T]=v,_[T]=M[T])}let p=0;const w=c.data;for(let v=0;v<r.length;++v){const y=r[v],[M,T]=hk(h,e,v,s,n);if(M){++p;for(const A of T)w[A]=p;d.push({id:p,label_id:y,score:t[v]})}}return[c,d]}function Gi(e,t,r=28,s=3136,n=784*1280,a=1){if(e<r||t<r){const l=Math.max(r/e,r/t);e=Math.round(e*l),t=Math.round(t*l)}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>n){const l=Math.sqrt(a*e*t/n);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r)}else if(a*o*i<s){const l=Math.sqrt(s/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r}return[i,o]}function k_(e,t=.5,r=.5,s=.8,n=null,a=null){n===null&&(ue.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);const o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[c,d,h]=o.dims;if(h-=1,a!==null&&a.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let p=0;p<c;++p){let w=a!==null?a[p]:null,v=o[p],y=l[p],[M,T,A]=dk(v,y,t,h);if(A.length===0){let[I,x]=w??y.dims.slice(-2),R=new U("int32",new Int32Array(I*x).fill(-1),[I,x]);_.push({segmentation:R,segments_info:[]});continue}let[S,C]=fk(M,T,A,r,s,n,w);_.push({segmentation:S,segments_info:C})}return _}function T_(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var de=class extends vt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){const s=e.height,n=e.width,a=t.height,o=t.width;let i=Math.min(s,a),l=Math.min(n,o);return i===s&&l===n?e:(s>n?l=Math.floor(n*i/s):n>s&&(i=Math.floor(s*l/n)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),s=ki(r.data)[0],a=je(r.data)[0]-s;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,c=0,d=0;const h=r.data;for(let _=0;_<r.height;++_){const p=_*r.width;for(let w=0;w<r.width;++w)(h[p+w]-s)/a<o&&(i=Math.min(i,w),l=Math.min(l,_),c=Math.max(c,w),d=Math.max(d,_))}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:s="constant",center:n=!1,constant_values:a=0}={}){const[o,i,l]=t;let c,d;if(typeof r=="number"?(c=r,d=r):r==="square"?c=d=Math.max(o,i):(c=r.width,d=r.height),c!==i||d!==o){const h=new Float32Array(c*d*l);if(Array.isArray(a))for(let w=0;w<h.length;++w)h[w]=a[w%l];else a!==0&&h.fill(a);const[_,p]=n?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+p)*c,y=w*i;for(let M=0;M<i;++M){const T=(v+M+_)*l,A=(y+M)*l;for(let S=0;S<l;++S)h[T+S]=e[A+S]}}if(s==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const w=o-1,v=i-1;for(let y=0;y<d;++y){const M=y*c,T=ra(y,w)*i;for(let A=0;A<c;++A){if(y<o&&A<i)continue;const S=(M+A)*l,C=(T+ra(A,v))*l;for(let I=0;I<l;++I)h[S+I]=e[C+I]}}}e=h,t=[d,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[r,s]=e.size;let n,a;if(this.do_thumbnail){const{height:o,width:i}=t;n=Math.min(o,i)}else Number.isInteger(t)?(n=t,a=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,a=t.longest_edge);if(n!==void 0||a!==void 0){const o=n===void 0?1:Math.max(n/r,n/s),i=r*o,l=s*o,c=a===void 0?1:Math.min(a/i,a/l);let d=Math.floor(Number((i*c).toFixed(2))),h=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=b_([d,h],this.size_divisibility)),[d,h]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/s,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=y_(l*s,this.config.ensure_multiple_of),o=y_(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return b_([r,s],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:s=null,do_convert_grayscale:n=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(s??this.do_convert_rgb?e=e.rgb():n&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,p;Number.isInteger(this.crop_size)?(_=this.crop_size,p=this.crop_size):(_=this.crop_size.width,p=this.crop_size.height),e=await e.center_crop(_,p)}const l=[e.height,e.width];let c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let p=this.image_std;if(Array.isArray(this.image_std)||(p=new Array(e.channels).fill(p)),_.length!==e.channels||p.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${p.length}) must match the number of channels in the image (${e.channels}).`);for(let w=0;w<c.length;w+=e.channels)for(let v=0;v<e.channels;++v)c[w+v]=(c[w+v]-_[v])/p[v]}if(r??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,p=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:_,height:p})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){const p=c[_];c[_]=c[_+2],c[_+2]=p}}const h=new U("float32",c,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:h}}async _call(e,...t){Array.isArray(e)||(e=[e]);const r=await Promise.all(e.map(n=>this.preprocess(n)));return{pixel_values:dr(r.map(n=>n.pixel_values),0),original_sizes:r.map(n=>n.original_size),reshaped_input_sizes:r.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await er(e,an,!0,t);return new this(r)}},wa={};os(wa,{BeitFeatureExtractor:()=>_k,BitImageProcessor:()=>pk,CHMv2ImageProcessor:()=>gk,CLIPFeatureExtractor:()=>wk,CLIPImageProcessor:()=>E_,ChineseCLIPFeatureExtractor:()=>mk,ConvNextFeatureExtractor:()=>vk,ConvNextImageProcessor:()=>A_,DINOv3ViTImageProcessor:()=>Mk,DPTFeatureExtractor:()=>kk,DPTImageProcessor:()=>P_,DeiTFeatureExtractor:()=>yk,DeiTImageProcessor:()=>C_,DetrFeatureExtractor:()=>bk,DetrImageProcessor:()=>S_,DonutFeatureExtractor:()=>xk,DonutImageProcessor:()=>$i,EfficientNetImageProcessor:()=>Tk,GLPNFeatureExtractor:()=>Pk,Gemma3ImageProcessor:()=>Ek,Gemma4ImageProcessor:()=>F_,Glm46VImageProcessor:()=>Sk,GroundingDinoImageProcessor:()=>Fk,Idefics3ImageProcessor:()=>I_,ImageFeatureExtractor:()=>de,ImageProcessor:()=>de,JinaCLIPImageProcessor:()=>Ik,Lfm2VlImageProcessor:()=>Bk,LlavaOnevisionImageProcessor:()=>Rk,Mask2FormerImageProcessor:()=>$k,MaskFormerFeatureExtractor:()=>Gk,MaskFormerImageProcessor:()=>Vi,MobileNetV1FeatureExtractor:()=>Vk,MobileNetV1ImageProcessor:()=>N_,MobileNetV2FeatureExtractor:()=>Uk,MobileNetV2ImageProcessor:()=>D_,MobileNetV3FeatureExtractor:()=>jk,MobileNetV3ImageProcessor:()=>z_,MobileNetV4FeatureExtractor:()=>qk,MobileNetV4ImageProcessor:()=>B_,MobileViTFeatureExtractor:()=>Wk,MobileViTImageProcessor:()=>R_,NougatImageProcessor:()=>Hk,OwlViTFeatureExtractor:()=>Qk,OwlViTImageProcessor:()=>Ui,Owlv2ImageProcessor:()=>Xk,Phi3VImageProcessor:()=>Jk,PixtralImageProcessor:()=>Kk,PvtImageProcessor:()=>Zk,Qwen2VLImageProcessor:()=>L_,RTDetrImageProcessor:()=>eT,Sam2ImageProcessor:()=>Wi,Sam3ImageProcessor:()=>Wi,SamImageProcessor:()=>Wi,SapiensFeatureExtractor:()=>tT,SapiensImageProcessor:()=>G_,SegformerFeatureExtractor:()=>rT,SegformerImageProcessor:()=>$_,SiglipImageProcessor:()=>sT,SmolVLMImageProcessor:()=>I_,Swin2SRImageProcessor:()=>nT,VLMImageProcessor:()=>Lk,ViTFeatureExtractor:()=>aT,ViTImageProcessor:()=>V_,VitMatteImageProcessor:()=>oT,VitPoseImageProcessor:()=>iT,YolosFeatureExtractor:()=>lT,YolosImageProcessor:()=>U_});var _k=class extends de{},pk=class extends de{},mk=class extends de{},gk=class extends de{},E_=class extends de{},wk=class extends E_{},A_=class extends de{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var r;const t=(r=this.size)==null?void 0:r.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const s=Math.floor(t/this.crop_pct),[n,a]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},vk=class extends A_{},C_=class extends de{},yk=class extends C_{},S_=class extends de{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],s=ct(r,1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return ga(...e)}post_process_panoptic_segmentation(...e){return k_(...e)}post_process_instance_segmentation(...e){return T_(...e)}},bk=class extends S_{},Mk=class extends de{},$i=class extends de{pad_image(e,t,r,s={}){const[n,a,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const c=i.map((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...s})}},xk=class extends $i{},P_=class extends de{},kk=class extends P_{},Tk=class extends de{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},Ek=class extends de{};function Ak(e,t,r,s,n){const a=s*r**2,o=Math.sqrt(a/(e*t)),i=n*r;let l=Math.floor(o*e/i)*i,c=Math.floor(o*t/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);const d=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(t/e)*i,d)):c===0&&(c=i,l=Math.min(Math.floor(e/t)*i,d)),[l,c]}function Ck(e,t,r,s,n,a,o){const i=Math.floor(t/n),l=Math.floor(r/n),c=i*l,d=n*n*s,h=new Float32Array(a*d);let _=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)for(let M=0;M<n;++M){const T=(v*n+M)*r*s+y*n*s;for(let A=0;A<n;++A){const S=T+A*s;for(let C=0;C<s;++C)h[_++]=e[S+C]}}const p=new BigInt64Array(a*2).fill(-1n);let w=0;for(let v=0;v<i;++v)for(let y=0;y<l;++y)p[w++]=BigInt(y),p[w++]=BigInt(v);return{patches:new U("float32",h,[a,d]),positions:new U("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var F_=class extends vt{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);const{patch_size:t,pooling_kernel_size:r}=this,s=this.max_soft_tokens*r**2,n=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){const[_,p]=Ak(i.height,i.width,t,s,r);(_!==i.height||p!==i.width)&&(i=await i.resize(p,_,{resample:this.resample}))}const l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;const{patches:c,positions:d,num_soft_tokens:h}=Ck(l,i.height,i.width,i.channels,t,s,r);n.push(c),a.push(d),o.push(h)}return{pixel_values:dr(n,0),image_position_ids:dr(a,0),num_soft_tokens_per_image:o}}},L_=class extends de{constructor(e){var t,r;super(e),this.min_pixels=e.min_pixels??((t=e.size)==null?void 0:t.shortest_edge),this.max_pixels=e.max_pixels??((r=e.size)==null?void 0:r.longest_edge),this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size;return Gi(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:s,reshaped_input_sizes:n}=await super._call(e,...t);let a=r;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=ze(Array.from({length:o},()=>a),0));const c=a.dims[0]/o,d=a.dims[1],h=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),p=a.view(c,o,d,Math.floor(h/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*h*_,d*o*l*l),w=new U("int64",[c,h,_],[1,3]);return{pixel_values:p,image_grid_thw:w,original_sizes:s,reshaped_input_sizes:n}}},Sk=class extends L_{get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size,s=this.config.temporal_patch_size??2;return Gi(e.height,e.width,r,this.min_pixels,this.max_pixels,s)}},Pk=class extends de{},Fk=class extends de{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,s=yt([r[0],r[2],r[3]]);return{...t,pixel_mask:s}}},I_=class extends de{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,s]=e.dims.slice(-2);const n=s/r;return s>=r?(s=Math.ceil(s/t)*t,r=Math.floor(s/n),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,s=Math.floor(r*n),s=Math.ceil(s/t)*t),{height:r,width:s}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let s;if(!Array.isArray(e))s=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?s=e:s=[e]}let n=[],a=[],o=[];const i=[],l=[];for(const y of s){let M=await Promise.all(y.map(S=>this.preprocess(S)));i.push(...M.map(S=>S.original_size)),l.push(...M.map(S=>S.reshaped_input_size)),M.forEach(S=>S.pixel_values.unsqueeze_(0));const{longest_edge:T}=this.max_image_size;let A;if(t??this.do_image_splitting){let S=new Array(M.length),C=new Array(M.length);A=await Promise.all(M.map(async(I,x)=>{const R=this.get_resize_for_vision_encoder(I.pixel_values,T),z=await jt(I.pixel_values,{size:[R.height,R.width]}),{frames:$,num_splits_h:Q,num_splits_w:H}=await this.split_image(z,this.max_image_size);return S[x]=Q,C[x]=H,ze($,0)})),a.push(S),o.push(C)}else{const S=[T,T];A=await Promise.all(M.map(C=>jt(C.pixel_values,{size:S}))),a.push(new Array(M.length).fill(0)),o.push(new Array(M.length).fill(0))}n.push(ze(A,0))}const c=n.length,[d,h,_,p]=n[0].dims;let w,v;if(c===1)w=n[0].unsqueeze_(0),v=ct([c,d,_,p],!0);else{const y=Math.max(...n.map(A=>A.dims.at(0)));v=ct([c,y,_,p],!0);const M=v.data,T=y*_*p;for(let A=0;A<c;++A){const S=n[A].dims[0];if(S<y){n[A]=ze([n[A],ct([y-S,h,_,p],0)],0);const C=A*T+S*_*p,I=(A+1)*T;M.fill(!1,C,I)}}w=dr(n,0)}return{pixel_values:w,pixel_attention_mask:v,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){const r=t,s=t,n=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>r||o>s){i=Math.ceil(a/r),l=Math.ceil(o/s);const c=Math.ceil(a/i),d=Math.ceil(o/l);for(let p=0;p<i;++p)for(let w=0;w<l;++w){let v,y,M,T;p===i-1?(y=a-c,T=a):(y=p*c,T=(p+1)*c),w===l-1?(v=o-d,M=o):(v=w*d,M=(w+1)*d);const C=await Qf(e,[y,v],[T,M],[2,3]);n.push(C)}const h=r,_=s;(a!==h||o!==_)&&(e=await jt(e,{size:[h,_]}))}return n.push(e),{frames:n,num_splits_h:i,num_splits_w:l}}},Lk=class extends de{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor)}pad_image(e,t,r,s){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...s})}},Ik=class extends de{constructor(e){const{resize_mode:t,fill_color:r,interpolation:s,size:n,...a}=e,o=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},i=s==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:n,do_normalize:!0})}};function O_(e,t){return Math.round(e/t)*t}function Ok(e,t,r,s,n){let a=1/0,o=[1,1];const i=r*s;for(const l of t){const c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*n*n*l[0]*l[1]&&(o=l)}return o}function Nk(e,t){const r=[],s=new Set;for(let n=e;n<=t;++n)for(let a=1;a<=n;++a)for(let o=1;o<=n;++o){const i=a*o;if(i>=e&&i<=t){const l=a<<16|o;s.has(l)||(s.add(l),r.push([a,o]))}}return r.sort((n,a)=>n[0]*n[1]-a[0]*a[1])}function Dk(e,t){const[r,s,n,a]=e.dims,o=Math.floor(n/t),i=Math.floor(a/t),l=t*t*s,c=e.data,d=new Float32Array(r*o*i*l),h=n*a;for(let _=0;_<r;++_){const p=_*s*h,w=_*o*i*l;for(let v=0;v<o;++v)for(let y=0;y<i;++y){let M=w+(v*i+y)*l;for(let T=0;T<t;++T){const A=(v*t+T)*a+y*t;for(let S=0;S<t;++S){const C=A+S;for(let I=0;I<s;++I)d[M++]=c[p+I*h+C]}}}}return new U("float32",d,[r,o*i,l])}function zk(e,t){const[,r,s]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,r);let a=e;if(r<t){const o=new Float32Array(t*s);o.set(e.data),a=new U("float32",o,[1,t,s])}return{padded:a,mask:new U("int64",n,[t])}}var Bk=class extends de{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;const t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r)}_is_image_too_large(e,t){const r=this.encoder_patch_size*this.downsample_factor,s=Math.max(this.encoder_patch_size,O_(e,r)),n=Math.max(this.encoder_patch_size,O_(t,r));return s*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=Nk(this.min_tiles,this.max_tiles),[s,n]=Ok(t/e,r,t,e,this.tile_size);return{grid_width:s,grid_height:n,target_width:this.tile_size*s,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];const s=[],n=[],a=[],o=[],i=[],l=[];for(const d of r){const h=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(const{pixel_values:_}of h){const[,p,w]=_.dims,v=_.unsqueeze_(0),y=this.encoder_patch_size*this.downsample_factor,M=y**2,[T,A]=Gi(Math.max(y,p),Math.max(y,w),y,this.min_image_tokens*M,this.max_image_tokens*M).map(z=>Math.max(y,z));let S,C=1,I=1;const x=this._is_image_too_large(p,w),R=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(x&&R){const{grid_width:z,grid_height:$,target_width:Q,target_height:H}=this._get_grid_layout(p,w);C=$,I=z;const D=await jt(v,{size:[H,Q]});S=[];for(let O=0;O<$;++O)for(let te=0;te<z;++te){const W=O*this.tile_size,ee=te*this.tile_size;S.push(D.slice(null,null,[W,W+this.tile_size],[ee,ee+this.tile_size]))}this.use_thumbnail&&z*$!==1&&S.push(await jt(v,{size:[A,T]}))}else S=[await jt(v,{size:[A,T]})];for(const z of S){const[,,$,Q]=z.dims,H=Dk(z,this.encoder_patch_size),{padded:D,mask:O}=zk(H,this.max_num_patches);s.push(D),n.push(O),a.push([Math.floor($/this.encoder_patch_size),Math.floor(Q/this.encoder_patch_size)])}o.push(C),i.push(I),l.push([A,T])}}const c={pixel_values:ze(s,0),pixel_attention_mask:dr(n,0),spatial_shapes:new U("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(c.image_rows=o,c.image_cols=i,c.image_sizes=l),c}},Rk=class extends de{},Vi=class extends de{post_process_panoptic_segmentation(...e){return k_(...e)}post_process_instance_segmentation(...e){return T_(...e)}},Gk=class extends Vi{},$k=class extends Vi{},N_=class extends de{},Vk=class extends N_{},D_=class extends de{},Uk=class extends D_{},z_=class extends de{},jk=class extends z_{},B_=class extends de{},qk=class extends B_{},R_=class extends de{},Wk=class extends R_{},Hk=class extends $i{},Ui=class extends de{post_process_object_detection(...e){return ga(...e)}},Qk=class extends Ui{},Xk=class extends Ui{},At=336,Yk=[2,3],{ceil:ji,floor:_s,sqrt:qi}=Math,Jk=class extends de{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,t){const{num_img_tokens:r}=this.config;return _s((_s(t/At)*_s(e/At)+1)*r+1+(_s(t/At)+1)*qi(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[s,n]=e.size;let a=s/n,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;const i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,s={}){const[n,a]=t,o=At*ji(n/At),i=At*ji(a/At),l=[1,1,1].map((c,d)=>(c-this.image_mean[d])/this.image_std[d]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...s})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??(t=this.config.num_crops),t<4||qi(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,s=await Promise.all(e.map(h=>this.preprocess(h))),n=s.map(h=>h.original_size),a=s.map(h=>h.reshaped_input_size),o=[];for(const{pixel_values:h}of s){h.unsqueeze_(0);const[_,p]=h.dims.slice(-2),w=await jt(h,{size:[At,At],mode:"bicubic"});if(t>0){const v=[],y=qi(t),M=_s(p/y),T=_s(_/y);for(let S=0;S<y;++S)for(let C=0;C<y;++C){let I,x,R,z;S===y-1?(x=_-T,z=_):(x=S*T,z=(S+1)*T),C===y-1?(I=p-M,R=p):(I=C*M,R=(C+1)*M);const H=await Qf(h,[x,I],[z,R],Yk);v.push(H)}const A=await jt(ze(v,0),{size:[At,At],mode:"bicubic"});o.push(ze([w,A],0))}else o.push(w)}const i=dr(o,0),l=a.map(h=>h.map(_=>At*ji(_/At))),c=new U("int64",l.flat(),[r,2]),d=l.map(([h,_])=>this.calc_num_image_tokens_from_image_size(_,h));return{pixel_values:i,original_sizes:n,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},Kk=class extends de{get_resize_output_image_size(e,t){const{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[s,n]=e.size,a=Math.max(s,n)/r;let o=s,i=n;a>1&&(o=Math.floor(s/a),i=Math.floor(n/a));const{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");const d=l*c,h=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return[h*d,_*d]}},Zk=class extends de{},eT=class extends de{post_process_object_detection(...e){return ga(...e)}},Wi=class extends de{reshape_input_points(e,t,r,s=!1){e=structuredClone(e);let n=Qh(e);if(n.length===3)s||(n=[1,...n]),e=[e];else if(n.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){const[o,i]=t[a],[l,c]=r[a],d=[c/i,l/o];for(let h=0;h<e[a].length;++h)for(let _=0;_<e[a][h].length;++_)for(let p=0;p<e[a][h][_].length;++p)e[a][h][_][p]*=d[p%2]}return new U("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let r=Qh(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((s,n)=>s!==t.dims[n]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:s=null}={}){const n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),r){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(r,n.input_points)}return s&&(n.input_boxes=this.reshape_input_points(s,n.original_sizes,n.reshaped_input_sizes,!0)),n}async post_process_masks(e,t,r,{mask_threshold:s=0,binarize:n=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;l<t.length;++l){const c=t[l],d=r[l];let h=await jt(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await jt(h,{mode:"bilinear",size:c}),n){const _=h.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)_[w]>s&&(p[w]=1);h=new U("bool",p,h.dims)}o.push(h)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:a=1}={}){}},G_=class extends de{post_process_semantic_segmentation(...e){return x_(...e)}},tT=class extends G_{},$_=class extends de{post_process_semantic_segmentation(...e){return x_(...e)}},rT=class extends $_{},sT=class extends de{},nT=class extends de{pad_image(e,t,r,s={}){const[n,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:n+(r-n%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}},V_=class extends de{},aT=class extends V_{},oT=class extends de{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(a=>this.preprocess(a))),s=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:dr(r.map((a,o)=>ze([a.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},iT=class extends de{post_process_pose_estimation(e,t,{threshold:r=null}={}){const s=e.tolist(),[n,a,o,i]=e.dims,l=[];for(let c=0;c<n;++c){const d=s[c],h=t[c],_=[];for(let p=0;p<h.length;++p){const w=h[p],v=[],y=[],M=[],T=w.at(-2)/i,A=w.at(-1)/o;for(let S=0;S<d.length;++S){let[C,I]=[0,0],x=0,R=-1/0;const z=d[S];for(let Q=0;Q<z.length;++Q){const H=z[Q];for(let D=0;D<H.length;++D){const O=H[D];x+=O,R=Math.max(R,O),C+=(D+.5)*O,I+=Q*O}}if(r!=null&&R<r)continue;const $=[T*C/x,A*I/x];v.push($),M.push(S),y.push(R)}_.push({bbox:w,scores:y,labels:M,keypoints:v})}l.push(_)}return l}},U_=class extends de{post_process_object_detection(...e){return ga(...e)}},lT=class extends U_{},dt=class{static async from_pretrained(e,t={}){const r=await er(e,an,!0,t),s=r.image_processor_type??r.feature_extractor_type;let n=wa[s==null?void 0:s.replace(/Fast$/,"")];return n||(s!==void 0&&ue.warn(`Image processor type '${s}' not found, assuming base ImageProcessor. Please report this at ${pa}.`),n=de),new n(r)}},cT=(Ha=class extends Ee{constructor(e,t,r){super(e,t,r);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const t=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(const[s,n]of this.task_prompts_with_input)if(r.includes(s)){t.push(n.replaceAll("{input}",r).replaceAll(s,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const s=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(s){case"pure_text":n=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=s==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[c,d,...h]of o)i.push(d?d.trim():i.at(-1)??""),l.push(h.map((_,p)=>(Number(_)+.5)/this.size_per_bin*r[p%2]));n={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${s}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=await this.image_processor(e,r),n=t?this.tokenizer(this.construct_prompts(t),r):{};return{...s,...n}}},k(Ha,"tokenizer_class",Te),k(Ha,"image_processor_class",dt),Ha),uT=(Ns=class extends Ee{constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;const{boi_token:s,image_token:n,eoi_token:a}=this.tokenizer.config;this.boi_token=s,this.image_token=n,this.eoi_token=a;const o=n.repeat(this.image_seq_length);this.full_image_sequence=`
18
18
 
19
19
  ${s}${o}${a}
20
20
 
21
- `}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let s;return t&&(s=await this.image_processor(t,r),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...s}}},k(Ds,"tokenizer_class",Te),k(Ds,"image_processor_class",dt),k(Ds,"uses_processor_config",!0),k(Ds,"uses_chat_template_file",!0),Ds),cT=(Zr=class extends Ee{constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:s,boa_token:n,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=s,this.boa_token=n,this.audio_token=a;const h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
21
+ `}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let s;return t&&(s=await this.image_processor(t,r),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...s}}},k(Ns,"tokenizer_class",Te),k(Ns,"image_processor_class",dt),k(Ns,"uses_processor_config",!0),k(Ns,"uses_chat_template_file",!0),Ns),dT=(Zr=class extends Ee{constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:s,boa_token:n,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=s,this.boa_token=n,this.audio_token=a;const h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
22
22
 
23
23
  ${n}${h}${o}
24
24
 
@@ -26,7 +26,7 @@ ${n}${h}${o}
26
26
 
27
27
  ${l}${_}${d}
28
28
 
29
- `}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;r&&(n=await this.feature_extractor(r,s),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,s),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...a,...n}}},k(Zr,"image_processor_class",dt),k(Zr,"feature_extractor_class",Lt),k(Zr,"tokenizer_class",Te),k(Zr,"uses_processor_config",!0),k(Zr,"uses_chat_template_file",!0),Zr),uT=(Qa=class extends Ee{constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;const{audio_token:s,boa_token:n,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=s,this.boa_token=n,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([er(e,a_,!0,t),Te.from_pretrained(e,t),xi(e,o_,!1,t)]),a={tokenizer:s};return r.image_processor&&(a.image_processor=new P_(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new m_(r.feature_extractor)),new this(r,a,n)}_compute_audio_num_tokens(e,t){const r=Math.round(t*20/1e3),s=Math.round(t*10/1e3),n=Math.floor(r/2);let a=Math.floor((e+n-r-1)/s)+1;if(a<=0)return 0;for(let o=0;o<2;++o)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,s);const o=n.num_soft_tokens_per_image;let i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>`
29
+ `}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;r&&(n=await this.feature_extractor(r,s),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,s),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...a,...n}}},k(Zr,"image_processor_class",dt),k(Zr,"feature_extractor_class",Lt),k(Zr,"tokenizer_class",Te),k(Zr,"uses_processor_config",!0),k(Zr,"uses_chat_template_file",!0),Zr),hT=(Qa=class extends Ee{constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;const{audio_token:s,boa_token:n,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=s,this.boa_token=n,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l}static async from_pretrained(e,t={}){const[r,s,n]=await Promise.all([er(e,o_,!0,t),Te.from_pretrained(e,t),xi(e,i_,!1,t)]),a={tokenizer:s};return r.image_processor&&(a.image_processor=new F_(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new g_(r.feature_extractor)),new this(r,a,n)}_compute_audio_num_tokens(e,t){const r=Math.round(t*20/1e3),s=Math.round(t*10/1e3),n=Math.floor(r/2);let a=Math.floor((e+n-r-1)/s)+1;if(a<=0)return 0;for(let o=0;o<2;++o)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,s);const o=n.num_soft_tokens_per_image;let i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>`
30
30
 
31
31
  ${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
32
32
 
@@ -34,8 +34,8 @@ ${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
34
34
 
35
35
  ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
36
36
 
37
- `))}return{...this.tokenizer(e,s),...n,...a}}},k(Qa,"uses_processor_config",!0),k(Qa,"uses_chat_template_file",!0),Qa),Hi=(xn=class extends Ee{async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let s,n;if(t&&(s=await this.image_processor(t),n=s.image_grid_thw),n){let o=this.image_processor.config.merge_size**2,i=0;const l=this.constructor.image_token,c=n.tolist();e=e.map(d=>{for(;d.includes(l);){const h=Number(c[i++].reduce((_,p)=>_*p,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(h/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...s}}},k(xn,"image_processor_class",dt),k(xn,"tokenizer_class",Te),k(xn,"image_token","<|image_pad|>"),xn),dT=(du=class extends Hi{},k(du,"image_token","<|image|>"),du),hT=(kn=class extends Ee{_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:s}=this.feature_extractor.config,n=Math.floor(r/s),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*n}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const{input_features:a}=await this.feature_extractor(t);s.input_features=a;const o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);s.input_features_mask=new U("bool",i,[1,o]);const l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(kn,"tokenizer_class",Te),k(kn,"feature_extractor_class",Lt),k(kn,"uses_processor_config",!0),kn);function fT(e,t){const s=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,s);const a=t.tolist();return n.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var _T=(Xa=class extends Ee{async _call(e,t,r={}){const s=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...s}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:n=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(n!==null&&n.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),h=o.tolist().map(p=>p.map(w=>b_(w))),_=[];for(let p=0;p<i;++p){const w=n!==null?n[p]:null;w!==null&&(h[p]=h[p].map(A=>A.map((C,S)=>C*w[(S+1)%2])));const v=d[p],y=[],M=[],T=[];for(let A=0;A<l;++A){const C=v[A];if(C<=r)continue;const S=h[p][A],N=c[p][A];y.push(C),T.push(S);const x=fT(N.gt(s),t[p]);M.push(x)}_.push({scores:y,boxes:T,labels:this.batch_decode(M)})}return _}},k(Xa,"tokenizer_class",Te),k(Xa,"image_processor_class",dt),Xa);function pT(e,t,r,s,n,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(e);o+=`
37
+ `))}return{...this.tokenizer(e,s),...n,...a}}},k(Qa,"uses_processor_config",!0),k(Qa,"uses_chat_template_file",!0),Qa),Hi=(xn=class extends Ee{async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let s,n;if(t&&(s=await this.image_processor(t),n=s.image_grid_thw),n){let o=this.image_processor.config.merge_size**2,i=0;const l=this.constructor.image_token,c=n.tolist();e=e.map(d=>{for(;d.includes(l);){const h=Number(c[i++].reduce((_,p)=>_*p,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(h/o)))}return d.replaceAll("<|placeholder|>",l)})}return{...this.tokenizer(e),...s}}},k(xn,"image_processor_class",dt),k(xn,"tokenizer_class",Te),k(xn,"image_token","<|image_pad|>"),xn),fT=(hu=class extends Hi{},k(hu,"image_token","<|image|>"),hu),_T=(kn=class extends Ee{_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:s}=this.feature_extractor.config,n=Math.floor(r/s),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*n}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const{input_features:a}=await this.feature_extractor(t);s.input_features=a;const o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);s.input_features_mask=new U("bool",i,[1,o]);const l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(kn,"tokenizer_class",Te),k(kn,"feature_extractor_class",Lt),k(kn,"uses_processor_config",!0),kn);function pT(e,t){const s=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,s);const a=t.tolist();return n.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var mT=(Xa=class extends Ee{async _call(e,t,r={}){const s=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...s}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:n=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(n!==null&&n.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),h=o.tolist().map(p=>p.map(w=>M_(w))),_=[];for(let p=0;p<i;++p){const w=n!==null?n[p]:null;w!==null&&(h[p]=h[p].map(A=>A.map((S,C)=>S*w[(C+1)%2])));const v=d[p],y=[],M=[],T=[];for(let A=0;A<l;++A){const S=v[A];if(S<=r)continue;const C=h[p][A],I=c[p][A];y.push(S),T.push(C);const x=pT(I.gt(s),t[p]);M.push(x)}_.push({scores:y,boxes:T,labels:this.batch_decode(M)})}return _}},k(Xa,"tokenizer_class",Te),k(Xa,"image_processor_class",dt),Xa);function gT(e,t,r,s,n,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(e);o+=`
38
38
  `}return o+=`
39
- ${s}${a}`+n.repeat(e)+`${s}`,o}function mT(e,t,r,s){return`${t}${s}`+r.repeat(e)+`${t}`}function gT(e,t,r,s,n,a){return e===0&&t===0?mT(r,s,n,a):pT(r,e,t,s,n,a)}var U_=(Tn=class extends Ee{constructor(){super(...arguments);k(this,"fake_image_token","<fake_token_around_image>");k(this,"image_token","<image>");k(this,"global_img_token","<global-img>")}async _call(t,r=null,s={}){s.return_row_col_info??(s.return_row_col_info=!0);let n;r&&(n=await this.image_processor(r,s)),Array.isArray(t)||(t=[t]);const a=n.rows??[new Array(t.length).fill(0)],o=n.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let h=0;h<t.length;++h){const _=t[h],p=a[h],w=o[h];l.push(Dy(_,this.image_token));const v=p.map((T,A)=>gT(T,w[A],i,this.fake_image_token,this.image_token,this.global_img_token)),y=_.split(this.image_token);if(y.length===0)throw new Error("The image token should be present in the text.");let M=y[0];for(let T=0;T<v.length;++T)M+=v[T]+y[T+1];c.push(M)}return{...this.tokenizer(c),...n}}},k(Tn,"image_processor_class",dt),k(Tn,"tokenizer_class",Te),k(Tn,"uses_processor_config",!0),Tn),wT=(En=class extends Ee{constructor(e,t,r){super(e,t,r),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(v=>v.images).flatMap(v=>v.images).map(v=>qt.read(v)));const s=this.tokenizer,n=s.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>s.encode(v,{add_special_tokens:!1}),o=n.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,c,d]=s.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let h=a(o[0]),_=new Array(h.length).fill(!1);for(let v=1;v<o.length;++v){const y=new Array(this.num_image_tokens).fill(l),M=a(o[v]);h=Jt(h,[c],y,[d],M);const T=new Array(this.num_image_tokens).fill(!0);_=Jt(_,[!1],T,[!1],new Array(M.length).fill(!1))}const p=[1,h.length],w={input_ids:new U("int64",h,p),attention_mask:new U("int64",new Array(h.length).fill(1),p),images_seq_mask:new U("bool",_,p),images_emb_mask:new U("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},k(En,"image_processor_class",dt),k(En,"tokenizer_class",Te),k(En,"uses_processor_config",!0),En),vT=(Ya=class extends Ee{async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=e?this.tokenizer(e,r):{},n=t?await this.image_processor(t,r):{};return{...s,...n}}},k(Ya,"tokenizer_class",Te),k(Ya,"image_processor_class",dt),Ya),yT=(Ja=class extends Ee{async _call(e,t=null,r={}){const{image_rows:s,image_cols:n,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){const i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:h=!0}=this.image_processor.config,_=T=>Math.ceil(Math.floor(T/d)/c),p=_(l)**2,w=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",y=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let M=0;t=t.map(T=>{const A=T.split(i);return A[0]+A.slice(1).map(C=>{const S=M++,[N,x]=a[S],R=s[S],z=n[S],$=_(N)*_(x);let Q=w;if(R>1||z>1){const H=i.repeat(p);for(let D=0;D<R;++D)for(let I=0;I<z;++I)Q+=`<|img_row_${D+1}_col_${I+1}|>`+H;h&&(Q+=y+i.repeat($))}else Q+=i.repeat($);return Q+v+C}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},k(Ja,"tokenizer_class",Te),k(Ja,"image_processor_class",dt),Ja),bT=(An=class extends Ee{async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let h=0;h<t.length;++h)t[h]=t[h].replace(i,i.repeat(d))}const n=t?this.tokenizer(t,r):{};return{...s,...n}}},k(An,"tokenizer_class",Te),k(An,"image_processor_class",dt),k(An,"uses_processor_config",!0),An),j_={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},MT=(Ka=class extends Ee{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!j_.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,s]=j_[t],n=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let h=0;h<a;++h){const _=c[h],p=[],w=[];for(let y=1;y<o;++y){const[M,T]=je(nt(_[y]));if(w.push(M),T==s)break;p.push(T)}const v=w.length>0?w.reduce((y,M)=>y*M,1):0;l.push(p),i.push(v)}return[n(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[s,n]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),c=[],d=[];for(let h=0;h<s.length;++h){const[_,p]=je([n[h],o[h],l[h]]);c.push([s[h],a[h],i[h]][p]),d.push(_)}return{generated_text:c,scores:d,char_preds:s,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),r=await Te.from_pretrained("Xenova/gpt2"),s=await Te.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:s},t}async _call(e,t=null){const r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},k(Ka,"tokenizer_class",Te),k(Ka,"image_processor_class",dt),Ka),xT=(Za=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(Za,"tokenizer_class",Te),k(Za,"feature_extractor_class",Lt),Za),kT=(eo=class extends Ee{},k(eo,"tokenizer_class",Te),k(eo,"image_processor_class",dt),eo),ms="<image>";function TT(e,t,r,s,n){return`${s.repeat(r*n)}${t}${e}
40
- `}var ET=(Cn=class extends Ee{async _call(e,t=null,r={}){t||(ue.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(ms))?a=t.map(l=>{const c=l.replaceAll(ms,ms.repeat(n)),d=c.lastIndexOf(ms),h=d===-1?0:d+ms.length;return c.slice(0,h)+s+c.slice(h)+`
41
- `}):(ue.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(l=>TT(l,s,n,ms,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},k(Cn,"tokenizer_class",Te),k(Cn,"image_processor_class",dt),k(Cn,"uses_processor_config",!1),Cn),q_="<|image|>",AT=/<\|image_\d+\|>/g,CT=(to=class extends Ee{async _call(e,t=null,{padding:r=!0,truncation:s=!0,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:n});const{num_img_tokens:i}=o,l=e.map((d,h)=>d.split(AT).join(q_.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:s});const c=this.tokenizer._tokenizer.token_to_id(q_);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},k(to,"image_processor_class",dt),k(to,"tokenizer_class",Te),to),ST=(Sn=class extends Ee{async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:d,spatial_merge_size:h}=this.config,_=d*h,p=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v<t.length;++v){const y=i.repeat(w),M=y+l,T=y+c,A=M.repeat(p-1)+T;t[v]=t[v].replace(i,A)}}const n=t?this.tokenizer(t,r):{};return{...s,...n}}},k(Sn,"tokenizer_class",Te),k(Sn,"image_processor_class",dt),k(Sn,"uses_processor_config",!0),Sn),PT=(hu=class extends Ee{async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},k(hu,"feature_extractor_class",g_),hu),W_=class extends Hi{},FT=class extends W_{},H_=(fu=class extends Ee{async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},k(fu,"image_processor_class",dt),fu),Q_=class extends H_{},LT=class extends Q_{},IT=(ro=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(ro,"tokenizer_class",Te),k(ro,"feature_extractor_class",Lt),ro),OT=(Pn=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);s.audio_token_len=[l],s.audio_values=o;const c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(Pn,"tokenizer_class",Te),k(Pn,"feature_extractor_class",Lt),k(Pn,"uses_processor_config",!0),Pn),va="[AUDIO]",NT="[BEGIN_AUDIO]",DT=375;function zT(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.subarray(s,Math.min(s+t,e.length)));return r}var BT=(Fn=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const s={};if(t){if(!e.includes(va))throw new Error(`The input text does not contain the audio token ${va}.`);Array.isArray(t)||(t=[t]);const a=e.split(va),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(p=>zT(p,i)),c=l.map(p=>p.length),d=l.flat(),h=(await Promise.all(d.map(p=>this.feature_extractor(p,r)))).map(p=>p.input_features);s.audio_values=h.length>1?ze(h,0):h[0];let _=a[0];for(let p=0;p<c.length;++p){_+=NT;for(let w=0;w<c[p];++w)_+=va.repeat(DT);_+=a[p+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(Fn,"tokenizer_class",Te),k(Fn,"feature_extractor_class",Lt),k(Fn,"uses_processor_config",!1),Fn),X_=32,Qi=6,ya=8,RT=10,GT=32,$T=(Ln=class extends Ee{get num_mel_frames_first_audio_chunk(){return(Qi+1)*ya}get num_samples_first_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return ya*e+t}get num_right_pad_tokens(){return Qi+1+RT}get audio_length_per_tok(){return ya}get raw_audio_length_per_tok(){return ya*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(at(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){const s=X_*this.raw_audio_length_per_tok,n=new Float32Array(s+e.length);n.set(e,s);const a=await this.feature_extractor(n,{center:!0}),i=1+(X_+Qi),l=new BigInt64Array(i).fill(BigInt(GT));return l[0]=1n,{input_ids:new U("int64",l,[1,i]),...a}}else{const s=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+s);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},k(Ln,"tokenizer_class",Te),k(Ln,"feature_extractor_class",Lt),k(Ln,"uses_processor_config",!1),Ln),VT=(so=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(so,"tokenizer_class",Te),k(so,"feature_extractor_class",Lt),so),UT=(no=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(no,"tokenizer_class",Te),k(no,"feature_extractor_class",Lt),no),jT=(ao=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(ao,"tokenizer_class",Te),k(ao,"feature_extractor_class",Lt),ao),qT=class{static async from_pretrained(e,t={}){const r=await er(e,an,!0,t),{image_processor_type:s,feature_extractor_type:n,processor_class:a}=r;if(a&&Di[a])return Di[a].from_pretrained(e,t);if(!s&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(s){const l=wa[s.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${s}'.`);o.image_processor=new l(r)}if(n){const l=wa[n];if(l)o.image_processor=new l(r);else{const c=zi[n];if(!c)throw new Error(`Unknown feature_extractor_type: '${n}'.`);o.feature_extractor=new c(r)}}const i={};return new Ee(i,o,null)}};async function WT(e,t){return await er(e,"config.json",!0,t)}function gs(e){const t={};let r={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=gs(e.text_config);break;case"moondream1":r=gs(e.phi_config);break;case"musicgen":r=gs(e.decoder);break;case"multi_modality":r=gs(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";const{num_hidden_layers:n,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:n,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":const i=gs(e.decoder),l="num_decoder_layers"in i,c=rt(e,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=i.num_decoder_layers,c.num_decoder_heads=i.num_decoder_heads,c.decoder_hidden_size=i.decoder_hidden_size,c.num_encoder_layers=i.num_encoder_layers,c.num_encoder_heads=i.num_encoder_heads,c.encoder_hidden_size=i.encoder_hidden_size):(c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size),c}const s={...r,...rt(e,["model_type","multi_query","is_encoder_decoder"])};for(const n in t)s[n]=e[t[n]];return s}function ba(e,t){e instanceof Xi||(e=new Xi(e));const r=(t==null?void 0:t.batch_size)??1;if(["lfm2","lfm2_moe"].includes(e.model_type)){const s=(t==null?void 0:t.prefix)??"past_key_values",n=s==="present"?"present":"past",a={},{layer_types:o,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,conv_L_cache:d}=e,h=c/i;for(let _=0;_<o.length;++_)if(o[_]==="full_attention")for(const p of["key","value"])a[`${s}.${_}.${p}`]=[r,l,0,h];else if(o[_]==="conv")a[`${n}_conv.${_}`]=[r,c,d];else throw new Error(`Unsupported layer type: ${o[_]}`);return a}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){const s=(t==null?void 0:t.prefix)??"past_key_values",n=s==="present"?"present":"past",a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??(o==null?void 0:o.length),l=a.num_key_value_heads,c=a.head_dim??a.hidden_size/a.num_attention_heads,d=a.mamba_n_heads??a.mamba_num_heads,h=a.mamba_d_head??a.mamba_head_dim,_=a.mamba_d_state??a.ssm_state_size,p=a.mamba_n_groups??a.n_groups,w=a.mamba_d_conv??a.conv_kernel,y=(a.mamba_d_ssm??(a.mamba_expand?a.mamba_expand*a.hidden_size:d*h))+2*p*_,M={};for(let T=0;T<i;++T)if((!o||o[T]==="mamba")&&(M[`${n}_conv.${T}`]=[r,y,w],M[`${n}_ssm.${T}`]=[r,d,h,_]),!o||o[T]==="attention")for(const A of["key","value"])M[`${s}.${T}.${A}`]=[r,l,0,c];return M}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){const s=(t==null?void 0:t.prefix)??"past_key_values",n=s==="present"?"present":"past",a={},{head_dim:o,layer_types:i,num_attention_heads:l,num_key_value_heads:c,hidden_size:d,linear_num_value_heads:h,linear_num_key_heads:_,linear_key_head_dim:p,linear_value_head_dim:w,linear_conv_kernel_dim:v}=e,y=p*_,M=w*h,T=o??d/l;for(let A=0;A<i.length;++A)if(i[A]==="full_attention")for(const C of["key","value"])a[`${s}.${A}.${C}`]=[r,c,0,T];else if(i[A]==="linear_attention"){if(e.model_type==="olmo_hybrid")a[`${n}_conv.${A}.key`]=[r,y,v],a[`${n}_conv.${A}.value`]=[r,M,v],a[`${n}_conv.${A}.query`]=[r,y,v];else{const C=y*2+M;a[`${n}_conv.${A}`]=[r,C,v]}a[`${n}_recurrent.${A}`]=[r,h,p,w]}else throw new Error(`Unsupported layer type: ${i[A]}`);return a}else if(["gemma4","gemma4_text"].includes(e.model_type)){const s=e.model_type==="gemma4"?e.text_config:e,n=(t==null?void 0:t.prefix)??"past_key_values",a={},o=s.num_hidden_layers,i=s.num_kv_shared_layers??0,l=o-i,c=s.num_key_value_heads,d=s.head_dim,h=s.global_head_dim??d,_=s.layer_types??[];for(let p=0;p<l;++p){const w=_[p]==="full_attention"?h:d;for(const v of["key","value"])a[`${n}.${p}.${v}`]=[r,c,0,w]}return a}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let s;return e.model_type==="voxtral_realtime"&&(t==null?void 0:t.session_name)==="audio_encoder"?s=e.audio_config:s=e.text_config,ba(s,t)}return HT(e,t)}function HT(e,{prefix:t="past_key_values",batch_size:r=1}={}){const s={},n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){const a=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,o=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,a],l=[r,n.num_decoder_heads,0,o];for(let c=0;c<n.num_decoder_layers;++c)s[`${t}.${c}.encoder.key`]=i,s[`${t}.${c}.encoder.value`]=i,s[`${t}.${c}.decoder.key`]=l,s[`${t}.${c}.decoder.value`]=l}else{const a=n.num_heads,o=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??a);if(n.model_type==="falcon"){const l=[r*a,0,i];for(let c=0;c<o;++c)s[`${t}.${c}.key`]=l,s[`${t}.${c}.value`]=l}else if(n.multi_query){const l=[r*a,0,2*i];for(let c=0;c<o;++c)s[`${t}.${c}.key_value`]=l}else if(n.model_type==="bloom"){const l=[r*a,i,0],c=[r*a,0,i];for(let d=0;d<o;++d)s[`${t}.${d}.key`]=l,s[`${t}.${d}.value`]=c}else if(n.model_type==="openelm")for(let l=0;l<o;++l){const c=[r,a[l],0,i];s[`${t}.${l}.key`]=c,s[`${t}.${l}.value`]=c}else{const l=[r,a,0,i];for(let c=0;c<o;++c)s[`${t}.${c}.key`]=l,s[`${t}.${c}.value`]=l}}return s}var Xi=class vd{constructor(t){k(this,"model_type",null);k(this,"is_encoder_decoder",!1);k(this,"max_position_embeddings");k(this,"transformers.js_config");Object.assign(this,t),this.normalized_config=gs(this)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){s&&!(s instanceof vd)&&(s=new vd(s));const i=s??await WT(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(i)}},on=class{static async from_pretrained(...e){return Xi.from_pretrained(...e)}};function Y_(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function J_(e,t){const r=[];for(let s=0;s<t;++s)r.push(`${e}_data${s===0?"":"_"+s}`);return r}async function QT(e,t,r,s){const n=`${t}${s}.onnx`,a=`${r.subfolder??""}/${n}`;return await ha(e,a,!0,r,fe.IS_NODE_ENV)}async function XT(e,t,r,s,n,a={}){const o=`${t}${r}.onnx`,i=fe.IS_NODE_ENV;let l=[];const c=Y_(n,o,t);if(c>0){if(c>bf)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${bf}).`);const d=J_(o,c);for(const h of d){const _=`${s.subfolder??""}/${h}`;l.push(new Promise(async(p,w)=>{const v=await ha(e,_,!0,s,i);p(v instanceof Uint8Array?{path:h,data:v}:h)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const h=await ha(e,d.data,!0,s);return{...d,data:h}}return d}));return Promise.all(l)}async function YT(e,t,r,s=!1,n=void 0){var C;let a=((C=r.config)==null?void 0:C["transformers.js_config"])??{};const o=Vf(r.device??a.device,t,{warn:S=>ue.info(S)}),i=yx(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const c=qf(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:S=>ue.info(S)});if(Ci.hasOwnProperty(c)){if(o==="webgpu"&&!fe.IS_NODE_ENV&&c===We.fp16&&!await xx())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(We).join(", ")}`);const d=a.kv_cache_dtype,h=d?typeof d=="string"?d:d[c]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);const _=Ci[c],p={...r.session_options};p.executionProviders??(p.executionProviders=i);const w=a.free_dimension_overrides;w?p.freeDimensionOverrides??(p.freeDimensionOverrides=w):o.startsWith("webnn")&&!p.freeDimensionOverrides&&ue.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const v=QT(e,t,r,_),y=r.use_external_data_format??a.use_external_data_format,M=await XT(e,t,_,r,y,p);if(M.length>0&&(!fe.IS_NODE_ENV||M.some(S=>typeof S!="string"))&&(p.externalData=M),s&&o==="webgpu"&&d!==!1){const S=ba(r.config,{prefix:"present",session_name:n});if(Object.keys(S).length>0&&!Ei()){const N={};for(const x in S)N[x]="gpu-buffer";p.preferredOutputLocation=N}}return{buffer_or_path:await v,session_options:p,session_config:{dtype:c,kv_cache_dtype:h,device:o}}}async function JT(e,t,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const a=(s==null?void 0:s[n])??!1,{buffer_or_path:o,session_options:i,session_config:l}=await YT(e,t[n],r,a,n),c=await Bf(o,i,l);return[n,c]})))}function K_(e){for(let t in e)$f(e[t])?e[t]=new U(e[t]):typeof e[t]=="object"&&K_(e[t]);return e}async function xe(e,t){const r=KT(e,t);try{const s=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return fe.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),n=await Gf(e,s);return K_(n)}catch(s){const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw ue.error(`An error occurred during model execution: "${s}".`),ue.error("Inputs given to model:",n),s}}function KT(e,t){const r=Object.create(null),s=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof U)){s.push(o);continue}r[o]=Ei()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);const n=Object.keys(t).length,a=e.inputNames.length;if(n>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ue.warn(`WARNING: Too many inputs were provided (${n} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var Ye=class{},ie=class extends Ye{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},He=class extends Ye{constructor({logits:e}){super(),this.logits=e}},Je=class extends Ye{constructor({logits:e}){super(),this.logits=e}},ht=class extends Ye{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Jr=class extends Ye{constructor({logits:e}){super(),this.logits=e}},ZT=class extends Ye{constructor({alphas:e}){super(),this.alphas=e}},Wt=class extends vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},eE=class extends vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Yi=class extends vt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},tE=class extends Wt{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){const s=t[r].data;s.fill(-1/0),s[this.bos_token_id]=0}return t}},rE=class extends Wt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){const s=t[r].data;s.fill(-1/0);for(const n of this.eos_token_id)s[n]=0}return t}},sE=class extends Wt{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of this.suppress_tokens)s[n]=-1/0}return t}},Z_=class extends Wt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){const s=t[r].data;for(const n of this.begin_suppress_tokens)s[n]=-1/0}return t}},nE=class extends Wt{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;if(s[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){s.subarray(0,this.timestamp_begin).fill(-1/0);continue}const n=e[r].slice(this.begin_index),a=n.length>=1&&n[n.length-1]>=this.timestamp_begin,o=n.length<2||n[n.length-2]>=this.timestamp_begin;if(a&&(o?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const d=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(d+1).fill(-1/0)}const i=ix(s),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=je(i.subarray(0,this.timestamp_begin))[0];l>c&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},aE=class extends Wt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[n+o]);r.push(a.map(Number))}const s=new Map;for(const n of r){const a=n.slice(0,n.length-1),o=JSON.stringify(a),i=s.get(o)??[];i.push(n[n.length-1]),s.set(o,i)}return s}getGeneratedNgrams(e,t){const r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data,n=this.calcBannedNgramTokens(e[r]);for(const a of n)s[a]=-1/0}return t}},oE=class extends Wt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of new Set(e[r])){const a=Number(n);s[a]<0?s[a]*=this.penalty:s[a]/=this.penalty}}return t}},iE=class extends Wt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){const s=t[r].data;for(const n of this.eos_token_id)s[n]=-1/0}return t}},lE=class extends Wt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){const n=t[r].data;for(const a of this.eos_token_id)n[a]=-1/0}return t}},cE=class extends Wt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data,n=e[r];for(const a of this.bad_words_ids){if(n.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=n.at(-i)){o=!1;break}o&&(s[a.at(-1)]=-1/0)}}return t}},uE=class extends Wt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,s=t.slice([0,r],null),n=t.slice([r,t.dims[0]],null);for(let a=0;a<n.data.length;++a)n.data[a]+=(s.data[a]-n.data[a])*this.guidance_scale;return n}},dE=class extends eE{constructor(e){super(),this.temperature=e}_call(e,t){const r=t.data;for(let s=0;s<r.length;++s)r[s]/=this.temperature;return t}},ep=class{constructor(e){k(this,"max_length",20);k(this,"max_new_tokens",null);k(this,"min_length",0);k(this,"min_new_tokens",null);k(this,"early_stopping",!1);k(this,"max_time",null);k(this,"do_sample",!1);k(this,"num_beams",1);k(this,"num_beam_groups",1);k(this,"penalty_alpha",null);k(this,"use_cache",!0);k(this,"temperature",1);k(this,"top_k",50);k(this,"top_p",1);k(this,"typical_p",1);k(this,"epsilon_cutoff",0);k(this,"eta_cutoff",0);k(this,"diversity_penalty",0);k(this,"repetition_penalty",1);k(this,"encoder_repetition_penalty",1);k(this,"length_penalty",1);k(this,"no_repeat_ngram_size",0);k(this,"bad_words_ids",null);k(this,"force_words_ids",null);k(this,"renormalize_logits",!1);k(this,"constraints",null);k(this,"forced_bos_token_id",null);k(this,"forced_eos_token_id",null);k(this,"remove_invalid_values",!1);k(this,"exponential_decay_length_penalty",null);k(this,"suppress_tokens",null);k(this,"streamer",null);k(this,"begin_suppress_tokens",null);k(this,"forced_decoder_ids",null);k(this,"guidance_scale",null);k(this,"num_return_sequences",1);k(this,"output_attentions",!1);k(this,"output_hidden_states",!1);k(this,"output_scores",!1);k(this,"return_dict_in_generate",!1);k(this,"pad_token_id",null);k(this,"bos_token_id",null);k(this,"eos_token_id",null);k(this,"encoder_no_repeat_ngram_size",0);k(this,"decoder_start_token_id",null);k(this,"generation_kwargs",{});Object.assign(this,rt(e,Object.getOwnPropertyNames(this)))}},Ma=class extends vt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},tp=class Ov extends vt{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof Ov?t=t.criteria:t instanceof Ma&&(t=[t]),this.criteria.push(...t)}_call(t,r){const s=new Array(t.length).fill(!1);for(const n of this.criteria){const a=n(t,r);for(let o=0;o<s.length;++o)s[o]||(s[o]=a[o])}return s}[Symbol.iterator](){return this.criteria.values()}},hE=class extends Ma{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(t=>t.length>=this.max_length)}},fE=class extends Ma{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(n=>s==n)})}},xa=class extends vt{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),s=e.data;if(t===-1)s=s.slice(-r);else{let n=t*r;s=s.slice(n,n+r)}return s}randomSelect(e){return jM(e)}static getSampler(e){if(e.do_sample)return new pE(e);if(e.num_beams>1)return new mE(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 _E(e)}},_E=class extends xa{async sample(e){const t=je(e.data)[1];return[[BigInt(t),0]]}},pE=class extends xa{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await _s(e,t),n=nt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(n);return[s.data[a],Math.log(n[a])]})}},mE=class extends xa{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await _s(e,t),n=nt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[s.data[o],Math.log(n[o])])}},gE=class{constructor(e){if(e)for(const t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);const r=e[t];if(!(r instanceof U))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){const e=this;if(Object.keys(e).length===0)return 0;for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(const t in e){const r=this[t],s=e[t];r&&r!==s&&r.location==="gpu-buffer"&&r.dispose(),this[t]=s}}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},Ji=gE,q={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},fr={[q.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[q.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[q.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[q.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[q.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.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"}},[q.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[q.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[q.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"}},[q.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},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 wE(e){const t=fr[e];return(t==null?void 0:t.text_only_sessions)??null}function vE(e,t,r={}){const s=fr[e]??fr.default;return{sessions:s.sessions(t,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function rp(e,{warn:t=!0}={}){const r=e.architectures||[];for(const s of r){const n=_r.get(s);if(n!==void 0)return n}if(e.model_type){const s=_r.get(e.model_type);if(s!==void 0)return s;for(const n of Object.values(ws))if(n.has(e.model_type)){const a=_r.get(n.get(e.model_type));if(a!==void 0)return a}}if(t){const s=r.length>0?r.join(", "):"(none)";ue.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${pa}`)}return q.EncoderOnly}function sp(e,{config:t=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(t!==null)return on.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n});const a=JSON.stringify([e,r,s,n]);return Af(a,()=>on.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n}))}async function np(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){t=await sp(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=s??o.device;let d=r??o.dtype;const h=rp(t),_=(v,y=null)=>{y=y??v;const M=Vf(c,v),T=qf(d,v,M),A=Ci[T]??"",C=`${y}${A}.onnx`,S=`${l}/${C}`;a.push(S);const N=Y_(i,C,v);for(const x of J_(C,N)){const R=`${l}/${x}`;a.push(R)}},{sessions:p,optional_configs:w}=vE(h,t,{model_file_name:n});for(const[v,y]of Object.entries(p))_(v,y);if(w)for(const v of Object.values(w))a.push(v);return a}var ws=null;function yE(e){ws=e}function Ki(e){if(e instanceof U)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new U("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new U("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function ap(e){return new U("bool",[e],[1])}var op={[q.DecoderOnly]:{can_generate:!0,forward:pr,prepare_inputs:ln},[q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:pr,prepare_inputs:ln},[q.Seq2Seq]:{can_generate:!0,forward:ka,prepare_inputs:Ta},[q.Vision2Seq]:{can_generate:!0,forward:ka,prepare_inputs:Ta},[q.Musicgen]:{can_generate:!0,forward:ka},[q.EncoderDecoder]:{can_generate:!1,forward:ka},[q.ImageTextToText]:{can_generate:!0,forward:kE,prepare_inputs:Ea},[q.AudioTextToText]:{can_generate:!0,forward:xE,prepare_inputs:Ea},[q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ea},[q.Phi3V]:{can_generate:!0,prepare_inputs:Ea},[q.MultiModality]:{can_generate:!0},[q.AutoEncoder]:{can_generate:!1,forward:bE},[q.Chatterbox]:{can_generate:!0,forward:Or},[q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ln},default:{can_generate:!1,forward:Or}};function ip(e,t){var i;let r=_r.get(e),s=!1;const n=(i=t==null?void 0:t.architectures)==null?void 0:i[0];if(n&&n!==e&&(e!=null&&e.endsWith("ForCausalLM"))&&n.endsWith("ForConditionalGeneration")){const l=_r.get(n);l!==void 0&&(r=l,s=!0)}const a=op[r]??op.default,o=fr[r]??fr.default;return{typeConfig:{...a,...o},textOnly:s,modelType:r}}var _r=new Map,Zi=new Map,vs=new Map,P=class extends vt{constructor(t,r,s){super();k(this,"main_input_name","input_ids");k(this,"forward_params",["input_ids","attention_mask"]);k(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=s;const n=vs.get(this.constructor),{typeConfig:a}=ip(n,t);this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const t=[];for(const s of Object.values(this.sessions))t.push((r=s.release)==null?void 0:r.call(s));return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:h=null,session_options:_={}}={}){const p={progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:c,dtype:d,use_external_data_format:h,session_options:_},w=vs.get(this);s=p.config=await on.from_pretrained(t,p);const{typeConfig:v,textOnly:y,modelType:M}=ip(w,s);if(M===void 0){const S=w??(s==null?void 0:s.model_type);S!=="custom"&&ue.warn(`Model type for '${S}' not found, assuming encoder-only architecture. Please report this at ${pa}.`)}if(r&&!(r instanceof pi)){const S={};try{const N=await np(t,{config:s,dtype:d,device:c,model_file_name:i});(await Promise.all(N.map(R=>tn(t,R,p)))).forEach((R,z)=>{if(R.exists){const $=N[z]==="config.json";S[N[z]]={loaded:$?R.size??0:0,total:R.size??0}}})}catch(N){ue.warn(`Unable to fetch model file metadata for total progress tracking: ${N}`)}Object.keys(S).length>0&&(p.progress_callback=new pi(r,S))}const T=v.sessions(s,p,y),A=[JT(t,T,p,v.cache_sessions)];v.optional_configs&&A.push(EE(t,v.optional_configs,p));const C=await Promise.all(A);return new this(s,...C)}async _call(t){return await this.forward(t)}async forward(t){return await this._forward(this,t)}get generation_config(){var t;return((t=this.configs)==null?void 0:t.generation_config)??null}_get_logits_processor(t,r,s=null){const n=new Yi;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&n.push(new oE(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&n.push(new aE(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&n.push(new cE(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&n.push(new iE(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&n.push(new lE(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&n.push(new tE(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&n.push(new rE(t.max_length,t.forced_eos_token_id)),t.suppress_tokens!==null&&n.push(new sE(t.suppress_tokens)),t.begin_suppress_tokens!==null){const a=r>1||t.forced_bos_token_id===null?r:r+1;n.push(new Z_(t.begin_suppress_tokens,a))}return t.guidance_scale!==null&&t.guidance_scale>1&&n.push(new uE(t.guidance_scale)),t.temperature===0&&t.do_sample&&(ue.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),t.do_sample=!1),t.do_sample&&t.temperature!==null&&t.temperature!==1&&n.push(new dE(t.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(t,r,s=ep){const n={...this.config};for(const o of["decoder","generator","text_config"])o in n&&Object.assign(n,n[o]);const a=new s(n);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,rt(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){const s=new tp;return t.max_length!==null&&s.push(new hE(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&s.push(new fE(t.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){const t=[ws.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,ws.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,ws.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,ws.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=vs.get(this.constructor),s=new Set,n=this.config.model_type;for(const o of t){const i=o==null?void 0:o.get(n);i&&s.add(i)}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(a+=` Please use the following class instead: ${[...s].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=el(r,s.past_key_values),s.input_ids=new U("int64",t.flat(),[t.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=ze([s.decoder_attention_mask,yt([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=ze([s.attention_mask,yt([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:s}){const n=rt(s,this.forward_params),a=this.main_input_name;if(a in n){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[a]=t;return{inputs_tensor:n[a],model_inputs:n,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:i,attention_mask:l,...c}=r,d=await this._prepare_inputs_embeds(r);r={...c,...rt(d,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await Or(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)a=ze([a,Li(a,0)],0),"attention_mask"in r&&(r.attention_mask=ze([r.attention_mask,Kf(r.attention_mask)],0));else if(r.decoder_input_ids){const o=Ki(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=ze(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof U)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(n??(n=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==t)throw new Error(`\`decoder_start_token_id\` expcted to have length ${t} but got ${n.length}`);i=n}else i=Array.from({length:t},()=>[n]);i=Ki(i)}return l.decoder_attention_mask=Yf(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:t,model_kwargs:o});const d=this.config.is_encoder_decoder;d&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let h;d?{input_ids:h,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):h=l[c];let _=h.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);const p=this._get_logits_processor(r,_,s),w=this._get_stopping_criteria(r,n),v=l[c].dims.at(0),y=xa.getSampler(r),M=new Array(v).fill(0),T=h.tolist();a&&a.put(T);let A,C={},S={};for(;;){if(l=this.prepare_inputs_for_generation(T,l,r),A=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){const I=ME(A);for(const te in I)te in C||(C[te]=[]),C[te].push(I[te])}else this._return_dict_in_generate_keys&&Object.assign(S,rt(A,this._return_dict_in_generate_keys));const $=A.logits.slice(null,-1,null).to("float32"),Q=p(T,$),H=[];for(let I=0;I<Q.dims.at(0);++I){const te=Q[I],W=await y(te);for(const[ee,G]of W){const L=BigInt(ee);M[I]+=G,T[I].push(L),H.push([L]);break}}if(a&&a.put(H),w(T).every(I=>I))break;l=this._update_model_kwargs_for_generation({generated_input_ids:H,outputs:A,model_inputs:l,is_encoder_decoder:d})}a&&a.end();const N=new U("int64",T.flat(),[T.length,T[0].length]),x=el(A,l.past_key_values),R=new Set(Object.values(x));for(const $ of Object.values(A))$.location==="gpu-buffer"&&!R.has($)&&$.dispose();return"past_key_values"in o||r.return_dict_in_generate||await x.dispose(),r.return_dict_in_generate?{sequences:N,past_key_values:x,...C,...S}:N}async _encode_input(t,r,s){if(!Object.hasOwn(this.sessions,t))throw new Error(`Model does not have a ${t} session.`);const n=this.sessions[t];return(await xe(n,rt(r,n.inputNames)))[s]}async encode_image(t){return this._encode_input("vision_encoder",t,"image_features")}async encode_text(t){return this._encode_input("embed_tokens",t,"inputs_embeds")}async encode_audio(t){return this._encode_input("audio_encoder",t,"audio_features")}};async function ka(e,t){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:a,...o}=t;if(!r){const i=rt(t,e.sessions.model.inputNames);r=(await Or(e,i)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,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 pr(e,o,!0)}async function Or(e,t){const r=e.sessions.model,s=rt(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Kf(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const n=s.pixel_values.dims;s.pixel_mask=yt([n[0],n[2],n[3]])}return await xe(r,s)}async function bE(e,t){const r=await e.encode(t);return await e.decode(r)}function el(e,t){const r=Object.create(null);for(const s in e)if(s.startsWith("present")){const n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");s.includes("encoder")&&t?r[n]=t[n]:r[n]=e[s]}return t?(t.update(r),t):new Ji(r)}function ME(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in e)s.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[s]));return t}function tl(e,t,r){var c,d,h;if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;const s=e.sessions.decoder_model_merged??e.sessions.model,n=((d=(c=t[e.main_input_name]??t.attention_mask)==null?void 0:c.dims)==null?void 0:d[0])??1,a=((h=s==null?void 0:s.config)==null?void 0:h.kv_cache_dtype)??"float32",o=a==="float16"?fs.float16:fs.float32,i=ba(e.config,{batch_size:n}),l=Object.create(null);for(const _ in i){const p=i[_].reduce((v,y)=>v*y,1),w=new U(a,new o(p),i[_]);t[_]=w,l[_]=w}return r?(r.update(l),r):new Ji(l)}async function pr(e,t,r=!1){const s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...a}=t;if(s.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=ap(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=TE(a,n,i)}s.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new U("int64",[0n],[])),tl(e,a,n);const o=rt(a,s.inputNames);return await xe(s,o)}async function lp(e,{encode_function:t,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:h=null,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});const w=rt(_,s);if(Object.keys(w).length>0){if(a.dims[1]!==1){const v=await t({...w,..._});({inputs_embeds:l,attention_mask:o}=r({[n]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){const v=a.dims[1],y=c.get_seq_length();o=ze([yt([a.dims[0],y]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){const{image_grid_thw:w,video_grid_thw:v}=_;[i]=e.get_rope_index(a,w,v,o)}return await pr(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},!0)}async function xE(e,t){return await lp(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 kE(e,t){return await lp(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 cp(e,t=0){const[r,s]=e.dims,n=e.data,a=new BigInt64Array(n.length);for(let o=0;o<r;++o){const i=o*s;let l=BigInt(t);for(let c=0;c<s;++c){const d=i+c;n[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=n[d])}}return{data:a,dims:e.dims}}function TE(e,t=null,r=0){const{input_ids:s,inputs_embeds:n,attention_mask:a}=e,{data:o,dims:i}=cp(a,r);let l=new U("int64",o,i);if(t){const c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function ln(e,t,r,s){const n=r.past_key_values?r.past_key_values.get_seq_length():0,a=e.sessions.decoder_model_merged??e.sessions.model;if(a!=null&&a.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new U("int64",[1n],[])),!r.attention_mask){let o;for(const i of["input_ids","inputs_embeds","position_ids"])if(r[i]){o=r[i].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=yt([o[0],n+o[1]])}if(r.past_key_values){const{input_ids:o,attention_mask:i}=r;i&&i.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]))}return r}function Ta(e,t,r,s){return r.past_key_values&&(t=t.map(n=>[n.at(-1)])),{...r,decoder_input_ids:Ki(t)}}function Ea(e,...t){return e.config.is_encoder_decoder?Ta(e,...t):ln(e,...t)}function up({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n}){const a=s.tolist().map(c=>c.reduce((d,h,_)=>(h==e&&d.push(_),d),[])),o=a.reduce((c,d)=>c+d.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){const d=a[c],h=t[c];for(let _=0;_<d.length;++_)h[d[_]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:n}}function rl({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:s,attention_mask:n}){return up({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}function dp({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:s,attention_mask:n}){return up({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}async function EE(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const n=await er(e,t[s],!1,r);return[s,n]})))}var sl={};os(sl,{ASTForAudioClassification:()=>BE,ASTModel:()=>zE,ASTPreTrainedModel:()=>il,AfmoeForCausalLM:()=>OE,AfmoeModel:()=>IE,AfmoePreTrainedModel:()=>al,AlbertForMaskedLM:()=>PE,AlbertForQuestionAnswering:()=>SE,AlbertForSequenceClassification:()=>CE,AlbertModel:()=>AE,AlbertPreTrainedModel:()=>cn,ApertusForCausalLM:()=>LE,ApertusModel:()=>FE,ApertusPreTrainedModel:()=>nl,ArceeForCausalLM:()=>DE,ArceeModel:()=>NE,ArceePreTrainedModel:()=>ol,BartForConditionalGeneration:()=>GE,BartForSequenceClassification:()=>$E,BartModel:()=>RE,BartPretrainedModel:()=>Aa,BeitForImageClassification:()=>UE,BeitModel:()=>VE,BeitPreTrainedModel:()=>ll,BertForMaskedLM:()=>qE,BertForQuestionAnswering:()=>QE,BertForSequenceClassification:()=>WE,BertForTokenClassification:()=>HE,BertModel:()=>jE,BertPreTrainedModel:()=>ys,BlenderbotForConditionalGeneration:()=>YE,BlenderbotModel:()=>XE,BlenderbotPreTrainedModel:()=>cl,BlenderbotSmallForConditionalGeneration:()=>KE,BlenderbotSmallModel:()=>JE,BlenderbotSmallPreTrainedModel:()=>ul,BloomForCausalLM:()=>e2,BloomModel:()=>ZE,BloomPreTrainedModel:()=>dl,CHMv2ForDepthEstimation:()=>l2,CHMv2PreTrainedModel:()=>mp,CLIPModel:()=>u2,CLIPPreTrainedModel:()=>Kr,CLIPSegForImageSegmentation:()=>p2,CLIPSegModel:()=>_2,CLIPSegPreTrainedModel:()=>hl,CLIPTextModel:()=>d2,CLIPTextModelWithProjection:()=>vp,CLIPVisionModel:()=>h2,CLIPVisionModelWithProjection:()=>f2,CamembertForMaskedLM:()=>r2,CamembertForQuestionAnswering:()=>a2,CamembertForSequenceClassification:()=>s2,CamembertForTokenClassification:()=>n2,CamembertModel:()=>t2,CamembertPreTrainedModel:()=>bs,ChatterboxModel:()=>_p,ChatterboxPreTrainedModel:()=>fp,ChineseCLIPModel:()=>i2,ChineseCLIPPreTrainedModel:()=>pp,ClapAudioModelWithProjection:()=>wp,ClapModel:()=>c2,ClapPreTrainedModel:()=>Ca,ClapTextModelWithProjection:()=>gp,CodeGenForCausalLM:()=>g2,CodeGenModel:()=>m2,CodeGenPreTrainedModel:()=>fl,Cohere2ForCausalLM:()=>b2,Cohere2Model:()=>y2,Cohere2PreTrainedModel:()=>pl,CohereAsrForConditionalGeneration:()=>x2,CohereAsrModel:()=>M2,CohereAsrPreTrainedModel:()=>ml,CohereForCausalLM:()=>v2,CohereModel:()=>w2,CoherePreTrainedModel:()=>_l,ConvBertForMaskedLM:()=>T2,ConvBertForQuestionAnswering:()=>C2,ConvBertForSequenceClassification:()=>E2,ConvBertForTokenClassification:()=>A2,ConvBertModel:()=>k2,ConvBertPreTrainedModel:()=>Ms,ConvNextForImageClassification:()=>P2,ConvNextModel:()=>S2,ConvNextPreTrainedModel:()=>gl,ConvNextV2ForImageClassification:()=>L2,ConvNextV2Model:()=>F2,ConvNextV2PreTrainedModel:()=>wl,DFineForObjectDetection:()=>D2,DFineModel:()=>N2,DFinePreTrainedModel:()=>yl,DINOv3ConvNextModel:()=>lA,DINOv3ConvNextPreTrainedModel:()=>Cp,DINOv3ViTModel:()=>cA,DINOv3ViTPreTrainedModel:()=>Sp,DPTForDepthEstimation:()=>gA,DPTModel:()=>mA,DPTPreTrainedModel:()=>El,DacDecoderModel:()=>xp,DacDecoderOutput:()=>bp,DacEncoderModel:()=>Mp,DacEncoderOutput:()=>yp,DacModel:()=>z2,DacPreTrainedModel:()=>Sa,DebertaForMaskedLM:()=>R2,DebertaForQuestionAnswering:()=>V2,DebertaForSequenceClassification:()=>G2,DebertaForTokenClassification:()=>$2,DebertaModel:()=>B2,DebertaPreTrainedModel:()=>xs,DebertaV2ForMaskedLM:()=>W2,DebertaV2ForQuestionAnswering:()=>X2,DebertaV2ForSequenceClassification:()=>H2,DebertaV2ForTokenClassification:()=>Q2,DebertaV2Model:()=>q2,DebertaV2PreTrainedModel:()=>ks,DecisionTransformerModel:()=>Y2,DecisionTransformerPreTrainedModel:()=>kp,DeepseekV3ForCausalLM:()=>j2,DeepseekV3Model:()=>U2,DeepseekV3PreTrainedModel:()=>bl,DeiTForImageClassification:()=>K2,DeiTModel:()=>J2,DeiTPreTrainedModel:()=>Ml,DepthAnythingForDepthEstimation:()=>Z2,DepthAnythingPreTrainedModel:()=>Tp,DepthProForDepthEstimation:()=>eA,DepthProPreTrainedModel:()=>Ep,DetrForObjectDetection:()=>rA,DetrForSegmentation:()=>sA,DetrModel:()=>tA,DetrObjectDetectionOutput:()=>xl,DetrPreTrainedModel:()=>Pa,DetrSegmentationOutput:()=>Ap,Dinov2ForImageClassification:()=>aA,Dinov2Model:()=>nA,Dinov2PreTrainedModel:()=>kl,Dinov2WithRegistersForImageClassification:()=>iA,Dinov2WithRegistersModel:()=>oA,Dinov2WithRegistersPreTrainedModel:()=>Tl,DistilBertForMaskedLM:()=>_A,DistilBertForQuestionAnswering:()=>fA,DistilBertForSequenceClassification:()=>dA,DistilBertForTokenClassification:()=>hA,DistilBertModel:()=>uA,DistilBertPreTrainedModel:()=>Ts,DonutSwinModel:()=>pA,DonutSwinPreTrainedModel:()=>Pp,EdgeTamModel:()=>EF,EfficientNetForImageClassification:()=>vA,EfficientNetModel:()=>wA,EfficientNetPreTrainedModel:()=>Al,ElectraForMaskedLM:()=>bA,ElectraForQuestionAnswering:()=>kA,ElectraForSequenceClassification:()=>MA,ElectraForTokenClassification:()=>xA,ElectraModel:()=>yA,ElectraPreTrainedModel:()=>Es,Ernie4_5ForCausalLM:()=>EA,Ernie4_5Model:()=>TA,Ernie4_5PretrainedModel:()=>Cl,EsmForMaskedLM:()=>CA,EsmForSequenceClassification:()=>SA,EsmForTokenClassification:()=>PA,EsmModel:()=>AA,EsmPreTrainedModel:()=>dn,EuroBertForMaskedLM:()=>LA,EuroBertForSequenceClassification:()=>IA,EuroBertForTokenClassification:()=>OA,EuroBertModel:()=>FA,EuroBertPreTrainedModel:()=>hn,ExaoneForCausalLM:()=>DA,ExaoneModel:()=>NA,ExaonePreTrainedModel:()=>Sl,FalconForCausalLM:()=>BA,FalconH1ForCausalLM:()=>GA,FalconH1Model:()=>RA,FalconH1PreTrainedModel:()=>Fl,FalconModel:()=>zA,FalconPreTrainedModel:()=>Pl,FastViTForImageClassification:()=>VA,FastViTModel:()=>$A,FastViTPreTrainedModel:()=>Ll,Florence2ForConditionalGeneration:()=>UA,Florence2PreTrainedModel:()=>Fp,GLPNForDepthEstimation:()=>oC,GLPNModel:()=>aC,GLPNPreTrainedModel:()=>Gl,GPT2LMHeadModel:()=>mC,GPT2Model:()=>pC,GPT2PreTrainedModel:()=>ql,GPTBigCodeForCausalLM:()=>lC,GPTBigCodeModel:()=>iC,GPTBigCodePreTrainedModel:()=>$l,GPTJForCausalLM:()=>wC,GPTJModel:()=>gC,GPTJPreTrainedModel:()=>Wl,GPTNeoForCausalLM:()=>uC,GPTNeoModel:()=>cC,GPTNeoPreTrainedModel:()=>Vl,GPTNeoXForCausalLM:()=>hC,GPTNeoXModel:()=>dC,GPTNeoXPreTrainedModel:()=>Ul,Gemma2ForCausalLM:()=>HA,Gemma2Model:()=>WA,Gemma2PreTrainedModel:()=>Ol,Gemma3ForCausalLM:()=>JA,Gemma3ForConditionalGeneration:()=>Op,Gemma3Model:()=>YA,Gemma3PreTrainedModel:()=>Ip,Gemma3nForCausalLM:()=>KA,Gemma3nForConditionalGeneration:()=>Fa,Gemma3nPreTrainedModel:()=>Np,Gemma4ForCausalLM:()=>ZA,Gemma4ForConditionalGeneration:()=>Nl,GemmaForCausalLM:()=>qA,GemmaModel:()=>jA,GemmaPreTrainedModel:()=>Il,GlmForCausalLM:()=>tC,GlmModel:()=>eC,GlmMoeDsaForCausalLM:()=>sC,GlmMoeDsaModel:()=>rC,GlmMoeDsaPreTrainedModel:()=>zl,GlmOcrForConditionalGeneration:()=>nC,GlmPreTrainedModel:()=>Dl,GptOssForCausalLM:()=>_C,GptOssModel:()=>fC,GptOssPreTrainedModel:()=>jl,GraniteForCausalLM:()=>yC,GraniteModel:()=>vC,GraniteMoeHybridForCausalLM:()=>MC,GraniteMoeHybridModel:()=>bC,GraniteMoeHybridPreTrainedModel:()=>Ql,GranitePreTrainedModel:()=>Hl,GraniteSpeechForConditionalGeneration:()=>xC,GroundingDinoForObjectDetection:()=>kC,GroundingDinoPreTrainedModel:()=>Gp,GroupViTModel:()=>TC,GroupViTPreTrainedModel:()=>$p,HeliumForCausalLM:()=>AC,HeliumModel:()=>EC,HeliumPreTrainedModel:()=>Yl,HieraForImageClassification:()=>SC,HieraModel:()=>CC,HieraPreTrainedModel:()=>Jl,HubertForCTC:()=>DC,HubertForSequenceClassification:()=>zC,HubertModel:()=>NC,HubertPreTrainedModel:()=>OC,HunYuanDenseV1ForCausalLM:()=>RC,HunYuanDenseV1Model:()=>BC,HunYuanDenseV1PreTrainedModel:()=>Kl,IJepaForImageClassification:()=>$C,IJepaModel:()=>GC,IJepaPreTrainedModel:()=>Zl,Idefics3ForConditionalGeneration:()=>Vp,JAISLMHeadModel:()=>UC,JAISModel:()=>VC,JAISPreTrainedModel:()=>ec,JinaCLIPModel:()=>jC,JinaCLIPPreTrainedModel:()=>La,JinaCLIPTextModel:()=>Up,JinaCLIPVisionModel:()=>qC,Lfm2ForCausalLM:()=>HC,Lfm2Model:()=>WC,Lfm2MoeForCausalLM:()=>YC,Lfm2MoeModel:()=>XC,Lfm2MoePreTrainedModel:()=>rc,Lfm2PreTrainedModel:()=>tc,Lfm2VlForConditionalGeneration:()=>JC,LightOnOcrForConditionalGeneration:()=>QC,LiteWhisperForConditionalGeneration:()=>HL,Llama4ForCausalLM:()=>eS,Llama4PreTrainedModel:()=>jp,LlamaForCausalLM:()=>ZC,LlamaModel:()=>KC,LlamaPreTrainedModel:()=>sc,LlavaForConditionalGeneration:()=>mr,LlavaOnevisionForConditionalGeneration:()=>mr,LlavaPreTrainedModel:()=>Lp,LlavaQwen2ForCausalLM:()=>XA,LongT5ForConditionalGeneration:()=>rS,LongT5Model:()=>tS,LongT5PreTrainedModel:()=>nc,M2M100ForConditionalGeneration:()=>nS,M2M100Model:()=>sS,M2M100PreTrainedModel:()=>ac,MBartForCausalLM:()=>hS,MBartForConditionalGeneration:()=>uS,MBartForSequenceClassification:()=>dS,MBartModel:()=>cS,MBartPreTrainedModel:()=>fn,MPNetForMaskedLM:()=>KS,MPNetForQuestionAnswering:()=>tP,MPNetForSequenceClassification:()=>ZS,MPNetForTokenClassification:()=>eP,MPNetModel:()=>JS,MPNetPreTrainedModel:()=>As,MT5ForConditionalGeneration:()=>aP,MT5Model:()=>nP,MT5PreTrainedModel:()=>mc,MarianMTModel:()=>oS,MarianModel:()=>aS,MarianPreTrainedModel:()=>oc,MaskFormerForInstanceSegmentation:()=>lS,MaskFormerModel:()=>iS,MaskFormerPreTrainedModel:()=>ic,Metric3DForDepthEstimation:()=>fS,Metric3DPreTrainedModel:()=>qp,Metric3Dv2ForDepthEstimation:()=>_S,Metric3Dv2PreTrainedModel:()=>Wp,MgpstrForSceneTextRecognition:()=>pS,MgpstrModelOutput:()=>Hp,MgpstrPreTrainedModel:()=>Qp,MimiDecoderModel:()=>Kp,MimiDecoderOutput:()=>Yp,MimiEncoderModel:()=>Jp,MimiEncoderOutput:()=>Xp,MimiModel:()=>mS,MimiPreTrainedModel:()=>Ia,Mistral4ForCausalLM:()=>yS,Mistral4Model:()=>vS,Mistral4PreTrainedModel:()=>cc,MistralForCausalLM:()=>wS,MistralModel:()=>gS,MistralPreTrainedModel:()=>lc,MobileBertForMaskedLM:()=>MS,MobileBertForQuestionAnswering:()=>kS,MobileBertForSequenceClassification:()=>xS,MobileBertModel:()=>bS,MobileBertPreTrainedModel:()=>_n,MobileLLMForCausalLM:()=>ES,MobileLLMModel:()=>TS,MobileLLMPreTrainedModel:()=>uc,MobileNetV1ForImageClassification:()=>CS,MobileNetV1ForSemanticSegmentation:()=>SS,MobileNetV1Model:()=>AS,MobileNetV1PreTrainedModel:()=>Oa,MobileNetV2ForImageClassification:()=>FS,MobileNetV2ForSemanticSegmentation:()=>LS,MobileNetV2Model:()=>PS,MobileNetV2PreTrainedModel:()=>Na,MobileNetV3ForImageClassification:()=>OS,MobileNetV3ForSemanticSegmentation:()=>NS,MobileNetV3Model:()=>IS,MobileNetV3PreTrainedModel:()=>Da,MobileNetV4ForImageClassification:()=>zS,MobileNetV4ForSemanticSegmentation:()=>BS,MobileNetV4Model:()=>DS,MobileNetV4PreTrainedModel:()=>za,MobileViTForImageClassification:()=>GS,MobileViTModel:()=>RS,MobileViTPreTrainedModel:()=>dc,MobileViTV2ForImageClassification:()=>VS,MobileViTV2Model:()=>$S,MobileViTV2PreTrainedModel:()=>hc,ModernBertDecoderForCausalLM:()=>QS,ModernBertDecoderModel:()=>HS,ModernBertDecoderPreTrainedModel:()=>fc,ModernBertForMaskedLM:()=>jS,ModernBertForSequenceClassification:()=>qS,ModernBertForTokenClassification:()=>WS,ModernBertModel:()=>US,ModernBertPreTrainedModel:()=>pn,Moondream1ForConditionalGeneration:()=>QA,MoonshineForConditionalGeneration:()=>YS,MoonshineModel:()=>XS,MoonshinePreTrainedModel:()=>_c,MptForCausalLM:()=>sP,MptModel:()=>rP,MptPreTrainedModel:()=>pc,MultiModalityCausalLM:()=>oP,MultiModalityPreTrainedModel:()=>Zp,MusicgenForCausalLM:()=>lP,MusicgenForConditionalGeneration:()=>em,MusicgenModel:()=>iP,MusicgenPreTrainedModel:()=>gc,NanoChatForCausalLM:()=>uP,NanoChatModel:()=>cP,NanoChatPreTrainedModel:()=>wc,NemotronHForCausalLM:()=>hP,NemotronHModel:()=>dP,NemotronHPreTrainedModel:()=>vc,NeoBertForMaskedLM:()=>_P,NeoBertForQuestionAnswering:()=>gP,NeoBertForSequenceClassification:()=>pP,NeoBertForTokenClassification:()=>mP,NeoBertModel:()=>fP,NeoBertPreTrainedModel:()=>Cs,NomicBertModel:()=>wP,NomicBertPreTrainedModel:()=>tm,OPTForCausalLM:()=>PP,OPTModel:()=>SP,OPTPreTrainedModel:()=>Tc,Olmo2ForCausalLM:()=>MP,Olmo2Model:()=>bP,Olmo2PreTrainedModel:()=>bc,Olmo3ForCausalLM:()=>kP,Olmo3Model:()=>xP,Olmo3PreTrainedModel:()=>Mc,OlmoForCausalLM:()=>yP,OlmoHybridForCausalLM:()=>EP,OlmoHybridModel:()=>TP,OlmoHybridPreTrainedModel:()=>xc,OlmoModel:()=>vP,OlmoPreTrainedModel:()=>yc,OpenELMForCausalLM:()=>CP,OpenELMModel:()=>AP,OpenELMPreTrainedModel:()=>kc,OwlViTForObjectDetection:()=>OP,OwlViTModel:()=>IP,OwlViTPreTrainedModel:()=>Ac,Owlv2ForObjectDetection:()=>LP,Owlv2Model:()=>FP,Owlv2PreTrainedModel:()=>Ec,PaliGemmaForConditionalGeneration:()=>NP,ParakeetForCTC:()=>DP,ParakeetPreTrainedModel:()=>rm,PatchTSMixerForPrediction:()=>BP,PatchTSMixerModel:()=>zP,PatchTSMixerPreTrainedModel:()=>Cc,PatchTSTForPrediction:()=>GP,PatchTSTModel:()=>RP,PatchTSTPreTrainedModel:()=>Sc,Phi3ForCausalLM:()=>jP,Phi3Model:()=>UP,Phi3PreTrainedModel:()=>Fc,Phi3VForCausalLM:()=>nm,Phi3VPreTrainedModel:()=>sm,PhiForCausalLM:()=>VP,PhiModel:()=>$P,PhiPreTrainedModel:()=>Pc,PreTrainedModel:()=>P,PvtForImageClassification:()=>WP,PvtModel:()=>qP,PvtPreTrainedModel:()=>Lc,PyAnnoteForAudioFrameClassification:()=>QP,PyAnnoteModel:()=>HP,PyAnnotePreTrainedModel:()=>Ic,Qwen2ForCausalLM:()=>YP,Qwen2Model:()=>XP,Qwen2MoeForCausalLM:()=>KP,Qwen2MoeModel:()=>JP,Qwen2MoePreTrainedModel:()=>Nc,Qwen2PreTrainedModel:()=>Oc,Qwen2VLForCausalLM:()=>zp,Qwen2VLForConditionalGeneration:()=>Bl,Qwen2VLPreTrainedModel:()=>Dp,Qwen2_5_VLForCausalLM:()=>Bp,Qwen2_5_VLForConditionalGeneration:()=>Rl,Qwen3ForCausalLM:()=>eF,Qwen3Model:()=>ZP,Qwen3MoeForCausalLM:()=>rF,Qwen3MoeModel:()=>tF,Qwen3MoePreTrainedModel:()=>zc,Qwen3NextForCausalLM:()=>nF,Qwen3NextModel:()=>sF,Qwen3NextPreTrainedModel:()=>Bc,Qwen3PreTrainedModel:()=>Dc,Qwen3VLForCausalLM:()=>am,Qwen3VLForConditionalGeneration:()=>Rc,Qwen3VLMoeForCausalLM:()=>oF,Qwen3VLMoeForConditionalGeneration:()=>aF,Qwen3_5ForCausalLM:()=>om,Qwen3_5ForConditionalGeneration:()=>Gc,Qwen3_5MoeForCausalLM:()=>lF,Qwen3_5MoeForConditionalGeneration:()=>iF,RFDetrForObjectDetection:()=>hF,RFDetrModel:()=>dF,RFDetrObjectDetectionOutput:()=>im,RFDetrPreTrainedModel:()=>Vc,RTDetrForObjectDetection:()=>O2,RTDetrModel:()=>I2,RTDetrObjectDetectionOutput:()=>un,RTDetrPreTrainedModel:()=>vl,RTDetrV2ForObjectDetection:()=>kF,RTDetrV2Model:()=>xF,RTDetrV2ObjectDetectionOutput:()=>lm,RTDetrV2PreTrainedModel:()=>Uc,ResNetForImageClassification:()=>uF,ResNetModel:()=>cF,ResNetPreTrainedModel:()=>$c,RoFormerForMaskedLM:()=>vF,RoFormerForQuestionAnswering:()=>MF,RoFormerForSequenceClassification:()=>yF,RoFormerForTokenClassification:()=>bF,RoFormerModel:()=>wF,RoFormerPreTrainedModel:()=>Ps,RobertaForMaskedLM:()=>_F,RobertaForQuestionAnswering:()=>gF,RobertaForSequenceClassification:()=>pF,RobertaForTokenClassification:()=>mF,RobertaModel:()=>fF,RobertaPreTrainedModel:()=>Ss,Sam2ImageSegmentationOutput:()=>dm,Sam2Model:()=>jc,Sam2PreTrainedModel:()=>hm,Sam3TrackerModel:()=>AF,SamImageSegmentationOutput:()=>cm,SamModel:()=>TF,SamPreTrainedModel:()=>um,SapiensForDepthEstimation:()=>SF,SapiensForNormalEstimation:()=>PF,SapiensForSemanticSegmentation:()=>CF,SapiensPreTrainedModel:()=>Ba,SegformerForImageClassification:()=>LF,SegformerForSemanticSegmentation:()=>IF,SegformerModel:()=>FF,SegformerPreTrainedModel:()=>Ra,SiglipModel:()=>OF,SiglipPreTrainedModel:()=>qc,SiglipTextModel:()=>fm,SiglipVisionModel:()=>NF,SmolLM3ForCausalLM:()=>zF,SmolLM3Model:()=>DF,SmolLM3PreTrainedModel:()=>Wc,SmolVLMForConditionalGeneration:()=>BF,SnacDecoderModel:()=>pm,SnacEncoderModel:()=>_m,SnacModel:()=>RF,SnacPreTrainedModel:()=>Ga,SolarOpenForCausalLM:()=>$F,SolarOpenModel:()=>GF,SolarOpenPreTrainedModel:()=>Hc,SpeechT5ForSpeechToText:()=>UF,SpeechT5ForTextToSpeech:()=>jF,SpeechT5HifiGan:()=>qF,SpeechT5Model:()=>VF,SpeechT5PreTrainedModel:()=>$a,SqueezeBertForMaskedLM:()=>HF,SqueezeBertForQuestionAnswering:()=>XF,SqueezeBertForSequenceClassification:()=>QF,SqueezeBertModel:()=>WF,SqueezeBertPreTrainedModel:()=>mn,StableLmForCausalLM:()=>JF,StableLmModel:()=>YF,StableLmPreTrainedModel:()=>Qc,Starcoder2ForCausalLM:()=>ZF,Starcoder2Model:()=>KF,Starcoder2PreTrainedModel:()=>Xc,StyleTextToSpeech2Model:()=>eL,StyleTextToSpeech2PreTrainedModel:()=>mm,SupertonicForConditionalGeneration:()=>wm,SupertonicPreTrainedModel:()=>gm,Swin2SRForImageSuperResolution:()=>aL,Swin2SRModel:()=>nL,Swin2SRPreTrainedModel:()=>Yc,SwinForImageClassification:()=>rL,SwinForSemanticSegmentation:()=>sL,SwinModel:()=>tL,SwinPreTrainedModel:()=>Va,T5ForConditionalGeneration:()=>iL,T5Model:()=>oL,T5PreTrainedModel:()=>Jc,TableTransformerForObjectDetection:()=>cL,TableTransformerModel:()=>lL,TableTransformerObjectDetectionOutput:()=>vm,TableTransformerPreTrainedModel:()=>Kc,TrOCRForCausalLM:()=>uL,TrOCRPreTrainedModel:()=>ym,UltravoxModel:()=>Xl,UltravoxPreTrainedModel:()=>Rp,UniSpeechForCTC:()=>hL,UniSpeechForSequenceClassification:()=>fL,UniSpeechModel:()=>dL,UniSpeechPreTrainedModel:()=>Ua,UniSpeechSatForAudioFrameClassification:()=>gL,UniSpeechSatForCTC:()=>pL,UniSpeechSatForSequenceClassification:()=>mL,UniSpeechSatModel:()=>_L,UniSpeechSatPreTrainedModel:()=>gn,VaultGemmaForCausalLM:()=>vL,VaultGemmaModel:()=>wL,VaultGemmaPreTrainedModel:()=>Zc,ViTForImageClassification:()=>ML,ViTMAEModel:()=>xL,ViTMAEPreTrainedModel:()=>bm,ViTMSNForImageClassification:()=>TL,ViTMSNModel:()=>kL,ViTMSNPreTrainedModel:()=>tu,ViTModel:()=>bL,ViTPreTrainedModel:()=>eu,VisionEncoderDecoderModel:()=>yL,VitMatteForImageMatting:()=>EL,VitMattePreTrainedModel:()=>Mm,VitPoseForPoseEstimation:()=>AL,VitPosePreTrainedModel:()=>xm,VitsModel:()=>CL,VitsModelOutput:()=>km,VitsPreTrainedModel:()=>Tm,VoxtralForConditionalGeneration:()=>SL,VoxtralRealtimeForConditionalGeneration:()=>Cm,VoxtralRealtimePreTrainedModel:()=>Am,Wav2Vec2BertForCTC:()=>zL,Wav2Vec2BertForSequenceClassification:()=>BL,Wav2Vec2BertModel:()=>DL,Wav2Vec2BertPreTrainedModel:()=>ja,Wav2Vec2ForAudioFrameClassification:()=>IC,Wav2Vec2ForCTC:()=>FC,Wav2Vec2ForSequenceClassification:()=>LC,Wav2Vec2Model:()=>PC,Wav2Vec2PreTrainedModel:()=>Nr,WavLMForAudioFrameClassification:()=>UL,WavLMForCTC:()=>GL,WavLMForSequenceClassification:()=>$L,WavLMForXVector:()=>VL,WavLMModel:()=>RL,WavLMPreTrainedModel:()=>Fs,WeSpeakerResNetModel:()=>jL,WeSpeakerResNetPreTrainedModel:()=>Pm,WhisperForConditionalGeneration:()=>Fm,WhisperModel:()=>WL,WhisperPreTrainedModel:()=>su,XLMForQuestionAnswering:()=>KL,XLMForSequenceClassification:()=>YL,XLMForTokenClassification:()=>JL,XLMModel:()=>QL,XLMPreTrainedModel:()=>Ls,XLMRobertaForMaskedLM:()=>eI,XLMRobertaForQuestionAnswering:()=>sI,XLMRobertaForSequenceClassification:()=>tI,XLMRobertaForTokenClassification:()=>rI,XLMRobertaModel:()=>ZL,XLMRobertaPreTrainedModel:()=>Is,XLMWithLMHeadModel:()=>XL,XVectorOutput:()=>Sm,YolosForObjectDetection:()=>aI,YolosModel:()=>nI,YolosObjectDetectionOutput:()=>Lm,YolosPreTrainedModel:()=>nu,YoutuForCausalLM:()=>iI,YoutuModel:()=>oI,YoutuPreTrainedModel:()=>au});var cn=class extends P{},AE=class extends cn{},CE=class extends cn{async _call(e){return new ie(await super._call(e))}},SE=class extends cn{async _call(e){return new ht(await super._call(e))}},PE=class extends cn{async _call(e){return new Je(await super._call(e))}},nl=class extends P{},FE=class extends nl{},LE=class extends nl{},al=class extends P{},IE=class extends al{},OE=class extends al{},ol=class extends P{},NE=class extends ol{},DE=class extends ol{},il=class extends P{},zE=class extends il{},BE=class extends il{},Aa=class extends P{},RE=class extends Aa{},GE=class extends Aa{},$E=class extends Aa{async _call(e){return new ie(await super._call(e))}},ll=class extends P{},VE=class extends ll{},UE=class extends ll{async _call(e){return new ie(await super._call(e))}},ys=class extends P{},jE=class extends ys{},qE=class extends ys{async _call(e){return new Je(await super._call(e))}},WE=class extends ys{async _call(e){return new ie(await super._call(e))}},HE=class extends ys{async _call(e){return new He(await super._call(e))}},QE=class extends ys{async _call(e){return new ht(await super._call(e))}},cl=class extends P{},XE=class extends cl{},YE=class extends cl{},ul=class extends P{},JE=class extends ul{},KE=class extends ul{},dl=class extends P{},ZE=class extends dl{},e2=class extends dl{},bs=class extends P{},t2=class extends bs{},r2=class extends bs{async _call(e){return new Je(await super._call(e))}},s2=class extends bs{async _call(e){return new ie(await super._call(e))}},n2=class extends bs{async _call(e){return new He(await super._call(e))}},a2=class extends bs{async _call(e){return new ht(await super._call(e))}},o2=4299n,hp=6561n,fp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);k(this,"main_input_name","input_ids");k(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},_p=class extends fp{async encode_speech(e){return xe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:c=null,audio_tokens:d=null,speaker_embeddings:h=null,speaker_features:_=null,...p}){let w;if(!a){const y=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(y.includes("exaggeration")){if(!(s instanceof U)){const T=e.dims[0];if(s==null)s=ct([T],.5);else if(typeof s=="number")s=ct([T],s);else if(Array.isArray(s))s=new U("float32",s,[T]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=s}if(y.includes("position_ids")&&(M.position_ids=n),{inputs_embeds:a}=await xe(this.sessions.embed_tokens,M),c&&d&&h&&_&&(w={audio_features:c,audio_tokens:d,speaker_embeddings:h,speaker_features:_}),w||r)w??(w=await this.encode_speech(r)),a=ze([w.audio_features,a],1),t=yt([a.dims[0],a.dims[1]]);else{const T=a.dims[1];if(!o||T!==1)throw new Error("Incorrect state encountered during generation.");const A=o.get_seq_length();t=yt([a.dims[0],A+T])}}return{...await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...w}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const s=Array.from({length:e.length},(n,a)=>e[a].length-e[a].findLastIndex(o=>o==hp)-1);t.position_ids=new U("int64",s,[e.length,1])}else{const n=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=hp?0:o++)});t.position_ids=new U("int64",n.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ln(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:s,speaker_features:n}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=ct([a.dims[0],3],o2),i=ze([r,a,o],1),{waveform:l}=await xe(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:n,speaker_embeddings:s});return l}},pp=class extends P{},i2=class extends pp{},mp=class extends P{},l2=class extends mp{},Ca=class extends P{},c2=class extends Ca{},gp=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},wp=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Kr=class extends P{},u2=class extends Kr{},d2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},vp=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},h2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},f2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},hl=class extends P{},_2=class extends hl{},p2=class extends hl{},fl=class extends P{},m2=class extends fl{},g2=class extends fl{},_l=class extends P{},w2=class extends _l{},v2=class extends _l{},pl=class extends P{},y2=class extends pl{},b2=class extends pl{},ml=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"])}},M2=class extends ml{},x2=class extends ml{},Ms=class extends P{},k2=class extends Ms{},T2=class extends Ms{async _call(e){return new Je(await super._call(e))}},E2=class extends Ms{async _call(e){return new ie(await super._call(e))}},A2=class extends Ms{async _call(e){return new He(await super._call(e))}},C2=class extends Ms{async _call(e){return new ht(await super._call(e))}},gl=class extends P{},S2=class extends gl{},P2=class extends gl{async _call(e){return new ie(await super._call(e))}},wl=class extends P{},F2=class extends wl{},L2=class extends wl{async _call(e){return new ie(await super._call(e))}},vl=class extends P{},I2=class extends vl{},O2=class extends vl{async _call(e){return new un(await super._call(e))}},un=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},yl=class extends P{},N2=class extends yl{},D2=class extends yl{async _call(e){return new un(await super._call(e))}},yp=class extends Ye{constructor({audio_codes:e}){super(),this.audio_codes=e}},bp=class extends Ye{constructor({audio_values:e}){super(),this.audio_values=e}},Sa=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},z2=class extends Sa{async encode(e){return new yp(await xe(this.sessions.encoder_model,e))}async decode(e){return new bp(await xe(this.sessions.decoder_model,e))}},Mp=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},xp=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},xs=class extends P{},B2=class extends xs{},R2=class extends xs{async _call(e){return new Je(await super._call(e))}},G2=class extends xs{async _call(e){return new ie(await super._call(e))}},$2=class extends xs{async _call(e){return new He(await super._call(e))}},V2=class extends xs{async _call(e){return new ht(await super._call(e))}},bl=class extends P{},U2=class extends bl{},j2=class extends bl{},ks=class extends P{},q2=class extends ks{},W2=class extends ks{async _call(e){return new Je(await super._call(e))}},H2=class extends ks{async _call(e){return new ie(await super._call(e))}},Q2=class extends ks{async _call(e){return new He(await super._call(e))}},X2=class extends ks{async _call(e){return new ht(await super._call(e))}},kp=class extends P{},Y2=class extends kp{},Ml=class extends P{},J2=class extends Ml{},K2=class extends Ml{async _call(e){return new ie(await super._call(e))}},Tp=class extends P{},Z2=class extends Tp{},Ep=class extends P{},eA=class extends Ep{},Pa=class extends P{},tA=class extends Pa{},rA=class extends Pa{async _call(e){return new xl(await super._call(e))}},sA=class extends Pa{async _call(e){return new Ap(await super._call(e))}},xl=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ap=class extends Ye{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},kl=class extends P{},nA=class extends kl{},aA=class extends kl{async _call(e){return new ie(await super._call(e))}},Tl=class extends P{},oA=class extends Tl{},iA=class extends Tl{async _call(e){return new ie(await super._call(e))}},Cp=class extends P{},lA=class extends Cp{},Sp=class extends P{},cA=class extends Sp{},Ts=class extends P{},uA=class extends Ts{},dA=class extends Ts{async _call(e){return new ie(await super._call(e))}},hA=class extends Ts{async _call(e){return new He(await super._call(e))}},fA=class extends Ts{async _call(e){return new ht(await super._call(e))}},_A=class extends Ts{async _call(e){return new Je(await super._call(e))}},Pp=class extends P{},pA=class extends Pp{},El=class extends P{},mA=class extends El{},gA=class extends El{},Al=class extends P{},wA=class extends Al{},vA=class extends Al{async _call(e){return new ie(await super._call(e))}},Es=class extends P{},yA=class extends Es{},bA=class extends Es{async _call(e){return new Je(await super._call(e))}},MA=class extends Es{async _call(e){return new ie(await super._call(e))}},xA=class extends Es{async _call(e){return new He(await super._call(e))}},kA=class extends Es{async _call(e){return new ht(await super._call(e))}},Cl=class extends P{},TA=class extends Cl{},EA=class extends Cl{},dn=class extends P{},AA=class extends dn{},CA=class extends dn{async _call(e){return new Je(await super._call(e))}},SA=class extends dn{async _call(e){return new ie(await super._call(e))}},PA=class extends dn{async _call(e){return new He(await super._call(e))}},hn=class extends P{},FA=class extends hn{},LA=class extends hn{async _call(e){return new Je(await super._call(e))}},IA=class extends hn{async _call(e){return new ie(await super._call(e))}},OA=class extends hn{async _call(e){return new He(await super._call(e))}},Sl=class extends P{},NA=class extends Sl{},DA=class extends Sl{},Pl=class extends P{},zA=class extends Pl{},BA=class extends Pl{},Fl=class extends P{},RA=class extends Fl{},GA=class extends Fl{},Ll=class extends P{},$A=class extends Ll{},VA=class extends Ll{async _call(e){return new ie(await super._call(e))}},Fp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);k(this,"main_input_name","inputs_embeds")}},UA=class extends Fp{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:s}){return{inputs_embeds:ze([t,e],1),attention_mask:ze([yt(t.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:s}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,a;return e&&(n=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),n&&a?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:a,input_ids:e,attention_mask:s}):r=n||a,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:n,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:d}=await Or(this,{inputs_embeds:i,attention_mask:r});a=d}if(!l){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:s})}return await pr(this,{inputs_embeds:l,attention_mask:n,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},Il=class extends P{},jA=class extends Il{},qA=class extends Il{},Ol=class extends P{},WA=class extends Ol{},HA=class extends Ol{},Lp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},mr=class extends Lp{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return rl({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},QA=class extends mr{},XA=class extends mr{},Ip=class extends P{},YA=class extends Ip{},Op=class extends mr{},JA=class extends Op{},Np=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},Fa=class extends Np{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:s=null,input_features_mask:n=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,...h}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await xe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:p}=await this._encode_vision({pixel_values:r,...h});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(s){const{audio_features:p}=await xe(this.sessions.audio_encoder,{input_features:s,input_features_mask:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await pr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d},!0)}_encode_vision(e){return xe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return rl({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return dp({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},KA=class extends Fa{},Nl=class extends Fa{constructor(){super(...arguments);k(this,"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(t){return xe(this.sessions.vision_encoder,{pixel_values:t.pixel_values,pixel_position_ids:t.image_position_ids})}},ZA=class extends Nl{},Dl=class extends P{},eC=class extends Dl{},tC=class extends Dl{},zl=class extends P{},rC=class extends zl{},sC=class extends zl{},Dp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},Bl=class extends Dp{constructor(){super(...arguments);k(this,"image_grid_thw_name","grid_thw")}_get_text_only_rope_index(t,r){if(r){const{data:s,dims:n}=cp(r),a=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),o=Array.from({length:n[0]},(i,l)=>je(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new U("int64",a,[3,...n]),new U("int64",o,[o.length,1])]}else{const[s,n]=t.dims,a=BigInt64Array.from({length:3*s*n},(o,i)=>BigInt(Math.floor(i%n/s)));return[new U("int64",a,[3,...t.dims]),Jf([s,1])]}}_reorder_and_write_positions(t,r,s,n){const a=t.reduce((c,d)=>c+d.length,0),o=new Array(a);let i=0;for(let c=0;c<3;++c)for(const d of t){const h=d.length/3;for(let _=c*h;_<(c+1)*h;++_)o[i++]=d[_]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let d=0;d<3;++d)s[d][n][c]=o[d*a/3+l];++l}return o}_get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:a}){const{image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,c=t,h=c.reduce((T,A,C)=>(A==l&&T.push(C),T),[]).map(T=>c[T+1]),_=h.filter(T=>T==o).length,p=h.filter(T=>T==i).length,w=[];let v=0,y=_,M=p;for(let T=0;T<h.length;++T){const A=c.findIndex((X,J)=>J>v&&X==o),C=c.findIndex((X,J)=>J>v&&X==i),S=y>0&&A!==-1?A:c.length+1,N=M>0&&C!==-1?C:c.length+1;let x,R,z,$;S<N?([R,z,$]=r[a.image_index],++a.image_index,--y,x=S):([R,z,$]=s[a.video_index],++a.video_index,--M,x=N);const[Q,H,D]=[Number(R),Math.floor(Number(z)/n),Math.floor(Number($)/n)],I=x-v,te=w.length>0?je(w.at(-1))[0]+1:0;w.push(Array.from({length:3*I},(X,J)=>te+J%I));const W=I+te,ee=Q*H*D,G=Array.from({length:ee},(X,J)=>W+Math.floor(J/(H*D))),L=Array.from({length:ee},(X,J)=>W+Math.floor(J/D)%H),V=Array.from({length:ee},(X,J)=>W+J%D);w.push([G,L,V].flat()),v=x+ee}if(v<c.length){const T=w.length>0?je(w.at(-1))[0]+1:0,A=c.length-v;w.push(Array.from({length:3*A},(C,S)=>T+S%A))}return w}get_rope_index(t,r,s,n){const{vision_config:a}=this.config,o=a.spatial_merge_size??2;if(r||s){const i=t.tolist();n||(n=Yf(t));const l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:t.dims[0]},()=>Array.from({length:t.dims[1]},()=>0))),d=r?r.tolist():[],h=s?s.tolist():[],_={image_index:0,video_index:0},p=[];for(let w=0;w<i.length;++w){const v=i[w].filter((T,A)=>l[w][A]==1),y=this._get_multimodal_rope_positions({filtered_ids:v,image_grid_thw_list:d,video_grid_thw_list:h,spatial_merge_size:o,state:_}),M=this._reorder_and_write_positions(y,l[w],c,w);p.push(je(M)[0]+1-i[w].length)}return[new U("int64",c.flat(1/0),[3,t.dims[0],t.dims[1]]),new U("int64",p,[p.length,1])]}else return this._get_text_only_rope_index(t,n)}async encode_image({pixel_values:t,image_grid_thw:r}){return(await xe(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return rl({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,s){if(!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;const a=r.past_key_values.get_seq_length();if(a<r.input_ids.dims[1]){const[o,i]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=i,r.position_ids=o.slice(null,null,[a,null]),r.input_ids=r.input_ids.slice(null,[a,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));const o=BigInt(a),i=r.rope_deltas.map(l=>o+l);r.position_ids=dr([i,i,i],0)}}return r}},zp=class extends Bl{},Rl=class extends Bl{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw")}},Bp=class extends zp{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw")}},nC=class extends Rl{get_vision_position_ids(e,t,r,s){const n=Math.floor(t[0]/r),a=Math.floor(t[1]/s),o=Math.floor(t[2]/s),i=a*o*n,l=Array.from({length:i},()=>e),c=Array.from({length:i},(h,_)=>e+Math.floor(_/(o*n))),d=Array.from({length:i},(h,_)=>e+_%o);return[...l,...c,...d]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:s,state:n}){const{image_token_id:a}=this.config,o=[];let i=0,l=e[0]==a?1:0;for(let h=1;h<=e.length;++h){const _=h<e.length?e[h]==a?1:0:-1;_!==l&&(o.push([l,i,h]),i=h,l=_)}let c=0;const d=[];for(const[h,_,p]of o)if(h===0){const w=p-_;d.push(Array.from({length:3*w},(v,y)=>c+y%w)),c+=w}else{const w=t[n.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(c,w,v,s)),c+=Math.max(w[1],w[2])/s}return d}},Gl=class extends P{},aC=class extends Gl{},oC=class extends Gl{},$l=class extends P{},iC=class extends $l{},lC=class extends $l{},Vl=class extends P{},cC=class extends Vl{},uC=class extends Vl{},Ul=class extends P{},dC=class extends Ul{},hC=class extends Ul{},jl=class extends P{},fC=class extends jl{},_C=class extends jl{},ql=class extends P{},pC=class extends ql{},mC=class extends ql{},Wl=class extends P{},gC=class extends Wl{},wC=class extends Wl{},Hl=class extends P{},vC=class extends Hl{},yC=class extends Hl{},Ql=class extends P{},bC=class extends Ql{},MC=class extends Ql{},Rp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}},Xl=class extends Rp{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return dp({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},xC=class extends Xl{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","input_features","past_key_values"])}},Gp=class extends P{},kC=class extends Gp{},$p=class extends P{},TC=class extends $p{},Yl=class extends P{},EC=class extends Yl{},AC=class extends Yl{},Jl=class extends P{},CC=class extends Jl{},SC=class extends Jl{async _call(e){return new ie(await super._call(e))}},Nr=class extends P{},PC=class extends Nr{},FC=class extends Nr{async _call(e){return new Jr(await super._call(e))}},LC=class extends Nr{async _call(e){return new ie(await super._call(e))}},IC=class extends Nr{async _call(e){return new He(await super._call(e))}},OC=class extends P{},NC=class extends Nr{},DC=class extends Nr{async _call(e){return new Jr(await super._call(e))}},zC=class extends Nr{async _call(e){return new ie(await super._call(e))}},Kl=class extends P{},BC=class extends Kl{},RC=class extends Kl{},Vp=class extends mr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},Zl=class extends P{},GC=class extends Zl{},$C=class extends Zl{async _call(e){return new ie(await super._call(e))}},ec=class extends P{},VC=class extends ec{},UC=class extends ec{},La=class extends P{},jC=class extends La{async forward(e){const t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=yt([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=ct([0,3,l,l],0)}const{text_embeddings:s,image_embeddings:n,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=s,i.l2norm_text_embeddings=a),r||(i.image_embeddings=n,i.l2norm_image_embeddings=o),i}},Up=class extends La{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},qC=class extends La{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},tc=class extends P{},WC=class extends tc{},HC=class extends tc{},QC=class extends mr{},rc=class extends P{},XC=class extends rc{},YC=class extends rc{},JC=class extends mr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"])}},sc=class extends P{},KC=class extends sc{},ZC=class extends sc{},jp=class extends P{},eS=class extends jp{},nc=class extends P{},tS=class extends nc{},rS=class extends nc{},ac=class extends P{},sS=class extends ac{},nS=class extends ac{},oc=class extends P{},aS=class extends oc{},oS=class extends oc{},ic=class extends P{},iS=class extends ic{},lS=class extends ic{},fn=class extends P{},cS=class extends fn{},uS=class extends fn{},dS=class extends fn{async _call(e){return new ie(await super._call(e))}},hS=class extends fn{},qp=class extends P{},fS=class extends qp{},Wp=class extends P{},_S=class extends Wp{},Hp=class extends Ye{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Qp=class extends P{},pS=class extends Qp{async _call(e){return new Hp(await super._call(e))}},Xp=class extends Ye{constructor({audio_codes:e}){super(),this.audio_codes=e}},Yp=class extends Ye{constructor({audio_values:e}){super(),this.audio_values=e}},Ia=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},mS=class extends Ia{async encode(e){return new Xp(await xe(this.sessions.encoder_model,e))}async decode(e){return new Yp(await xe(this.sessions.decoder_model,e))}},Jp=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Kp=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},lc=class extends P{},gS=class extends lc{},wS=class extends lc{},cc=class extends P{},vS=class extends cc{},yS=class extends cc{},_n=class extends P{},bS=class extends _n{},MS=class extends _n{async _call(e){return new Je(await super._call(e))}},xS=class extends _n{async _call(e){return new ie(await super._call(e))}},kS=class extends _n{async _call(e){return new ht(await super._call(e))}},uc=class extends P{},TS=class extends uc{},ES=class extends uc{},Oa=class extends P{},AS=class extends Oa{},CS=class extends Oa{async _call(e){return new ie(await super._call(e))}},SS=class extends Oa{},Na=class extends P{},PS=class extends Na{},FS=class extends Na{async _call(e){return new ie(await super._call(e))}},LS=class extends Na{},Da=class extends P{},IS=class extends Da{},OS=class extends Da{async _call(e){return new ie(await super._call(e))}},NS=class extends Da{},za=class extends P{},DS=class extends za{},zS=class extends za{async _call(e){return new ie(await super._call(e))}},BS=class extends za{},dc=class extends P{},RS=class extends dc{},GS=class extends dc{async _call(e){return new ie(await super._call(e))}},hc=class extends P{},$S=class extends hc{},VS=class extends hc{async _call(e){return new ie(await super._call(e))}},pn=class extends P{},US=class extends pn{},jS=class extends pn{async _call(e){return new Je(await super._call(e))}},qS=class extends pn{async _call(e){return new ie(await super._call(e))}},WS=class extends pn{async _call(e){return new He(await super._call(e))}},fc=class extends P{},HS=class extends fc{},QS=class extends fc{},_c=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},XS=class extends _c{},YS=class extends _c{},As=class extends P{},JS=class extends As{},KS=class extends As{async _call(e){return new Je(await super._call(e))}},ZS=class extends As{async _call(e){return new ie(await super._call(e))}},eP=class extends As{async _call(e){return new He(await super._call(e))}},tP=class extends As{async _call(e){return new ht(await super._call(e))}},pc=class extends P{},rP=class extends pc{},sP=class extends pc{},mc=class extends P{},nP=class extends mc{},aP=class extends mc{},Zp=class extends P{},oP=class extends Zp{constructor(...t){super(...t);k(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(t){const r=this._generation_mode??"text";let s;if(r==="text"||!t.past_key_values){const l=this.sessions.prepare_inputs_embeds,c=rt(t,l.inputNames);s=await xe(l,c)}else{const l=this.sessions.gen_img_embeds,c=rt({image_ids:t.input_ids},l.inputNames);s=await xe(l,c)}const n={...t,...s},a=await pr(this,n),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await xe(o,rt(a,o.inputNames));return{...s,...a,...i}}prepare_inputs_for_generation(t,r,s){const n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=ze([r.input_ids,r.input_ids],0):(r.input_ids=ze([r.input_ids,Li(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ze([r.attention_mask,Li(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=ct([0,0,3,384,384],1)),n&&(r.images_seq_mask=new U("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new U("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(t){return this._generation_mode="text",super.generate(t)}async generate_images(t){this._generation_mode="image";const r=(t.inputs??t[this.main_input_name]).dims[1],n=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await xe(a,{generated_tokens:n}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(const c of i){const d=qt.fromTensor(c);l.push(d)}return l}},gc=class extends P{},iP=class extends gc{},lP=class extends gc{},em=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(t){const[r,s]=t.dims,n=this.config.decoder.num_codebooks,a=s-n;let o=0;for(let c=0;c<t.size;++c){if(t.data[c]==this.config.decoder.pad_token_id)continue;const d=c%s,h=Math.floor(c/s)%n,_=d-h;_>0&&_<=a&&(t.data[o++]=t.data[c])}const i=Math.floor(r/n),l=o/(i*n);return new U(t.type,t.data.slice(0,o),[i,n,l])}prepare_inputs_for_generation(t,r,s){const n=BigInt(this.config.decoder.pad_token_id);let a=structuredClone(t);for(let o=0;o<a.length;++o)for(let i=0;i<a[o].length;++i)o%this.config.decoder.num_codebooks>=i&&(a[o][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(a=a.concat(a)),Ta(this,a,r)}async generate(t){const r=await super.generate(t),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await xe(this.sessions.encodec_decode,{audio_codes:s});return n}},wc=class extends P{},cP=class extends wc{},uP=class extends wc{},vc=class extends P{},dP=class extends vc{},hP=class extends vc{},Cs=class extends P{},fP=class extends Cs{},_P=class extends Cs{async _call(e){return new Je(await super._call(e))}},pP=class extends Cs{async _call(e){return new ie(await super._call(e))}},mP=class extends Cs{async _call(e){return new He(await super._call(e))}},gP=class extends Cs{async _call(e){return new ht(await super._call(e))}},tm=class extends P{},wP=class extends tm{},yc=class extends P{},vP=class extends yc{},yP=class extends yc{},bc=class extends P{},bP=class extends bc{},MP=class extends bc{},Mc=class extends P{},xP=class extends Mc{},kP=class extends Mc{},xc=class extends P{},TP=class extends xc{},EP=class extends xc{},kc=class extends P{},AP=class extends kc{},CP=class extends kc{},Tc=class extends P{},SP=class extends Tc{},PP=class extends Tc{},Ec=class extends P{},FP=class extends Ec{},LP=class extends Ec{},Ac=class extends P{},IP=class extends Ac{},OP=class extends Ac{},NP=class extends mr{},rm=class extends P{},DP=class extends rm{async _call(e){return new Jr(await super._call(e))}},Cc=class extends P{},zP=class extends Cc{},BP=class extends Cc{},Sc=class extends P{},RP=class extends Sc{},GP=class extends Sc{},Pc=class extends P{},$P=class extends Pc{},VP=class extends Pc{},Fc=class extends P{},UP=class extends Fc{},jP=class extends Fc{},sm=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},nm=class extends sm{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!a){let h;if(r&&e.dims[1]!==1){if(!s)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:h}=await xe(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}))}else{const _=this.config.normalized_config.hidden_size;h=new U("float32",[],[0,_])}({inputs_embeds:a}=await xe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:h}))}return await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:n,generation_config:i,logits_processor:l},!1)}},Lc=class extends P{},qP=class extends Lc{},WP=class extends Lc{async _call(e){return new ie(await super._call(e))}},Ic=class extends P{},HP=class extends Ic{},QP=class extends Ic{async _call(e){return new He(await super._call(e))}},Oc=class extends P{},XP=class extends Oc{},YP=class extends Oc{},Nc=class extends P{},JP=class extends Nc{},KP=class extends Nc{},Dc=class extends P{},ZP=class extends Dc{},eF=class extends Dc{},zc=class extends P{},tF=class extends zc{},rF=class extends zc{},Bc=class extends P{},sF=class extends Bc{},nF=class extends Bc{},Rc=class extends Rl{},am=class extends Bp{},aF=class extends Rc{},oF=class extends am{},Gc=class extends Rc{},om=class extends Gc{},iF=class extends Gc{},lF=class extends om{},$c=class extends P{},cF=class extends $c{},uF=class extends $c{async _call(e){return new ie(await super._call(e))}},Vc=class extends P{},dF=class extends Vc{},hF=class extends Vc{async _call(e){return new im(await super._call(e))}},im=class extends un{},Ss=class extends P{},fF=class extends Ss{},_F=class extends Ss{async _call(e){return new Je(await super._call(e))}},pF=class extends Ss{async _call(e){return new ie(await super._call(e))}},mF=class extends Ss{async _call(e){return new He(await super._call(e))}},gF=class extends Ss{async _call(e){return new ht(await super._call(e))}},Ps=class extends P{},wF=class extends Ps{},vF=class extends Ps{async _call(e){return new Je(await super._call(e))}},yF=class extends Ps{async _call(e){return new ie(await super._call(e))}},bF=class extends Ps{async _call(e){return new He(await super._call(e))}},MF=class extends Ps{async _call(e){return new ht(await super._call(e))}},Uc=class extends P{},xF=class extends Uc{},kF=class extends Uc{async _call(e){return new lm(await super._call(e))}},lm=class extends un{},cm=class extends Ye{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},um=class extends P{},TF=class extends um{async get_image_embeddings({pixel_values:e}){return await Or(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??(e.input_labels=yt(e.input_points.dims.slice(0,-1)));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await xe(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new cm(await super._call(e))}},dm=class extends Ye{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},hm=class extends P{},jc=class extends hm{async get_image_embeddings({pixel_values:e}){return await Or(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const a=e.input_points.dims;e.input_labels??(e.input_labels=yt(a.slice(0,-1))),e.input_boxes??(e.input_boxes=ct([a[0],0,4],0))}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=ct([a[0],a[1],0],-1n),e.input_points=ct([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const s=this.sessions.prompt_encoder_mask_decoder,n=rt(e,s.inputNames);return await xe(s,n)}async _call(e){return new dm(await super._call(e))}},EF=class extends jc{},AF=class extends jc{},Ba=class extends P{},CF=class extends Ba{},SF=class extends Ba{},PF=class extends Ba{},Ra=class extends P{},FF=class extends Ra{},LF=class extends Ra{},IF=class extends Ra{},qc=class extends P{},OF=class extends qc{},fm=class extends qc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},NF=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Wc=class extends P{},DF=class extends Wc{},zF=class extends Wc{},BF=class extends Vp{},Ga=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},RF=class extends Ga{async encode(e){return await xe(this.sessions.encoder_model,e)}async decode(e){return await xe(this.sessions.decoder_model,e)}},_m=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},pm=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Hc=class extends P{},GF=class extends Hc{},$F=class extends Hc{},$a=class extends P{},VF=class extends $a{},UF=class extends $a{},jF=class extends $a{async generate_speech(e,t,{threshold:r=.5,minlenratio:s=0,maxlenratio:n=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Or(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),h=Math.floor(c*s),_=this.config.num_mel_bins;let p=[],w=null,v=null,y=0;for(;;){++y;const A=ap(!!v);let C;v?C=v.output_sequence_out:C=new U("float32",new Float32Array(_),[1,1,_]);let S={use_cache_branch:A,output_sequence:C,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};tl(this,S,w),v=await xe(this.sessions.decoder_model_merged,S),w=el(v,w);const{prob:N,spectrum:x}=v;if(p.push(x),y>=h&&(Array.from(N.data).filter(R=>R>=r).length>0||y>=d))break}const M=ze(p),{waveform:T}=await xe(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:T}}},qF=class extends P{constructor(){super(...arguments);k(this,"main_input_name","spectrogram")}},mn=class extends P{},WF=class extends mn{},HF=class extends mn{async _call(e){return new Je(await super._call(e))}},QF=class extends mn{async _call(e){return new ie(await super._call(e))}},XF=class extends mn{async _call(e){return new ht(await super._call(e))}},Qc=class extends P{},YF=class extends Qc{},JF=class extends Qc{},Xc=class extends P{},KF=class extends Xc{},ZF=class extends Xc{},mm=class extends P{},eL=class extends mm{},gm=class extends P{},wm=class extends gm{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:s=5,speed:n=1.05}){const{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:c,durations:d}=await xe(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),h=d.div(n).mul_(a),_=i*o,p=h.data,w=Int32Array.from(p,z=>Math.ceil(z/_)),v=Math.max(...w),y=e.dims[0],M=new BigInt64Array(y*v);for(let z=0;z<y;++z)M.fill(1n,z*v,z*v+w[z]);const T=new U("int64",M,[y,v]),A=l*o,C=A*v;let S=Sx([y,A,v]);const N=S.data;for(let z=0;z<y;++z)if(w[z]!==v)for(let $=0;$<A;++$)N.fill(0,z*C+$*v+w[z],z*C+($+1)*v);const x=ct([y],s);for(let z=0;z<s;++z){const $=ct([y],z);({denoised_latents:S}=await xe(this.sessions.latent_denoiser,{style:r,noisy_latents:S,latent_mask:T,encoder_outputs:c,attention_mask:t,timestep:$,num_inference_steps:x}))}const{waveform:R}=await xe(this.sessions.voice_decoder,{latents:S});return{waveform:R,durations:h}}},Va=class extends P{},tL=class extends Va{},rL=class extends Va{async _call(e){return new ie(await super._call(e))}},sL=class extends Va{},Yc=class extends P{},nL=class extends Yc{},aL=class extends Yc{},Jc=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}},oL=class extends Jc{},iL=class extends Jc{},Kc=class extends P{},lL=class extends Kc{},cL=class extends Kc{async _call(e){return new vm(await super._call(e))}},vm=class extends xl{},ym=class extends P{},uL=class extends ym{},Ua=class extends P{},dL=class extends Ua{},hL=class extends Ua{async _call(e){return new Jr(await super._call(e))}},fL=class extends Ua{async _call(e){return new ie(await super._call(e))}},gn=class extends P{},_L=class extends gn{},pL=class extends gn{async _call(e){return new Jr(await super._call(e))}},mL=class extends gn{async _call(e){return new ie(await super._call(e))}},gL=class extends gn{async _call(e){return new He(await super._call(e))}},Zc=class extends P{},wL=class extends Zc{},vL=class extends Zc{},yL=class extends P{constructor(){super(...arguments);k(this,"main_input_name","pixel_values");k(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}},eu=class extends P{},bL=class extends eu{},ML=class extends eu{async _call(e){return new ie(await super._call(e))}},bm=class extends P{},xL=class extends bm{},tu=class extends P{},kL=class extends tu{},TL=class extends tu{async _call(e){return new ie(await super._call(e))}},Mm=class extends P{},EL=class extends Mm{async _call(e){return new ZT(await super._call(e))}},xm=class extends P{},AL=class extends xm{},km=class extends Ye{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Tm=class extends P{},CL=class extends Tm{async _call(e){return new km(await super._call(e))}},SL=class extends Xl{},Em=2,PL=1,ru=new WeakMap;function FL(e,t){var w,v,y;const{text_config:r,audio_config:s}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=s,i=a+o,l=new Ji,c=((w=n==null?void 0:n.config)==null?void 0:w.kv_cache_dtype)??"float32",d=c==="float16"?fs.float16:fs.float32,h=ba(s,{batch_size:1});for(const M in h){const T=h[M].reduce((A,C)=>A*C,1);l[M]=new U(c,new d(T),h[M])}const _=new U(c,new d(i*Em),[1,i,Em]),p=((v=t[Symbol.asyncIterator])==null?void 0:v.call(t))??((y=t[Symbol.iterator])==null?void 0:y.call(t));if(!p)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:_,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:r.hidden_size}}async function LL(e,t){const r=t.dims[2],s=Math.floor((PL+r-3)/2)+1,n=new U("int64",BigInt64Array.from({length:s},(d,h)=>BigInt(e.enc_past_seq_len+h)),[1,s]),a=e.enc_past_seq_len+s,o=yt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await xe(e.encoder_session,{input_features:t,attention_mask:o,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=l;for(const d in c)if(d.startsWith("present.")){const h=d.replace("present","past_key_values"),_=e.enc_kv_cache[h];(_==null?void 0:_.location)==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[h]=c[d]}return e.enc_past_seq_len=a,i}async function IL(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){const r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}const s=await LL(e,r.value);e.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),e.audio_embed_total_tokens+=s.dims[1]}}function OL(e,t,r){if(e.audio_embed_queue.length===0)return;const s=t.data;let n=0,a=r;for(;a>0&&e.audio_embed_queue.length>0;){const o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)s[n*e.text_hidden_size+d]+=o.data[c+d];n+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}var NL=class extends Ma{constructor(e){super(),this._s=e}_call(e){const t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},Am=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values"])}},Cm=class extends Am{async forward({input_ids:e,past_key_values:t,...r}){const s=e.dims[1],n=ru.get(this);n&&await IL(n,n.audio_consumed+s);const{inputs_embeds:a}=await xe(this.sessions.embed_tokens,{input_ids:e});n&&OL(n,a,s);const o={inputs_embeds:a,...r};tl(this,o,t);const i=this.sessions.decoder_model_merged,l=rt(o,i.inputNames);return await xe(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const s=FL(this,e);ru.set(this,s);const n=new tp;n.push(new NL(s)),t&&n.extend(t);try{return await super.generate({...r,stopping_criteria:n})}finally{s.enc_kv_cache.dispose(),ru.delete(this)}}},ja=class extends P{},DL=class extends ja{},zL=class extends ja{async _call(e){return new Jr(await super._call(e))}},BL=class extends ja{async _call(e){return new ie(await super._call(e))}},Sm=class extends Ye{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Fs=class extends P{},RL=class extends Fs{},GL=class extends Fs{async _call(e){return new Jr(await super._call(e))}},$L=class extends Fs{async _call(e){return new ie(await super._call(e))}},VL=class extends Fs{async _call(e){return new Sm(await super._call(e))}},UL=class extends Fs{async _call(e){return new He(await super._call(e))}},Pm=class extends P{},jL=class extends Pm{},qL=class extends ep{constructor(){super(...arguments);k(this,"return_timestamps",null);k(this,"return_token_timestamps",null);k(this,"num_frames",null);k(this,"alignment_heads",null);k(this,"task",null);k(this,"language",null);k(this,"no_timestamps_token_id",null);k(this,"prompt_ids",null);k(this,"is_multilingual",null);k(this,"lang_to_id",null);k(this,"task_to_id",null);k(this,"max_initial_timestamp_index",1)}},su=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}},WL=class extends su{},Fm=class extends su{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,qL)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const s=e.task;if(e.is_multilingual){r||(ue.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${k1(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[s??"transcribe"])}else if(r||s)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(ue.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,...n}){t=this._prepare_generation_config(t,n);const a=n.decoder_input_ids instanceof U?Ii(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new Yi),r.push(new nE(t,a))),t.begin_suppress_tokens&&(r??(r=new Yi),r.push(new Z_(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&ue.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:n});const o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...n});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:s,kwargs:n}){const a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,i=t.return_token_timestamps,l=e,c=l.dims[2],d=2,h=this.config.max_source_positions,_=d*h;let p=0;const w=[],v=[];for(;p<c;){const M=Math.min(p+_,c),T=l.slice(null,null,[p,M]);let A;const C=T.dims[2];if(C<_){const W=l.dims[1],ee=new Float32Array(W*_),G=T.data;for(let L=0;L<W;++L)ee.set(G.subarray(L*C,(L+1)*C),L*_);A=new U("float32",ee,[1,W,_])}else A=T;if(r)for(const W of r)"begin_index"in W&&(W.begin_index=s.length);const S=await super.generate({inputs:A,generation_config:t,logits_processor:r,decoder_input_ids:s,...n}),x=(i?S.sequences:S)[0].tolist().map(Number).slice(s.length);let R;if(i){S.token_timestamps=this._extract_token_timestamps(S,t.alignment_heads,Math.floor((M-p)/d),.02,s.length);const W=p/d*.02;R=S.token_timestamps[0].tolist().slice(s.length).map(ee=>ee+W)}if(x.length>0&&x.at(-1)===o&&x.pop(),x.length===0)break;const z=x.map(W=>W>=a),$=x.length>=2&&z[x.length-1]&&!z[x.length-2],Q=[];for(let W=0;W<x.length-1;++W)z[W]&&z[W+1]&&Q.push(W+1);let H,D=x.length;if(Q.length>0)if($)H=M-p;else{const W=Q.at(-1);H=(x[W-1]-a)*d,D=W}else H=M-p;const I=Math.floor(p/d),te=a+1500;for(let W=0;W<D;++W)x[W]>=a&&(x[W]=Math.min(x[W]+I,te));w.push(...x.slice(0,D)),R&&v.push(...R.slice(0,D)),p+=H}w.push(o);const y=[...s,...w];if(i){const M=new U("int64",y.map(BigInt),[1,y.length]),T=[...new Array(s.length).fill(0),...v,0],A=new U("float32",new Float32Array(T),[1,T.length]);return{sequences:M,token_timestamps:A}}return new U("int64",y.map(BigInt),[1,y.length])}_extract_token_timestamps(e,t,r=null,s=.02,n=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&ue.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&&(ue.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(y,M)=>ze(o.map(T=>T[M]),2)),l=dr(t.map(([y,M])=>{if(y>=i.length)throw new Error(`Layer index ${y} is out of bounds for cross attentions (length ${i.length}).`);return r?i[y].slice(null,M,null,[0,r]):i[y].slice(null,M)})).transpose(1,0,2,3),[c,d]=Cx(l,-2,0,!0),h=l.clone();for(let y=0;y<h.dims[0];++y){const M=h[y];for(let T=0;T<M.dims[0];++T){const A=M[T],C=c[y][T][0].data,S=d[y][T][0].data;for(let N=0;N<A.dims[0];++N){let x=A[N].data;for(let R=0;R<x.length;++R)x[R]=(x[R]-S[R])/C[R];x.set(ux(x,a))}}}const _=n>0?h.slice(null,null,[n,h.dims[2]],null):h,p=[Si(_,1)],w=e.sequences.dims,v=new U("float32",new Float32Array(w[0]*w[1]),w);for(let y=0;y<w[0];++y){const M=p[y].neg().squeeze_(0),[T,A]=hx(M.tolist()),C=Array.from({length:T.length-1},(R,z)=>T[z+1]-T[z]),S=Jt([1],C).map(R=>!!R),N=[];for(let R=0;R<S.length;++R)S[R]&&N.push(A[R]*s);const x=new Array(n).fill(0);x.push(...N),N.length>0&&x.push(N.at(-1)),v[y].data.set(x)}return v}},HL=class extends Fm{},Ls=class extends P{},QL=class extends Ls{},XL=class extends Ls{async _call(e){return new Je(await super._call(e))}},YL=class extends Ls{async _call(e){return new ie(await super._call(e))}},JL=class extends Ls{async _call(e){return new He(await super._call(e))}},KL=class extends Ls{async _call(e){return new ht(await super._call(e))}},Is=class extends P{},ZL=class extends Is{},eI=class extends Is{async _call(e){return new Je(await super._call(e))}},tI=class extends Is{async _call(e){return new ie(await super._call(e))}},rI=class extends Is{async _call(e){return new He(await super._call(e))}},sI=class extends Is{async _call(e){return new ht(await super._call(e))}},nu=class extends P{},nI=class extends nu{},aI=class extends nu{async _call(e){return new Lm(await super._call(e))}},Lm=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},au=class extends P{},oI=class extends au{},iI=class extends au{},lI=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"]]),cI=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"]]),uI=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),dI=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"]]),Im=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Om=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Nm=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Dm=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"]]),zm=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"]]),Bm=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Rm=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"]]),hI=new Map([["multi_modality","MultiModalityCausalLM"]]),Gm=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"]]),$m=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"]]),Vm=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Um=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"]]),jm=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),fI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),qm=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"]]),Wm=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Hm=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Os=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Qm=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Xm=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Ym=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Jm=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Km=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Zm=new Map([["wavlm","WavLMForXVector"]]),eg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),tg=new Map([["vitmatte","VitMatteForImageMatting"]]),_I=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),rg=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),sg=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),ng=new Map([["sapiens","SapiensForNormalEstimation"]]),ag=new Map([["vitpose","VitPoseForPoseEstimation"]]),og=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),ig=[[lI,q.EncoderOnly],[cI,q.EncoderDecoder],[dI,q.DecoderOnlyWithoutHead],[uI,q.AutoEncoder],[Dm,q.EncoderOnly],[zm,q.EncoderOnly],[Bm,q.Seq2Seq],[Im,q.Seq2Seq],[Rm,q.DecoderOnly],[hI,q.MultiModality],[Gm,q.EncoderOnly],[$m,q.EncoderOnly],[Vm,q.Vision2Seq],[Um,q.ImageTextToText],[jm,q.AudioTextToText],[qm,q.EncoderOnly],[Os,q.EncoderOnly],[Xm,q.EncoderOnly],[Qm,q.EncoderOnly],[tg,q.EncoderOnly],[_I,q.EncoderOnly],[rg,q.EncoderOnly],[sg,q.EncoderOnly],[ng,q.EncoderOnly],[ag,q.EncoderOnly],[Wm,q.EncoderOnly],[Hm,q.EncoderOnly],[Ym,q.MaskGeneration],[Jm,q.EncoderOnly],[Km,q.EncoderOnly],[Om,q.Seq2Seq],[Nm,q.EncoderOnly],[Zm,q.EncoderOnly],[eg,q.EncoderOnly],[og,q.EncoderOnly]];for(const[e,t]of ig)for(const r of e.values()){_r.set(r,t);const s=sl[r];vs.set(s,r),Zi.set(r,s)}var pI=[["MusicgenForConditionalGeneration",em,q.Musicgen],["Phi3VForCausalLM",nm,q.Phi3V],["CLIPTextModelWithProjection",vp,q.EncoderOnly],["SiglipTextModel",fm,q.EncoderOnly],["JinaCLIPTextModel",Up,q.EncoderOnly],["ClapTextModelWithProjection",gp,q.EncoderOnly],["ClapAudioModelWithProjection",wp,q.EncoderOnly],["DacEncoderModel",Mp,q.EncoderOnly],["DacDecoderModel",xp,q.EncoderOnly],["MimiEncoderModel",Jp,q.EncoderOnly],["MimiDecoderModel",Kp,q.EncoderOnly],["SnacEncoderModel",_m,q.EncoderOnly],["SnacDecoderModel",pm,q.EncoderOnly],["Gemma3nForConditionalGeneration",Fa,q.ImageAudioTextToText],["Gemma4ForConditionalGeneration",Nl,q.ImageAudioTextToText],["SupertonicForConditionalGeneration",wm,q.Supertonic],["ChatterboxModel",_p,q.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Cm,q.VoxtralRealtime]];for(const[e,t,r]of pI)_r.set(e,r),vs.set(t,e),Zi.set(e,t);var lg=new Map([["modnet",Os],["birefnet",Os],["isnet",Os],["ben",Os]]);for(const[e,t]of lg.entries())t.set(e,"PreTrainedModel"),_r.set(e,q.EncoderOnly),Zi.set(e,P);var mI=new Set(lg.keys());_r.set("PreTrainedModel",q.EncoderOnly),vs.set(P,"PreTrainedModel");var Ae={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Dm,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:zm,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Om,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Nm,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Gm,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:$m,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:qm,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Os,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Qm,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Xm,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Wm,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Hm,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Ym,MODEL_FOR_CTC_MAPPING_NAMES:Jm,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Km,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Zm,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:eg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:fI,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:tg,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:rg,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:sg,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:ng,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:ag,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:og,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Um,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:jm,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Bm,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Im,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Rm,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Vm};yE(Ae);var Ce=(oo=class{static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(const t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:h={}}={}){const _={progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h};if(_.config=await on.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const{model_type:p}=_.config;for(const w of this.MODEL_CLASS_MAPPINGS){let v=w.get(p);if(!v){for(const y of w.values())if(y[0]===p){v=y;break}if(!v)continue}return await sl[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return mI.has(p)||ue.warn(`Unknown model class "${p}", attempting to construct from base class.`),await P.from_pretrained(e,_);throw Error(`Unsupported model type: ${p}`)}},k(oo,"MODEL_CLASS_MAPPINGS",null),k(oo,"BASE_IF_FAIL",!1),oo),wn=(io=class extends Ce{},k(io,"MODEL_CLASS_MAPPINGS",ig.map(e=>e[0])),k(io,"BASE_IF_FAIL",!0),io),cg=(_u=class extends Ce{},k(_u,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),_u),gI=(pu=class extends Ce{},k(pu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),pu),ou=(mu=class extends Ce{},k(mu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),mu),wI=(gu=class extends Ce{},k(gu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),gu),vI=(wu=class extends Ce{},k(wu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),wu),yI=(vu=class extends Ce{},k(vu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),vu),bI=(yu=class extends Ce{},k(yu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),yu),MI=(bu=class extends Ce{},k(bu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),bu),xI=(Mu=class extends Ce{},k(Mu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),Mu),kI=(xu=class extends Ce{},k(xu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),xu),TI=(ku=class extends Ce{},k(ku,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),ku),ug=(Tu=class extends Ce{},k(Tu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),Tu),dg=(Eu=class extends Ce{},k(Eu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),Eu),hg=(Au=class extends Ce{},k(Au,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),Au),EI=(Cu=class extends Ce{},k(Cu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),Cu),AI=(Su=class extends Ce{},k(Su,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),Su);Pu=class extends Ce{},k(Pu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);var CI=(Fu=class extends Ce{},k(Fu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CTC_MAPPING_NAMES]),Fu),SI=(Lu=class extends Ce{},k(Lu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),Lu);Iu=class extends Ce{},k(Iu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]),Ou=class extends Ce{},k(Ou,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);var PI=(Nu=class extends Ce{},k(Nu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),Nu);Du=class extends Ce{},k(Du,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);var FI=(zu=class extends Ce{},k(zu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),zu),LI=(Bu=class extends Ce{},k(Bu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),Bu);Ru=class extends Ce{},k(Ru,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]),Gu=class extends Ce{},k(Gu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]);var II=($u=class extends Ce{},k($u,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),$u);Vu=class extends Ce{},k(Vu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]),Uu=class extends Ce{},k(Uu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]);async function Ht(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>qt.read(t)))}async function Ns(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?I1(r,t):r instanceof Float64Array?new Float32Array(r):r))}function iu(e,t){t&&(e=e.map(o=>o|0));const[r,s,n,a]=e;return{xmin:r,ymin:s,xmax:n,ymax:a}}var Ve=class extends vt{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}},OI=class extends Ve{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),{problem_type:n,id2label:a}=this.model.config,o=n==="multi_label_classification"?l=>l.sigmoid():l=>new U("float32",nt(l.data),l.dims),i=[];for(const l of s.logits){const c=o(l),d=await _s(c,t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:a?a[w]:`LABEL_${w}`,score:h[v]}));t===1?i.push(...p):i.push(p)}return Array.isArray(e)||t===1?i:i[0]}},NI=class extends Ve{async _call(e,{ignore_labels:t=["O"]}={}){const r=Array.isArray(e),s=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(s)).logits,o=this.model.config.id2label,i=[];for(let l=0;l<a.dims[0];++l){const c=s.input_ids[l],d=a[l],h=[];for(let _=0;_<d.dims[0];++_){const p=d[_],w=je(p.data)[1],v=o?o[w]:`LABEL_${w}`;if(t.includes(v))continue;const y=this.tokenizer.decode([c[_].item()],{skip_special_tokens:!0});if(y==="")continue;const M=nt(p.data);h.push({entity:v,score:M[w],index:_,word:y})}i.push(h)}return r?i:i[0]}},DI=class extends Ve{async _call(e,t,{top_k:r=1}={}){const s=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),n=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(s),i=s.input_ids.tolist(),l=s.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,h=[];for(let _=0;_<a.dims[0];++_){const p=i[_],w=p.findIndex(S=>S==d),v=a[_].tolist(),y=o[_].tolist();for(let S=1;S<v.length;++S)(l[_]==0||S<=w||c.findIndex(N=>N==p[S])!==-1)&&(v[S]=-1/0,y[S]=-1/0);const M=nt(v).map((S,N)=>[S,N]),T=nt(y).map((S,N)=>[S,N]);M[0][0]=0,T[0][0]=0;const A=Ny(M,T).filter(S=>S[0][1]<=S[1][1]).map(S=>[S[0][1],S[1][1],S[0][0]*S[1][0]]).sort((S,N)=>N[2]-S[2]),C=[];for(let S=0;S<Math.min(A.length,r);++S){const[N,x,R]=A[S],z=p.slice(N,x+1),$=this.tokenizer.decode(z,{skip_special_tokens:!0});C.push({answer:$,score:R})}r===1?h.push(...C):h.push(C)}return n?h:h[0]}},zI=class extends Ve{async _call(e,{top_k:t=5}={}){const{mask_token_id:r,mask_token:s}=this.tokenizer,n=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(n),o=[],i=n.input_ids.tolist();for(let l=0;l<i.length;++l){const c=i[l],d=c.findIndex(v=>v==r);if(d===-1)throw Error(`Mask token (${s}) not found in text.`);const h=a[l][d],_=await _s(new U("float32",nt(h.data),h.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((v,y)=>{const M=c.slice();return M[d]=v,{score:p[y],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},lu=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256});k(this,"_key","generated_text")}async _call(t,r={}){Array.isArray(t)||(t=[t]),this.model.config.prefix&&(t=t.map(l=>this.model.config.prefix+l));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(t=t.map(l=>s[this.task].prefix+l));const n=this.tokenizer,a={padding:!0,truncation:!0};let o;this.task==="translation"&&"_build_translation_inputs"in n?o=n._build_translation_inputs(t,a,r):o=n(t,a);const i=await this.model.generate({...o,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}},BI=class extends lu{constructor(){super(...arguments);k(this,"_key","summary_text")}},RI=class extends lu{constructor(){super(...arguments);k(this,"_key","translation_text")}};function fg(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var GI=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r={}){let s=!1,n=!1,a=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,o=r.tokenizer_encode_kwargs,i;if(typeof t=="string")i=t=[t];else if(Array.isArray(t)&&t.every(w=>typeof w=="string"))s=!0,i=t;else{if(fg(t))t=[t];else if(Array.isArray(t)&&t.every(fg))s=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,i=t.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:!1,add_generation_prompt:!0,...o})),a=!1,o=void 0}const l=n?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";const c=this.tokenizer(i,{add_special_tokens:a,padding:!0,truncation:!0,...o}),d=await this.model.generate({...c,...this._default_generation_config,...r}),h=this.tokenizer.batch_decode(d,{skip_special_tokens:!0});let _;!l&&c.input_ids.dims.at(-1)>0&&(_=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(w=>w.length));const p=Array.from({length:t.length},w=>[]);for(let w=0;w<h.length;++w){const v=Math.floor(w/d.dims[0]*t.length);_&&(h[w]=h[w].slice(_[v])),p[v].push({generated_text:n?[...t[v],{role:"assistant",content:h[w]}]:h[w]})}return!s&&p.length===1?p[0]:p}},$I=class extends Ve{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ue.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&&(ue.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:s=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>r.replace("{}",l)),o=s||t.length===1,i=[];for(const l of e){const c=[];for(const _ of a){const p=this.tokenizer(l,{text_pair:_,padding:!0,truncation:!0}),w=await this.model(p);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id])}const h=(o?c.map(_=>nt(_)[1]):nt(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:h.map(_=>t[_[1]]),scores:h.map(_=>_[0])})}return n?i:i[0]}},VI=class extends Ve{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await Ns(e,r),n=this.model.config.id2label,a=[];for(const o of s){const i=await this.processor(o),c=(await this.model(i)).logits[0],d=await _s(new U("float32",nt(c.data),c.dims),t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:n?n[w]:`LABEL_${w}`,score:h[v]}));a.push(p)}return Array.isArray(e)?a:a[0]}},UI=class extends Ve{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const n=t.map(c=>r.replace("{}",c)),a=this.tokenizer(n,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await Ns(e,o),l=[];for(const c of i){const d=await this.processor(c),h=await this.model({...a,...d}),_=nt(h.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})))}return s?l[0]:l}},jI=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{})}async _call(t,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(t,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(t,r);case"moonshine":return this._call_moonshine(t,r);case"cohere_asr":return this._call_cohere_asr(t,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(t,r){r.language&&ue.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ue.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Ns(n,a),i=[];for(const l of o){const c=await this.processor(l),h=(await this.model(c)).logits[0],_=[];for(const w of h)_.push(je(w.data)[1]);const p=this.tokenizer.decode(_,{skip_special_tokens:!0}).trim();i.push({text:p})}return s?i[0]:i}async _call_whisper(t,r){const s=r.return_timestamps??!1,n=r.chunk_length_s??0,a=r.force_full_sequences??!1;let o=r.stride_length_s??null;const i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);const l=!Array.isArray(t),c=l?[t]:t,d=this.processor.feature_extractor.config,h=d.chunk_length/this.model.config.max_source_positions,_=d.hop_length,p=d.sampling_rate,w=await Ns(c,p),v=[];for(const y of w){let M=[];if(n>0){if(o===null)o=n/6;else if(n<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const C=p*n,S=p*o,N=C-2*S;let x=0;for(;;){const R=x+C,z=y.subarray(x,R),$=await this.processor(z),Q=x===0,H=R>=y.length;if(M.push({stride:[z.length,Q?0:S,H?0:S],input_features:$.input_features,is_last:H}),H)break;x+=N}}else M=[{stride:[y.length,0,0],input_features:(await this.processor(y)).input_features,is_last:!0}];for(const C of M){i.num_frames=Math.floor(C.stride[0]/_);const S=await this.model.generate({inputs:C.input_features,...i});if(s==="word"){const N=S.sequences.tolist()[0],x=S.token_timestamps.tolist()[0],R=this.tokenizer.timestamp_begin,z=Math.max(N.findIndex($=>Number($)>=R),0);C.tokens=N.slice(z),C.token_timestamps=x.slice(z).map($=>sn($,2))}else C.tokens=S[0].tolist();C.stride=C.stride.map(N=>N/p)}const[T,A]=this.tokenizer._decode_asr(M,{time_precision:h,return_timestamps:s,force_full_sequences:a});v.push({text:T,...A})}return l?v[0]:v}async _call_moonshine(t,r){const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Ns(n,a),i=[];for(const l of o){const c=await this.processor(l),d=Math.floor(l.length/a)*6,h=await this.model.generate({max_new_tokens:d,...r,...c}),_=this.processor.batch_decode(h,{skip_special_tokens:!0})[0];i.push({text:_})}return s?i[0]:i}async _call_cohere_asr(t,r){const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor,o=a.config.sampling_rate,i=await Ns(n,o),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),d=[];for(const h of i){const _=a.split_audio(h),p=[];for(const v of _){const y=await this.processor(v),M=await this.model.generate({...y,decoder_input_ids:c,...r}),T=this.tokenizer.decode(M[0].tolist(),{skip_special_tokens:!0}).trim();p.push(T)}const w=this.processor.constructor.join_chunks(p,l);d.push({text:w})}return s?d[0]:d}},qI=class extends Ve{constructor(t){super(t);k(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=t.vocoder??null}async _prepare_speaker_embeddings(t,r){if((typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await be.fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new U("float32",t,[t.length]);else if(!(t instanceof U))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(t.dims[0]===1)t=t.repeat(r,1);else if(t.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${t.dims[0]}.`)}return t}_postprocess_waveform(t,r,s,n=null){const a=r.data,[o,i]=r.dims,l=n?n.data:null,c=[];for(let d=0;d<o;++d){const h=l?Math.min(Math.ceil(l[d]),i):i,_=d*i;c.push(new U1(a.slice(_,_+h),s))}return Array.isArray(t)?c:c[0]}async _call(t,r){return this.processor?this._call_text_to_spectrogram(t,r):this.model.config.model_type==="supertonic"?this._call_supertonic(t,r):this._call_text_to_waveform(t)}async _call_supertonic(t,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:a,style_dim:o}=this.model.config,i=this.tokenizer(t,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,o);const{waveform:c,durations:d}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(t,c,a,d)}async _call_text_to_waveform(t){const r=this.tokenizer(t,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(t,s,n)}async _call_text_to_spectrogram(t,{speaker_embeddings:r}){this.vocoder||(ue.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await wn.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:s}=this.tokenizer(t,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);const{waveform:a}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(t,a,o)}},WI=class extends Ve{async _call(e,t={}){const r=Array.isArray(e),s=await Ht(e),{pixel_values:n}=await this.processor(s),a=[];for(const o of n){o.dims=[1,...o.dims];const i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(l)}return r?a:a[0]}},HI=class extends Ve{async _call(e,{top_k:t=5}={}){const r=await Ht(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s}),{id2label:a}=this.model.config,o=[];for(const i of n.logits){const l=await _s(new U("float32",nt(i.data),i.dims),t),c=l[0].tolist(),h=l[1].tolist().map((_,p)=>({label:a?a[_]:`LABEL_${_}`,score:c[p]}));o.push(h)}return Array.isArray(e)?o:o[0]}},_g={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},pg=class extends Ve{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:n=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const l=await Ht(e),c=l.map(M=>[M.height,M.width]),d=await this.processor(l),{inputNames:h,outputNames:_}=this.model.sessions.model;if(!h.includes("pixel_values")){if(h.length!==1)throw Error(`Expected a single input name, but got ${h.length} inputs: ${h}.`);const M=h[0];if(M in d)throw Error(`Input name ${M} already exists in the inputs.`);d[M]=d.pixel_values}const p=await this.model(d);let w=null;if(o!==null)w=_g[o];else if(this.processor.image_processor){for(const[M,T]of Object.entries(_g))if(T in this.processor.image_processor){w=this.processor.image_processor[T].bind(this.processor.image_processor),o=M;break}}const v=this.model.config.id2label,y=[];if(o)if(o==="panoptic"||o==="instance"){const M=w(p,t,r,s,n,a??c)[0],T=M.segmentation;for(const A of M.segments_info){const C=new Uint8ClampedArray(T.data.length);for(let N=0;N<T.data.length;++N)T.data[N]===A.id&&(C[N]=255);const S=new qt(C,T.dims[1],T.dims[0],1);y.push({score:A.score,label:v[A.label_id],mask:S})}}else if(o==="semantic"){const{segmentation:M,labels:T}=w(p,a??c)[0];for(const A of T){const C=new Uint8ClampedArray(M.data.length);for(let N=0;N<M.data.length;++N)M.data[N]===A&&(C[N]=255);const S=new qt(C,M.dims[1],M.dims[0],1);y.push({score:null,label:v[A],mask:S})}}else throw Error(`Subtask ${o} not supported.`);else{const T=p[_[0]];for(let A=0;A<c.length;++A){const C=c[A],S=T[A];S.data.some(x=>x<-1e-5||x>1+1e-5)&&S.sigmoid_();const N=await qt.fromTensor(S.mul_(255).to("uint8")).resize(C[1],C[0]);y.push({label:null,score:null,mask:N})}}return y}},QI=class extends pg{async _call(e,t={}){const r=await Ht(e),s=await super._call(e,t),n=r.map((a,o)=>{const i=a.clone();return i.putAlpha(s[o].mask),i});return Array.isArray(e)?n:n[0]}},XI=class extends Ve{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const s=Array.isArray(e),n=await Ht(e),a=t.map(h=>r.replace("{}",h)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(n),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>nt(h.data),d=[];for(const h of l.logits_per_image){const p=[...c(h)].map((w,v)=>({score:w,label:t[v]}));p.sort((w,v)=>v.score-w.score),d.push(p)}return s?d:d[0]}},YI=class extends Ve{async _call(e,{threshold:t=.9,percentage:r=!1}={}){const s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await Ht(e),a=r?null:n.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(n),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=c.map(_=>_.boxes.map((p,w)=>({score:_.scores[w],label:d[_.classes[w]],box:iu(p,!r)})));return s?h:h[0]}},JI=class extends Ve{async _call(e,t,{threshold:r=.1,top_k:s=null,percentage:n=!1}={}){const a=Array.isArray(e),o=await Ht(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){const h=o[d],_=n?null:[[h.height,h.width]],p=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:p});let v;if("post_process_grounded_object_detection"in this.processor){const y=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];v=y.boxes.map((M,T)=>({score:y.scores[T],label:y.labels[T],box:iu(M,!n)}))}else{const y=this.processor.image_processor.post_process_object_detection(w,r,_,!0)[0];v=y.boxes.map((M,T)=>({score:y.scores[T],label:t[y.classes[T]],box:iu(M,!n)}))}v.sort((y,M)=>M.score-y.score),s!==null&&(v=v.slice(0,s)),c.push(v)}return a?c:c[0]}},KI=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r,s={}){if(Array.isArray(t)){if(t.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");t=t[0]}const n=(await Ht(t))[0],{pixel_values:a}=await this.processor(n),o=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:a,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),d=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/);let h=null;return d&&d.length>=2&&(h=d[1].trim()),[{answer:h}]}},ZI=class extends Ve{async _call(e){const t=await Ht(e),r=await this.processor(t),s=await this.model(r),n=[];for(const a of s.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(qt.fromTensor(o))}return Array.isArray(e)?n:n[0]}},eO=class extends Ve{async _call(e){const t=await Ht(e),r=await this.processor(t),{predicted_depth:s}=await this.model(r),n=[];for(let a=0;a<t.length;++a){const o=s[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,h=(await jt(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=h.min().item(),p=h.max().item(),w=h.sub(_).div_(p-_).mul_(255).to("uint8").unsqueeze(0),v=qt.fromTensor(w);n.push({predicted_depth:h,depth:v})}return Array.isArray(e)?n:n[0]}},tO=class extends Ve{async _call(e,{pooling:t="none",normalize:r=!1,quantize:s=!1,precision:n="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=Ax(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),s&&(i=Px(i,n)),i}},rO=class extends Ve{async _call(e,{pool:t=null}={}){const r=await Ht(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s});let a;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=n.pooler_output}else a=n.last_hidden_state??n.logits??n.image_embeds;return a}},qa=Object.freeze({"text-classification":{pipeline:OI,model:cg,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:NI,model:gI,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:DI,model:xI,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:zI,model:MI,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:BI,model:ou,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:RI,model:ou,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:lu,model:ou,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:GI,model:bI,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:$I,model:cg,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:VI,model:SI,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:UI,model:wn,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:jI,model:[wI,CI],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:qI,model:[yI,vI],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:WI,model:kI,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:HI,model:TI,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:pg,model:[ug,dg,hg],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:QI,model:[ug,dg,hg],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:XI,model:wn,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:YI,model:EI,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:JI,model:AI,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:KI,model:PI,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ZI,model:FI,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:eO,model:LI,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:tO,model:wn,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:rO,model:[II,wn],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),mg=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function sO(e){if(!e)throw new Error("modelId is required");return(await tn(e,an,{})).exists?[an]:[]}async function nO(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await np(e,{config:t,dtype:r,device:s,model_file_name:n});if(a){const l=await Zf(e);i.push(...l)}if(o){const l=await sO(e);i.push(...l)}return i}async function aO(e,t,r={}){e=mg[e]??e;const s=qa[e];if(!s)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(qa).join(", ")}]`);const{type:n}=s,i=await nO(t,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){const l=await sp(t,r),c=rp(l),d=wE(c);if(d){const h=Object.values(d).map(_=>`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||h.some(p=>_.startsWith(p)))}}return i}async function oO(e,t=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:_={}}={}){e=mg[e]??e;const p=qa[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(qa)}]`);t||(t=p.default.model,ue.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype&&(l=p.default.dtype));const w=await aO(e,t,{device:i,dtype:l});let v={};r&&(await Promise.all(w.map(async Q=>tn(t,Q)))).forEach((Q,H)=>{Q.exists&&(v[w[H]]={loaded:0,total:Q.size??0})});const y={progress_callback:r?new pi(r,v):void 0,config:s,cache_dir:n,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:h,session_options:_},M=w.includes("tokenizer.json"),T=w.includes("preprocessor_config.json"),A=p.model;let C;if(Array.isArray(A)){const $=s??await on.from_pretrained(t,y),{model_type:Q}=$,H=A.find(D=>D.supports(Q));if(!H)throw Error(`Unsupported model type "${Q}" for task "${e}". None of the candidate model classes support this type.`);C=H.from_pretrained(t,{...y,config:$})}else C=A.from_pretrained(t,y);const[S,N,x]=await Promise.all([M?Te.from_pretrained(t,y):null,T?qT.from_pretrained(t,y):null,C]),R={task:e,model:x};S&&(R.tokenizer=S),N&&(R.processor=N),Pr(r,{status:"ready",task:e,model:t});const z=p.pipeline;return new z(R)}fe.IS_PROCESS_AVAILABLE;let gr=null;const gg="onnx-community/moonshine-base-ONNX";function Ct(e,t,r){self.postMessage({type:"log",level:e,message:t,meta:r})}async function iO(){if(gr)return;Ct("info","load: begin",{model:gg}),self.postMessage({type:"status",status:"loading",message:"Downloading speech model…"});let e=!1,t="downloading";const r=setTimeout(()=>{!e&&!gr&&(t="cache-loading",self.postMessage({type:"status",status:"loading",message:"Loading speech model from cache…"}),Ct("info","load: no download progress within 1.5s, assuming cache hit"))},1500),s=setInterval(()=>{if(gr)return;const n=t==="downloading"?"Downloading speech model…":"Loading speech model from cache…";self.postMessage({type:"status",status:"loading",message:n})},1e4);try{const n=Date.now();gr=await oO("automatic-speech-recognition",gg,{dtype:"fp32",device:"wasm",progress_callback:o=>{o.status==="progress_total"&&typeof o.progress=="number"?(e=!0,self.postMessage({type:"progress",pct:o.progress})):(o.status==="download"||o.status==="initiate")&&(e=!0,Ct("debug","pipeline: "+o.status,{file:o.file}))}}),Ct("info","load: pipeline ready",{ms:Date.now()-n});const a=Date.now();try{await Promise.race([gr(new Float32Array(16e3)),new Promise((o,i)=>setTimeout(()=>i(new Error("warmup timeout")),1e4))]),Ct("info","load: warmup done",{ms:Date.now()-a})}catch(o){const i=o instanceof Error?o.message:String(o);Ct("warn","load: warmup failed (best-effort, ignored)",{error:i,ms:Date.now()-a})}self.postMessage({type:"status",status:"ready",message:"Speech model ready"})}finally{clearTimeout(r),clearInterval(s)}}self.onmessage=async e=>{var r,s;const{type:t}=e.data;if(t==="load"){try{await iO()}catch(n){const a=n instanceof Error?n.message:"Model load failed",o=n instanceof Error?n.stack:"";console.error("[speechWorker] load failed:",a,o),Ct("error","load: failed",{error:a,stack:o}),self.postMessage({type:"error",error:a})}return}if(t==="transcribe"){const n=e.data.audio,a=e.data.seq??0;if(!gr){Ct("warn","transcribe: model not loaded, dropping segment",{samples:n==null?void 0:n.length,seq:a}),self.postMessage({type:"error",error:"Model not loaded",seq:a});return}const o=Date.now();try{const l=((r=(await gr(n)).text)==null?void 0:r.trim())??"";Ct("debug","transcribe: ok",{ms:Date.now()-o,samples:n.length,chars:l.length,seq:a}),self.postMessage({type:"result",text:l,seq:a})}catch(i){const l=i instanceof Error?i.message:"Transcription failed";Ct("error","transcribe: failed",{error:l,ms:Date.now()-o,seq:a}),self.postMessage({type:"error",error:l,seq:a})}return}if(t==="transcribe-partial"){const n=e.data.audio,a=e.data.seq??0;if(!gr){Ct("warn","transcribe-partial: model not loaded, dropping",{samples:n==null?void 0:n.length,seq:a}),self.postMessage({type:"partial-error",seq:a,error:"Model not loaded"});return}const o=Date.now();try{const l=((s=(await gr(n)).text)==null?void 0:s.trim())??"";Ct("debug","transcribe-partial: ok",{ms:Date.now()-o,samples:n.length,chars:l.length,seq:a}),self.postMessage({type:"partial",text:l,seq:a})}catch(i){const l=i instanceof Error?i.message:"Partial transcription failed";Ct("warn","transcribe-partial: failed",{error:l,ms:Date.now()-o,seq:a}),self.postMessage({type:"partial-error",seq:a,error:l})}return}}})();
39
+ ${s}${a}`+n.repeat(e)+`${s}`,o}function wT(e,t,r,s){return`${t}${s}`+r.repeat(e)+`${t}`}function vT(e,t,r,s,n,a){return e===0&&t===0?wT(r,s,n,a):gT(r,e,t,s,n,a)}var j_=(Tn=class extends Ee{constructor(){super(...arguments);k(this,"fake_image_token","<fake_token_around_image>");k(this,"image_token","<image>");k(this,"global_img_token","<global-img>")}async _call(t,r=null,s={}){s.return_row_col_info??(s.return_row_col_info=!0);let n;r&&(n=await this.image_processor(r,s)),Array.isArray(t)||(t=[t]);const a=n.rows??[new Array(t.length).fill(0)],o=n.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let h=0;h<t.length;++h){const _=t[h],p=a[h],w=o[h];l.push(By(_,this.image_token));const v=p.map((T,A)=>vT(T,w[A],i,this.fake_image_token,this.image_token,this.global_img_token)),y=_.split(this.image_token);if(y.length===0)throw new Error("The image token should be present in the text.");let M=y[0];for(let T=0;T<v.length;++T)M+=v[T]+y[T+1];c.push(M)}return{...this.tokenizer(c),...n}}},k(Tn,"image_processor_class",dt),k(Tn,"tokenizer_class",Te),k(Tn,"uses_processor_config",!0),Tn),yT=(En=class extends Ee{constructor(e,t,r){super(e,t,r),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(v=>v.images).flatMap(v=>v.images).map(v=>qt.read(v)));const s=this.tokenizer,n=s.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>s.encode(v,{add_special_tokens:!1}),o=n.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,c,d]=s.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let h=a(o[0]),_=new Array(h.length).fill(!1);for(let v=1;v<o.length;++v){const y=new Array(this.num_image_tokens).fill(l),M=a(o[v]);h=Jt(h,[c],y,[d],M);const T=new Array(this.num_image_tokens).fill(!0);_=Jt(_,[!1],T,[!1],new Array(M.length).fill(!1))}const p=[1,h.length],w={input_ids:new U("int64",h,p),attention_mask:new U("int64",new Array(h.length).fill(1),p),images_seq_mask:new U("bool",_,p),images_emb_mask:new U("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},k(En,"image_processor_class",dt),k(En,"tokenizer_class",Te),k(En,"uses_processor_config",!0),En),bT=(Ya=class extends Ee{async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=e?this.tokenizer(e,r):{},n=t?await this.image_processor(t,r):{};return{...s,...n}}},k(Ya,"tokenizer_class",Te),k(Ya,"image_processor_class",dt),Ya),MT=(Ja=class extends Ee{async _call(e,t=null,r={}){const{image_rows:s,image_cols:n,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){const i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:h=!0}=this.image_processor.config,_=T=>Math.ceil(Math.floor(T/d)/c),p=_(l)**2,w=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",y=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let M=0;t=t.map(T=>{const A=T.split(i);return A[0]+A.slice(1).map(S=>{const C=M++,[I,x]=a[C],R=s[C],z=n[C],$=_(I)*_(x);let Q=w;if(R>1||z>1){const H=i.repeat(p);for(let D=0;D<R;++D)for(let O=0;O<z;++O)Q+=`<|img_row_${D+1}_col_${O+1}|>`+H;h&&(Q+=y+i.repeat($))}else Q+=i.repeat($);return Q+v+S}).join("")})}return{...o,...t?this.tokenizer(t,r):{}}}},k(Ja,"tokenizer_class",Te),k(Ja,"image_processor_class",dt),Ja),xT=(An=class extends Ee{async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let h=0;h<t.length;++h)t[h]=t[h].replace(i,i.repeat(d))}const n=t?this.tokenizer(t,r):{};return{...s,...n}}},k(An,"tokenizer_class",Te),k(An,"image_processor_class",dt),k(An,"uses_processor_config",!0),An),q_={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},kT=(Ka=class extends Ee{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!q_.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,s]=q_[t],n=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let h=0;h<a;++h){const _=c[h],p=[],w=[];for(let y=1;y<o;++y){const[M,T]=je(nt(_[y]));if(w.push(M),T==s)break;p.push(T)}const v=w.length>0?w.reduce((y,M)=>y*M,1):0;l.push(p),i.push(v)}return[n(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[s,n]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),c=[],d=[];for(let h=0;h<s.length;++h){const[_,p]=je([n[h],o[h],l[h]]);c.push([s[h],a[h],i[h]][p]),d.push(_)}return{generated_text:c,scores:d,char_preds:s,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),r=await Te.from_pretrained("Xenova/gpt2"),s=await Te.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:s},t}async _call(e,t=null){const r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},k(Ka,"tokenizer_class",Te),k(Ka,"image_processor_class",dt),Ka),TT=(Za=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(Za,"tokenizer_class",Te),k(Za,"feature_extractor_class",Lt),Za),ET=(eo=class extends Ee{},k(eo,"tokenizer_class",Te),k(eo,"image_processor_class",dt),eo),ps="<image>";function AT(e,t,r,s,n){return`${s.repeat(r*n)}${t}${e}
40
+ `}var CT=(Cn=class extends Ee{async _call(e,t=null,r={}){t||(ue.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(ps))?a=t.map(l=>{const c=l.replaceAll(ps,ps.repeat(n)),d=c.lastIndexOf(ps),h=d===-1?0:d+ps.length;return c.slice(0,h)+s+c.slice(h)+`
41
+ `}):(ue.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(l=>AT(l,s,n,ps,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},k(Cn,"tokenizer_class",Te),k(Cn,"image_processor_class",dt),k(Cn,"uses_processor_config",!1),Cn),W_="<|image|>",ST=/<\|image_\d+\|>/g,PT=(to=class extends Ee{async _call(e,t=null,{padding:r=!0,truncation:s=!0,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:n});const{num_img_tokens:i}=o,l=e.map((d,h)=>d.split(ST).join(W_.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:s});const c=this.tokenizer._tokenizer.token_to_id(W_);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},k(to,"image_processor_class",dt),k(to,"tokenizer_class",Te),to),FT=(Sn=class extends Ee{async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:d,spatial_merge_size:h}=this.config,_=d*h,p=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v<t.length;++v){const y=i.repeat(w),M=y+l,T=y+c,A=M.repeat(p-1)+T;t[v]=t[v].replace(i,A)}}const n=t?this.tokenizer(t,r):{};return{...s,...n}}},k(Sn,"tokenizer_class",Te),k(Sn,"image_processor_class",dt),k(Sn,"uses_processor_config",!0),Sn),LT=(fu=class extends Ee{async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},k(fu,"feature_extractor_class",w_),fu),H_=class extends Hi{},IT=class extends H_{},Q_=(_u=class extends Ee{async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},k(_u,"image_processor_class",dt),_u),X_=class extends Q_{},OT=class extends X_{},NT=(ro=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(ro,"tokenizer_class",Te),k(ro,"feature_extractor_class",Lt),ro),DT=(Pn=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);s.audio_token_len=[l],s.audio_values=o;const c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(Pn,"tokenizer_class",Te),k(Pn,"feature_extractor_class",Lt),k(Pn,"uses_processor_config",!0),Pn),va="[AUDIO]",zT="[BEGIN_AUDIO]",BT=375;function RT(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.subarray(s,Math.min(s+t,e.length)));return r}var GT=(Fn=class extends Ee{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const s={};if(t){if(!e.includes(va))throw new Error(`The input text does not contain the audio token ${va}.`);Array.isArray(t)||(t=[t]);const a=e.split(va),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(p=>RT(p,i)),c=l.map(p=>p.length),d=l.flat(),h=(await Promise.all(d.map(p=>this.feature_extractor(p,r)))).map(p=>p.input_features);s.audio_values=h.length>1?ze(h,0):h[0];let _=a[0];for(let p=0;p<c.length;++p){_+=zT;for(let w=0;w<c[p];++w)_+=va.repeat(BT);_+=a[p+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},k(Fn,"tokenizer_class",Te),k(Fn,"feature_extractor_class",Lt),k(Fn,"uses_processor_config",!1),Fn),Y_=32,Qi=6,ya=8,$T=10,VT=32,UT=(Ln=class extends Ee{get num_mel_frames_first_audio_chunk(){return(Qi+1)*ya}get num_samples_first_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){const{hop_length:e,n_fft:t}=this.feature_extractor.config;return ya*e+t}get num_right_pad_tokens(){return Qi+1+$T}get audio_length_per_tok(){return ya}get raw_audio_length_per_tok(){return ya*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:r=!0}={}){if(at(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){const s=Y_*this.raw_audio_length_per_tok,n=new Float32Array(s+e.length);n.set(e,s);const a=await this.feature_extractor(n,{center:!0}),i=1+(Y_+Qi),l=new BigInt64Array(i).fill(BigInt(VT));return l[0]=1n,{input_ids:new U("int64",l,[1,i]),...a}}else{const s=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+s);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},k(Ln,"tokenizer_class",Te),k(Ln,"feature_extractor_class",Lt),k(Ln,"uses_processor_config",!1),Ln),jT=(so=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(so,"tokenizer_class",Te),k(so,"feature_extractor_class",Lt),so),qT=(no=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(no,"tokenizer_class",Te),k(no,"feature_extractor_class",Lt),no),WT=(ao=class extends Ee{async _call(e){return await this.feature_extractor(e)}},k(ao,"tokenizer_class",Te),k(ao,"feature_extractor_class",Lt),ao),HT=class{static async from_pretrained(e,t={}){const r=await er(e,an,!0,t),{image_processor_type:s,feature_extractor_type:n,processor_class:a}=r;if(a&&Di[a])return Di[a].from_pretrained(e,t);if(!s&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(s){const l=wa[s.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${s}'.`);o.image_processor=new l(r)}if(n){const l=wa[n];if(l)o.image_processor=new l(r);else{const c=zi[n];if(!c)throw new Error(`Unknown feature_extractor_type: '${n}'.`);o.feature_extractor=new c(r)}}const i={};return new Ee(i,o,null)}};async function QT(e,t){return await er(e,"config.json",!0,t)}function ms(e){const t={};let r={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=ms(e.text_config);break;case"moondream1":r=ms(e.phi_config);break;case"musicgen":r=ms(e.decoder);break;case"multi_modality":r=ms(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";const{num_hidden_layers:n,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:n,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case"vision-encoder-decoder":const i=ms(e.decoder),l="num_decoder_layers"in i,c=Ze(e,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=i.num_decoder_layers,c.num_decoder_heads=i.num_decoder_heads,c.decoder_hidden_size=i.decoder_hidden_size,c.num_encoder_layers=i.num_encoder_layers,c.num_encoder_heads=i.num_encoder_heads,c.encoder_hidden_size=i.encoder_hidden_size):(c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size),c}const s={...r,...Ze(e,["model_type","multi_query","is_encoder_decoder"])};for(const n in t)s[n]=e[t[n]];return s}function ba(e,t){e instanceof Xi||(e=new Xi(e));const r=(t==null?void 0:t.prefix)??"past_key_values",s=r==="present"?"present":"past",n=new Set;if(["lfm2","lfm2_moe"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")n.add(`${r}.${o}.key`),n.add(`${r}.${o}.value`);else if(a[o]==="conv")n.add(`${s}_conv.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){const a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??(o==null?void 0:o.length);for(let l=0;l<i;++l)(!o||o[l]==="mamba")&&(n.add(`${s}_conv.${l}`),n.add(`${s}_ssm.${l}`)),(!o||o[l]==="attention")&&(n.add(`${r}.${l}.key`),n.add(`${r}.${l}.value`));return n}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){const{layer_types:a}=e;for(let o=0;o<a.length;++o)if(a[o]==="full_attention")n.add(`${r}.${o}.key`),n.add(`${r}.${o}.value`);else if(a[o]==="linear_attention")e.model_type==="olmo_hybrid"?(n.add(`${s}_conv.${o}.key`),n.add(`${s}_conv.${o}.value`),n.add(`${s}_conv.${o}.query`)):n.add(`${s}_conv.${o}`),n.add(`${s}_recurrent.${o}`);else throw new Error(`Unsupported layer type: ${a[o]}`);return n}else if(["gemma4","gemma4_text"].includes(e.model_type)){const a=e.model_type==="gemma4"?e.text_config:e,o=a.num_hidden_layers,i=a.num_kv_shared_layers??0,l=o-i;for(let c=0;c<l;++c)n.add(`${r}.${c}.key`),n.add(`${r}.${c}.value`);return n}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let a;return e.model_type==="voxtral_realtime"&&(t==null?void 0:t.session_name)==="audio_encoder"?a=e.audio_config:a=e.text_config,ba(a,t)}return XT(e,{prefix:r})}function XT(e,{prefix:t="past_key_values"}={}){const r=new Set,s=e.normalized_config;if(s.is_encoder_decoder&&"num_encoder_heads"in s&&"num_decoder_heads"in s)for(let n=0;n<s.num_decoder_layers;++n)r.add(`${t}.${n}.encoder.key`),r.add(`${t}.${n}.encoder.value`),r.add(`${t}.${n}.decoder.key`),r.add(`${t}.${n}.decoder.value`);else if(s.multi_query)for(let n=0;n<s.num_layers;++n)r.add(`${t}.${n}.key_value`);else for(let n=0;n<s.num_layers;++n)r.add(`${t}.${n}.key`),r.add(`${t}.${n}.value`);return r}var Xi=class yd{constructor(t){k(this,"model_type",null);k(this,"is_encoder_decoder",!1);k(this,"max_position_embeddings");k(this,"transformers.js_config");Object.assign(this,t),this.normalized_config=ms(this)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main"}={}){s&&!(s instanceof yd)&&(s=new yd(s));const i=s??await QT(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(i)}},on=class{static async from_pretrained(...e){return Xi.from_pretrained(...e)}};function J_(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function K_(e,t){const r=[];for(let s=0;s<t;++s)r.push(`${e}_data${s===0?"":"_"+s}`);return r}async function YT(e,t,r,s){const n=`${t}${s}.onnx`,a=`${r.subfolder??""}/${n}`;return await ha(e,a,!0,r,fe.IS_NODE_ENV)}async function JT(e,t,r,s,n,a={}){const o=`${t}${r}.onnx`,i=fe.IS_NODE_ENV;let l=[];const c=J_(n,o,t);if(c>0){if(c>Mf)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Mf}).`);const d=K_(o,c);for(const h of d){const _=`${s.subfolder??""}/${h}`;l.push(new Promise(async(p,w)=>{const v=await ha(e,_,!0,s,i);p(v instanceof Uint8Array?{path:h,data:v}:h)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const h=await ha(e,d.data,!0,s);return{...d,data:h}}return d}));return Promise.all(l)}async function KT(e,t,r,s=!1,n=void 0){var T;let a=((T=r.config)==null?void 0:T["transformers.js_config"])??{};const o=Uf(r.device??a.device,t,{warn:A=>ue.info(A)}),i=Mx(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});const c=Wf(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:A=>ue.info(A)});if(Ci.hasOwnProperty(c)){if(o==="webgpu"&&!fe.IS_NODE_ENV&&c===We.fp16&&!await Tx())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(We).join(", ")}`);const d=Ci[c],h={...r.session_options};h.executionProviders??(h.executionProviders=i);const _=a.free_dimension_overrides;_?h.freeDimensionOverrides??(h.freeDimensionOverrides=_):o.startsWith("webnn")&&!h.freeDimensionOverrides&&ue.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const p=YT(e,t,r,d),w=r.use_external_data_format??a.use_external_data_format,v=await JT(e,t,d,r,w,h);if(v.length>0&&(!fe.IS_NODE_ENV||v.some(A=>typeof A!="string"))&&(h.externalData=v),s&&o==="webgpu"){const A=ba(r.config,{prefix:"present",session_name:n});if(A.size>0&&!Ei()){const S={};for(const C of A)S[C]="gpu-buffer";h.preferredOutputLocation=S}}return{buffer_or_path:await p,session_options:h,session_config:{dtype:c,device:o}}}async function ZT(e,t,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const a=(s==null?void 0:s[n])??!1,{buffer_or_path:o,session_options:i,session_config:l}=await KT(e,t[n],r,a,n),c=await Rf(o,i,l);return[n,c]})))}function Z_(e){for(let t in e)Vf(e[t])?e[t]=new U(e[t]):typeof e[t]=="object"&&Z_(e[t]);return e}async function xe(e,t){const r=eE(e,t);try{const s=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return fe.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),n=await $f(e,s);return Z_(n)}catch(s){const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw ue.error(`An error occurred during model execution: "${s}".`),ue.error("Inputs given to model:",n),s}}function eE(e,t){const r=Object.create(null),s=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof U)){s.push(o);continue}r[o]=Ei()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);const n=Object.keys(t).length,a=e.inputNames.length;if(n>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ue.warn(`WARNING: Too many inputs were provided (${n} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var Ye=class{},ne=class extends Ye{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},He=class extends Ye{constructor({logits:e}){super(),this.logits=e}},Je=class extends Ye{constructor({logits:e}){super(),this.logits=e}},ht=class extends Ye{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Jr=class extends Ye{constructor({logits:e}){super(),this.logits=e}},tE=class extends Ye{constructor({alphas:e}){super(),this.alphas=e}},Wt=class extends vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},rE=class extends vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Yi=class extends vt{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},sE=class extends Wt{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){const s=t[r].data;s.fill(-1/0),s[this.bos_token_id]=0}return t}},nE=class extends Wt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){const s=t[r].data;s.fill(-1/0);for(const n of this.eos_token_id)s[n]=0}return t}},aE=class extends Wt{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of this.suppress_tokens)s[n]=-1/0}return t}},ep=class extends Wt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){const s=t[r].data;for(const n of this.begin_suppress_tokens)s[n]=-1/0}return t}},oE=class extends Wt{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;if(s[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){s.subarray(0,this.timestamp_begin).fill(-1/0);continue}const n=e[r].slice(this.begin_index),a=n.length>=1&&n[n.length-1]>=this.timestamp_begin,o=n.length<2||n[n.length-2]>=this.timestamp_begin;if(a&&(o?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const d=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(d+1).fill(-1/0)}const i=cx(s),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=je(i.subarray(0,this.timestamp_begin))[0];l>c&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},iE=class extends Wt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[n+o]);r.push(a.map(Number))}const s=new Map;for(const n of r){const a=n.slice(0,n.length-1),o=JSON.stringify(a),i=s.get(o)??[];i.push(n[n.length-1]),s.set(o,i)}return s}getGeneratedNgrams(e,t){const r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data,n=this.calcBannedNgramTokens(e[r]);for(const a of n)s[a]=-1/0}return t}},lE=class extends Wt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data;for(const n of new Set(e[r])){const a=Number(n);s[a]<0?s[a]*=this.penalty:s[a]/=this.penalty}}return t}},cE=class extends Wt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){const s=t[r].data;for(const n of this.eos_token_id)s[n]=-1/0}return t}},uE=class extends Wt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){const n=t[r].data;for(const a of this.eos_token_id)n[a]=-1/0}return t}},dE=class extends Wt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){const s=t[r].data,n=e[r];for(const a of this.bad_words_ids){if(n.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=n.at(-i)){o=!1;break}o&&(s[a.at(-1)]=-1/0)}}return t}},hE=class extends Wt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,s=t.slice([0,r],null),n=t.slice([r,t.dims[0]],null);for(let a=0;a<n.data.length;++a)n.data[a]+=(s.data[a]-n.data[a])*this.guidance_scale;return n}},fE=class extends rE{constructor(e){super(),this.temperature=e}_call(e,t){const r=t.data;for(let s=0;s<r.length;++s)r[s]/=this.temperature;return t}},tp=class{constructor(e){k(this,"max_length",20);k(this,"max_new_tokens",null);k(this,"min_length",0);k(this,"min_new_tokens",null);k(this,"early_stopping",!1);k(this,"max_time",null);k(this,"do_sample",!1);k(this,"num_beams",1);k(this,"num_beam_groups",1);k(this,"penalty_alpha",null);k(this,"use_cache",!0);k(this,"temperature",1);k(this,"top_k",50);k(this,"top_p",1);k(this,"typical_p",1);k(this,"epsilon_cutoff",0);k(this,"eta_cutoff",0);k(this,"diversity_penalty",0);k(this,"repetition_penalty",1);k(this,"encoder_repetition_penalty",1);k(this,"length_penalty",1);k(this,"no_repeat_ngram_size",0);k(this,"bad_words_ids",null);k(this,"force_words_ids",null);k(this,"renormalize_logits",!1);k(this,"constraints",null);k(this,"forced_bos_token_id",null);k(this,"forced_eos_token_id",null);k(this,"remove_invalid_values",!1);k(this,"exponential_decay_length_penalty",null);k(this,"suppress_tokens",null);k(this,"streamer",null);k(this,"begin_suppress_tokens",null);k(this,"forced_decoder_ids",null);k(this,"guidance_scale",null);k(this,"num_return_sequences",1);k(this,"output_attentions",!1);k(this,"output_hidden_states",!1);k(this,"output_scores",!1);k(this,"return_dict_in_generate",!1);k(this,"pad_token_id",null);k(this,"bos_token_id",null);k(this,"eos_token_id",null);k(this,"encoder_no_repeat_ngram_size",0);k(this,"decoder_start_token_id",null);k(this,"generation_kwargs",{});Object.assign(this,Ze(e,Object.getOwnPropertyNames(this)))}},Ma=class extends vt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},rp=class Dv extends vt{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof Dv?t=t.criteria:t instanceof Ma&&(t=[t]),this.criteria.push(...t)}_call(t,r){const s=new Array(t.length).fill(!1);for(const n of this.criteria){const a=n(t,r);for(let o=0;o<s.length;++o)s[o]||(s[o]=a[o])}return s}[Symbol.iterator](){return this.criteria.values()}},_E=class extends Ma{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(t=>t.length>=this.max_length)}},pE=class extends Ma{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(n=>s==n)})}},xa=class extends vt{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),s=e.data;if(t===-1)s=s.slice(-r);else{let n=t*r;s=s.slice(n,n+r)}return s}randomSelect(e){return WM(e)}static getSampler(e){if(e.do_sample)return new gE(e);if(e.num_beams>1)return new wE(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 mE(e)}},mE=class extends xa{async sample(e){const t=je(e.data)[1];return[[BigInt(t),0]]}},gE=class extends xa{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await fs(e,t),n=nt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(n);return[s.data[a],Math.log(n[a])]})}},wE=class extends xa{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await fs(e,t),n=nt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[s.data[o],Math.log(n[o])])}},vE=class{constructor(e){if(e)for(const t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);const r=e[t];if(!(r instanceof U))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){const e=this;if(Object.keys(e).length===0)return 0;for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(const t in e){const r=this[t],s=e[t];r&&r!==s&&r.location==="gpu-buffer"&&r.dispose(),this[t]=s}}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},Ji=vE,q={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},fr={[q.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[q.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[q.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[q.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[q.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[q.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[q.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"}},[q.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"}},[q.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[q.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[q.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"}},[q.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{const s={...fr[q.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},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 yE(e){const t=fr[e];return(t==null?void 0:t.text_only_sessions)??null}function bE(e,t,r={}){const s=fr[e]??fr.default;return{sessions:s.sessions(t,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function sp(e,{warn:t=!0}={}){const r=e.architectures||[];for(const s of r){const n=_r.get(s);if(n!==void 0)return n}if(e.model_type){const s=_r.get(e.model_type);if(s!==void 0)return s;for(const n of Object.values(gs))if(n.has(e.model_type)){const a=_r.get(n.get(e.model_type));if(a!==void 0)return a}}if(t){const s=r.length>0?r.join(", "):"(none)";ue.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${pa}`)}return q.EncoderOnly}function np(e,{config:t=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(t!==null)return on.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n});const a=JSON.stringify([e,r,s,n]);return Cf(a,()=>on.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n}))}async function ap(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){t=await np(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=s??o.device;let d=r??o.dtype;const h=sp(t),_=(v,y=null)=>{y=y??v;const M=Uf(c,v),T=Wf(d,v,M),A=Ci[T]??"",S=`${y}${A}.onnx`,C=`${l}/${S}`;a.push(C);const I=J_(i,S,v);for(const x of K_(S,I)){const R=`${l}/${x}`;a.push(R)}},{sessions:p,optional_configs:w}=bE(h,t,{model_file_name:n});for(const[v,y]of Object.entries(p))_(v,y);if(w)for(const v of Object.values(w))a.push(v);return a}var gs=null;function ME(e){gs=e}function Ki(e){if(e instanceof U)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new U("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new U("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function op(e){return new U("bool",[e],[1])}var ip={[q.DecoderOnly]:{can_generate:!0,forward:pr,prepare_inputs:ln},[q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:pr,prepare_inputs:ln},[q.Seq2Seq]:{can_generate:!0,forward:ka,prepare_inputs:Ta},[q.Vision2Seq]:{can_generate:!0,forward:ka,prepare_inputs:Ta},[q.Musicgen]:{can_generate:!0,forward:ka},[q.EncoderDecoder]:{can_generate:!1,forward:ka},[q.ImageTextToText]:{can_generate:!0,forward:EE,prepare_inputs:Ea},[q.AudioTextToText]:{can_generate:!0,forward:TE,prepare_inputs:Ea},[q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ea},[q.Phi3V]:{can_generate:!0,prepare_inputs:Ea},[q.MultiModality]:{can_generate:!0},[q.AutoEncoder]:{can_generate:!1,forward:xE},[q.Chatterbox]:{can_generate:!0,forward:Or},[q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ln},default:{can_generate:!1,forward:Or}};function lp(e,t){var i;let r=_r.get(e),s=!1;const n=(i=t==null?void 0:t.architectures)==null?void 0:i[0];if(n&&n!==e&&(e!=null&&e.endsWith("ForCausalLM"))&&n.endsWith("ForConditionalGeneration")){const l=_r.get(n);l!==void 0&&(r=l,s=!0)}const a=ip[r]??ip.default,o=fr[r]??fr.default;return{typeConfig:{...a,...o},textOnly:s,modelType:r}}var _r=new Map,Zi=new Map,ws=new Map,P=class extends vt{constructor(t,r,s){super();k(this,"main_input_name","input_ids");k(this,"forward_params",["input_ids","attention_mask"]);k(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=s;const n=ws.get(this.constructor),{typeConfig:a}=lp(n,t);this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const t=[];for(const s of Object.values(this.sessions))t.push((r=s.release)==null?void 0:r.call(s));return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:h=null,session_options:_={}}={}){const p={progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:c,dtype:d,use_external_data_format:h,session_options:_},w=ws.get(this);s=p.config=await on.from_pretrained(t,p);const{typeConfig:v,textOnly:y,modelType:M}=lp(w,s);if(M===void 0){const C=w??(s==null?void 0:s.model_type);C!=="custom"&&ue.warn(`Model type for '${C}' not found, assuming encoder-only architecture. Please report this at ${pa}.`)}if(r&&!(r instanceof pi)){const C={};try{const I=await ap(t,{config:s,dtype:d,device:c,model_file_name:i});(await Promise.all(I.map(R=>en(t,R,p)))).forEach((R,z)=>{if(R.exists){const $=I[z]==="config.json";C[I[z]]={loaded:$?R.size??0:0,total:R.size??0}}})}catch(I){ue.warn(`Unable to fetch model file metadata for total progress tracking: ${I}`)}Object.keys(C).length>0&&(p.progress_callback=new pi(r,C))}const T=v.sessions(s,p,y),A=[ZT(t,T,p,v.cache_sessions)];v.optional_configs&&A.push(CE(t,v.optional_configs,p));const S=await Promise.all(A);return new this(s,...S)}async _call(t){return await this.forward(t)}async forward(t){return await this._forward(this,t)}get generation_config(){var t;return((t=this.configs)==null?void 0:t.generation_config)??null}_get_logits_processor(t,r,s=null){const n=new Yi;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&n.push(new lE(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&n.push(new iE(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&n.push(new dE(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&n.push(new cE(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&n.push(new uE(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&n.push(new sE(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&n.push(new nE(t.max_length,t.forced_eos_token_id)),t.suppress_tokens!==null&&n.push(new aE(t.suppress_tokens)),t.begin_suppress_tokens!==null){const a=r>1||t.forced_bos_token_id===null?r:r+1;n.push(new ep(t.begin_suppress_tokens,a))}return t.guidance_scale!==null&&t.guidance_scale>1&&n.push(new hE(t.guidance_scale)),t.temperature===0&&t.do_sample&&(ue.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),t.do_sample=!1),t.do_sample&&t.temperature!==null&&t.temperature!==1&&n.push(new fE(t.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(t,r,s=tp){const n={...this.config};for(const o of["decoder","generator","text_config"])o in n&&Object.assign(n,n[o]);const a=new s(n);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,Ze(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){const s=new rp;return t.max_length!==null&&s.push(new _E(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&s.push(new pE(t.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){const t=[gs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,gs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,gs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,gs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=ws.get(this.constructor),s=new Set,n=this.config.model_type;for(const o of t){const i=o==null?void 0:o.get(n);i&&s.add(i)}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(a+=` Please use the following class instead: ${[...s].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=el(r,s.past_key_values),s.input_ids=new U("int64",t.flat(),[t.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=ze([s.decoder_attention_mask,yt([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=ze([s.attention_mask,yt([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:s}){const n=Ze(s,this.forward_params),a=this.main_input_name;if(a in n){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[a]=t;return{inputs_tensor:n[a],model_inputs:n,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:i,attention_mask:l,...c}=r,d=await this._prepare_inputs_embeds(r);r={...c,...Ze(d,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await Or(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)a=ze([a,Li(a,0)],0),"attention_mask"in r&&(r.attention_mask=ze([r.attention_mask,Zf(r.attention_mask)],0));else if(r.decoder_input_ids){const o=Ki(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=ze(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof U)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(n??(n=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==t)throw new Error(`\`decoder_start_token_id\` expcted to have length ${t} but got ${n.length}`);i=n}else i=Array.from({length:t},()=>[n]);i=Ki(i)}return l.decoder_attention_mask=Jf(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:t,model_kwargs:o});const d=this.config.is_encoder_decoder;d&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let h;d?{input_ids:h,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):h=l[c];let _=h.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);const p=this._get_logits_processor(r,_,s),w=this._get_stopping_criteria(r,n),v=l[c].dims.at(0),y=xa.getSampler(r),M=new Array(v).fill(0),T=h.tolist();a&&a.put(T);let A,S={},C={};for(;;){if(l=this.prepare_inputs_for_generation(T,l,r),A=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){const O=kE(A);for(const te in O)te in S||(S[te]=[]),S[te].push(O[te])}else this._return_dict_in_generate_keys&&Object.assign(C,Ze(A,this._return_dict_in_generate_keys));const $=A.logits.slice(null,-1,null).to("float32"),Q=p(T,$),H=[];for(let O=0;O<Q.dims.at(0);++O){const te=Q[O],W=await y(te);for(const[ee,G]of W){const L=BigInt(ee);M[O]+=G,T[O].push(L),H.push([L]);break}}if(a&&a.put(H),w(T).every(O=>O))break;l=this._update_model_kwargs_for_generation({generated_input_ids:H,outputs:A,model_inputs:l,is_encoder_decoder:d})}a&&a.end();const I=new U("int64",T.flat(),[T.length,T[0].length]),x=el(A,l.past_key_values),R=new Set(Object.values(x));for(const $ of Object.values(A))$.location==="gpu-buffer"&&!R.has($)&&$.dispose();return"past_key_values"in o||r.return_dict_in_generate||await x.dispose(),r.return_dict_in_generate?{sequences:I,past_key_values:x,...S,...C}:I}async _encode_input(t,r,s){if(!Object.hasOwn(this.sessions,t))throw new Error(`Model does not have a ${t} session.`);const n=this.sessions[t];return(await xe(n,Ze(r,n.inputNames)))[s]}async encode_image(t){return this._encode_input("vision_encoder",t,"image_features")}async encode_text(t){return this._encode_input("embed_tokens",t,"inputs_embeds")}async encode_audio(t){return this._encode_input("audio_encoder",t,"audio_features")}};async function ka(e,t){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:a,...o}=t;if(!r){const i=Ze(t,e.sessions.model.inputNames);r=(await Or(e,i)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,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 pr(e,o,!0)}async function Or(e,t){const r=e.sessions.model,s=Ze(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Zf(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const n=s.pixel_values.dims;s.pixel_mask=yt([n[0],n[2],n[3]])}return await xe(r,s)}async function xE(e,t){const r=await e.encode(t);return await e.decode(r)}function el(e,t){const r=Object.create(null);for(const s in e)if(s.startsWith("present")){const n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");s.includes("encoder")&&t?r[n]=t[n]:r[n]=e[s]}return t?(t.update(r),t):new Ji(r)}function kE(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in e)s.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[s]));return t}function cp(e,t){return e.map(r=>typeof r=="number"?r:t[r]??0)}function tl(e,t,r){var c,d,h,_;if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;const s=e.sessions.decoder_model_merged??e.sessions.model,n=((d=(c=t[e.main_input_name]??t.attention_mask)==null?void 0:c.dims)==null?void 0:d[0])??1,a=ba(e.config),o=(_=(h=e.config)==null?void 0:h.normalized_config)==null?void 0:_.num_heads,i={batch_size:n};typeof o=="number"&&(i["batch_size x num_heads"]=n*o);const l=Object.create(null);for(const p of s.inputMetadata){if(!a.has(p.name))continue;const w=cp(p.shape,i),v=w.reduce((T,A)=>T*A,1),y=sn[p.type],M=new U(p.type,new y(v),w);t[p.name]=M,l[p.name]=M}return r?(r.update(l),r):new Ji(l)}async function pr(e,t,r=!1){const s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...a}=t;if(s.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=op(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=AE(a,n,i)}s.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new U("int64",[0n],[])),tl(e,a,n);const o=Ze(a,s.inputNames);return await xe(s,o)}async function up(e,{encode_function:t,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:h=null,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});const w=Ze(_,s);if(Object.keys(w).length>0){if(a.dims[1]!==1){const v=await t({...w,..._});({inputs_embeds:l,attention_mask:o}=r({[n]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(c&&a.dims[1]===1){const v=a.dims[1],y=c.get_seq_length();o=ze([yt([a.dims[0],y]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){const{image_grid_thw:w,video_grid_thw:v}=_;[i]=e.get_rope_index(a,w,v,o)}return await pr(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},!0)}async function TE(e,t){return await up(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 EE(e,t){return await up(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 dp(e,t=0){const[r,s]=e.dims,n=e.data,a=new BigInt64Array(n.length);for(let o=0;o<r;++o){const i=o*s;let l=BigInt(t);for(let c=0;c<s;++c){const d=i+c;n[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=n[d])}}return{data:a,dims:e.dims}}function AE(e,t=null,r=0){const{input_ids:s,inputs_embeds:n,attention_mask:a}=e,{data:o,dims:i}=dp(a,r);let l=new U("int64",o,i);if(t){const c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function ln(e,t,r,s){const n=r.past_key_values?r.past_key_values.get_seq_length():0,a=e.sessions.decoder_model_merged??e.sessions.model;if(a!=null&&a.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new U("int64",[1n],[])),!r.attention_mask){let o;for(const i of["input_ids","inputs_embeds","position_ids"])if(r[i]){o=r[i].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=yt([o[0],n+o[1]])}if(r.past_key_values){const{input_ids:o,attention_mask:i}=r;i&&i.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]))}return r}function Ta(e,t,r,s){return r.past_key_values&&(t=t.map(n=>[n.at(-1)])),{...r,decoder_input_ids:Ki(t)}}function Ea(e,...t){return e.config.is_encoder_decoder?Ta(e,...t):ln(e,...t)}function hp({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n}){const a=s.tolist().map(c=>c.reduce((d,h,_)=>(h==e&&d.push(_),d),[])),o=a.reduce((c,d)=>c+d.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){const d=a[c],h=t[c];for(let _=0;_<d.length;++_)h[d[_]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:n}}function rl({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:s,attention_mask:n}){return hp({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}function fp({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:s,attention_mask:n}){return hp({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}async function CE(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const n=await er(e,t[s],!1,r);return[s,n]})))}var sl={};os(sl,{ASTForAudioClassification:()=>GE,ASTModel:()=>RE,ASTPreTrainedModel:()=>il,AfmoeForCausalLM:()=>DE,AfmoeModel:()=>NE,AfmoePreTrainedModel:()=>al,AlbertForMaskedLM:()=>LE,AlbertForQuestionAnswering:()=>FE,AlbertForSequenceClassification:()=>PE,AlbertModel:()=>SE,AlbertPreTrainedModel:()=>cn,ApertusForCausalLM:()=>OE,ApertusModel:()=>IE,ApertusPreTrainedModel:()=>nl,ArceeForCausalLM:()=>BE,ArceeModel:()=>zE,ArceePreTrainedModel:()=>ol,BartForConditionalGeneration:()=>VE,BartForSequenceClassification:()=>UE,BartModel:()=>$E,BartPretrainedModel:()=>Aa,BeitForImageClassification:()=>qE,BeitModel:()=>jE,BeitPreTrainedModel:()=>ll,BertForMaskedLM:()=>HE,BertForQuestionAnswering:()=>YE,BertForSequenceClassification:()=>QE,BertForTokenClassification:()=>XE,BertModel:()=>WE,BertPreTrainedModel:()=>vs,BlenderbotForConditionalGeneration:()=>KE,BlenderbotModel:()=>JE,BlenderbotPreTrainedModel:()=>cl,BlenderbotSmallForConditionalGeneration:()=>e2,BlenderbotSmallModel:()=>ZE,BlenderbotSmallPreTrainedModel:()=>ul,BloomForCausalLM:()=>r2,BloomModel:()=>t2,BloomPreTrainedModel:()=>dl,CHMv2ForDepthEstimation:()=>u2,CHMv2PreTrainedModel:()=>wp,CLIPModel:()=>h2,CLIPPreTrainedModel:()=>Kr,CLIPSegForImageSegmentation:()=>g2,CLIPSegModel:()=>m2,CLIPSegPreTrainedModel:()=>hl,CLIPTextModel:()=>f2,CLIPTextModelWithProjection:()=>bp,CLIPVisionModel:()=>_2,CLIPVisionModelWithProjection:()=>p2,CamembertForMaskedLM:()=>n2,CamembertForQuestionAnswering:()=>i2,CamembertForSequenceClassification:()=>a2,CamembertForTokenClassification:()=>o2,CamembertModel:()=>s2,CamembertPreTrainedModel:()=>ys,ChatterboxModel:()=>mp,ChatterboxPreTrainedModel:()=>pp,ChineseCLIPModel:()=>c2,ChineseCLIPPreTrainedModel:()=>gp,ClapAudioModelWithProjection:()=>yp,ClapModel:()=>d2,ClapPreTrainedModel:()=>Ca,ClapTextModelWithProjection:()=>vp,CodeGenForCausalLM:()=>v2,CodeGenModel:()=>w2,CodeGenPreTrainedModel:()=>fl,Cohere2ForCausalLM:()=>x2,Cohere2Model:()=>M2,Cohere2PreTrainedModel:()=>pl,CohereAsrForConditionalGeneration:()=>T2,CohereAsrModel:()=>k2,CohereAsrPreTrainedModel:()=>ml,CohereForCausalLM:()=>b2,CohereModel:()=>y2,CoherePreTrainedModel:()=>_l,ConvBertForMaskedLM:()=>A2,ConvBertForQuestionAnswering:()=>P2,ConvBertForSequenceClassification:()=>C2,ConvBertForTokenClassification:()=>S2,ConvBertModel:()=>E2,ConvBertPreTrainedModel:()=>bs,ConvNextForImageClassification:()=>L2,ConvNextModel:()=>F2,ConvNextPreTrainedModel:()=>gl,ConvNextV2ForImageClassification:()=>O2,ConvNextV2Model:()=>I2,ConvNextV2PreTrainedModel:()=>wl,DFineForObjectDetection:()=>B2,DFineModel:()=>z2,DFinePreTrainedModel:()=>yl,DINOv3ConvNextModel:()=>uA,DINOv3ConvNextPreTrainedModel:()=>Pp,DINOv3ViTModel:()=>dA,DINOv3ViTPreTrainedModel:()=>Fp,DPTForDepthEstimation:()=>vA,DPTModel:()=>wA,DPTPreTrainedModel:()=>El,DacDecoderModel:()=>Tp,DacDecoderOutput:()=>xp,DacEncoderModel:()=>kp,DacEncoderOutput:()=>Mp,DacModel:()=>R2,DacPreTrainedModel:()=>Sa,DebertaForMaskedLM:()=>$2,DebertaForQuestionAnswering:()=>j2,DebertaForSequenceClassification:()=>V2,DebertaForTokenClassification:()=>U2,DebertaModel:()=>G2,DebertaPreTrainedModel:()=>Ms,DebertaV2ForMaskedLM:()=>Q2,DebertaV2ForQuestionAnswering:()=>J2,DebertaV2ForSequenceClassification:()=>X2,DebertaV2ForTokenClassification:()=>Y2,DebertaV2Model:()=>H2,DebertaV2PreTrainedModel:()=>xs,DecisionTransformerModel:()=>K2,DecisionTransformerPreTrainedModel:()=>Ep,DeepseekV3ForCausalLM:()=>W2,DeepseekV3Model:()=>q2,DeepseekV3PreTrainedModel:()=>bl,DeiTForImageClassification:()=>eA,DeiTModel:()=>Z2,DeiTPreTrainedModel:()=>Ml,DepthAnythingForDepthEstimation:()=>tA,DepthAnythingPreTrainedModel:()=>Ap,DepthProForDepthEstimation:()=>rA,DepthProPreTrainedModel:()=>Cp,DetrForObjectDetection:()=>nA,DetrForSegmentation:()=>aA,DetrModel:()=>sA,DetrObjectDetectionOutput:()=>xl,DetrPreTrainedModel:()=>Pa,DetrSegmentationOutput:()=>Sp,Dinov2ForImageClassification:()=>iA,Dinov2Model:()=>oA,Dinov2PreTrainedModel:()=>kl,Dinov2WithRegistersForImageClassification:()=>cA,Dinov2WithRegistersModel:()=>lA,Dinov2WithRegistersPreTrainedModel:()=>Tl,DistilBertForMaskedLM:()=>mA,DistilBertForQuestionAnswering:()=>pA,DistilBertForSequenceClassification:()=>fA,DistilBertForTokenClassification:()=>_A,DistilBertModel:()=>hA,DistilBertPreTrainedModel:()=>ks,DonutSwinModel:()=>gA,DonutSwinPreTrainedModel:()=>Lp,EdgeTamModel:()=>PF,EfficientNetForImageClassification:()=>bA,EfficientNetModel:()=>yA,EfficientNetPreTrainedModel:()=>Al,ElectraForMaskedLM:()=>xA,ElectraForQuestionAnswering:()=>EA,ElectraForSequenceClassification:()=>kA,ElectraForTokenClassification:()=>TA,ElectraModel:()=>MA,ElectraPreTrainedModel:()=>Ts,Ernie4_5ForCausalLM:()=>CA,Ernie4_5Model:()=>AA,Ernie4_5PretrainedModel:()=>Cl,EsmForMaskedLM:()=>PA,EsmForSequenceClassification:()=>FA,EsmForTokenClassification:()=>LA,EsmModel:()=>SA,EsmPreTrainedModel:()=>dn,EuroBertForMaskedLM:()=>OA,EuroBertForSequenceClassification:()=>NA,EuroBertForTokenClassification:()=>DA,EuroBertModel:()=>IA,EuroBertPreTrainedModel:()=>hn,ExaoneForCausalLM:()=>BA,ExaoneModel:()=>zA,ExaonePreTrainedModel:()=>Sl,FalconForCausalLM:()=>GA,FalconH1ForCausalLM:()=>VA,FalconH1Model:()=>$A,FalconH1PreTrainedModel:()=>Fl,FalconModel:()=>RA,FalconPreTrainedModel:()=>Pl,FastViTForImageClassification:()=>jA,FastViTModel:()=>UA,FastViTPreTrainedModel:()=>Ll,Florence2ForConditionalGeneration:()=>qA,Florence2PreTrainedModel:()=>Ip,GLPNForDepthEstimation:()=>lC,GLPNModel:()=>iC,GLPNPreTrainedModel:()=>Gl,GPT2LMHeadModel:()=>wC,GPT2Model:()=>gC,GPT2PreTrainedModel:()=>ql,GPTBigCodeForCausalLM:()=>uC,GPTBigCodeModel:()=>cC,GPTBigCodePreTrainedModel:()=>$l,GPTJForCausalLM:()=>yC,GPTJModel:()=>vC,GPTJPreTrainedModel:()=>Wl,GPTNeoForCausalLM:()=>hC,GPTNeoModel:()=>dC,GPTNeoPreTrainedModel:()=>Vl,GPTNeoXForCausalLM:()=>_C,GPTNeoXModel:()=>fC,GPTNeoXPreTrainedModel:()=>Ul,Gemma2ForCausalLM:()=>XA,Gemma2Model:()=>QA,Gemma2PreTrainedModel:()=>Ol,Gemma3ForCausalLM:()=>ZA,Gemma3ForConditionalGeneration:()=>Dp,Gemma3Model:()=>KA,Gemma3PreTrainedModel:()=>Np,Gemma3nForCausalLM:()=>eC,Gemma3nForConditionalGeneration:()=>Fa,Gemma3nPreTrainedModel:()=>zp,Gemma4ForCausalLM:()=>tC,Gemma4ForConditionalGeneration:()=>Nl,GemmaForCausalLM:()=>HA,GemmaModel:()=>WA,GemmaPreTrainedModel:()=>Il,GlmForCausalLM:()=>sC,GlmModel:()=>rC,GlmMoeDsaForCausalLM:()=>aC,GlmMoeDsaModel:()=>nC,GlmMoeDsaPreTrainedModel:()=>zl,GlmOcrForConditionalGeneration:()=>oC,GlmPreTrainedModel:()=>Dl,GptOssForCausalLM:()=>mC,GptOssModel:()=>pC,GptOssPreTrainedModel:()=>jl,GraniteForCausalLM:()=>MC,GraniteModel:()=>bC,GraniteMoeHybridForCausalLM:()=>kC,GraniteMoeHybridModel:()=>xC,GraniteMoeHybridPreTrainedModel:()=>Ql,GranitePreTrainedModel:()=>Hl,GraniteSpeechForConditionalGeneration:()=>TC,GroundingDinoForObjectDetection:()=>EC,GroundingDinoPreTrainedModel:()=>Vp,GroupViTModel:()=>AC,GroupViTPreTrainedModel:()=>Up,HeliumForCausalLM:()=>SC,HeliumModel:()=>CC,HeliumPreTrainedModel:()=>Yl,HieraForImageClassification:()=>FC,HieraModel:()=>PC,HieraPreTrainedModel:()=>Jl,HubertForCTC:()=>BC,HubertForSequenceClassification:()=>RC,HubertModel:()=>zC,HubertPreTrainedModel:()=>DC,HunYuanDenseV1ForCausalLM:()=>$C,HunYuanDenseV1Model:()=>GC,HunYuanDenseV1PreTrainedModel:()=>Kl,IJepaForImageClassification:()=>UC,IJepaModel:()=>VC,IJepaPreTrainedModel:()=>Zl,Idefics3ForConditionalGeneration:()=>jp,JAISLMHeadModel:()=>qC,JAISModel:()=>jC,JAISPreTrainedModel:()=>ec,JinaCLIPModel:()=>WC,JinaCLIPPreTrainedModel:()=>La,JinaCLIPTextModel:()=>qp,JinaCLIPVisionModel:()=>HC,Lfm2ForCausalLM:()=>XC,Lfm2Model:()=>QC,Lfm2MoeForCausalLM:()=>KC,Lfm2MoeModel:()=>JC,Lfm2MoePreTrainedModel:()=>rc,Lfm2PreTrainedModel:()=>tc,Lfm2VlForConditionalGeneration:()=>ZC,LightOnOcrForConditionalGeneration:()=>YC,LiteWhisperForConditionalGeneration:()=>JL,Llama4ForCausalLM:()=>rS,Llama4PreTrainedModel:()=>Wp,LlamaForCausalLM:()=>tS,LlamaModel:()=>eS,LlamaPreTrainedModel:()=>sc,LlavaForConditionalGeneration:()=>mr,LlavaOnevisionForConditionalGeneration:()=>mr,LlavaPreTrainedModel:()=>Op,LlavaQwen2ForCausalLM:()=>JA,LongT5ForConditionalGeneration:()=>nS,LongT5Model:()=>sS,LongT5PreTrainedModel:()=>nc,M2M100ForConditionalGeneration:()=>oS,M2M100Model:()=>aS,M2M100PreTrainedModel:()=>ac,MBartForCausalLM:()=>_S,MBartForConditionalGeneration:()=>hS,MBartForSequenceClassification:()=>fS,MBartModel:()=>dS,MBartPreTrainedModel:()=>fn,MPNetForMaskedLM:()=>eP,MPNetForQuestionAnswering:()=>sP,MPNetForSequenceClassification:()=>tP,MPNetForTokenClassification:()=>rP,MPNetModel:()=>ZS,MPNetPreTrainedModel:()=>Es,MT5ForConditionalGeneration:()=>iP,MT5Model:()=>oP,MT5PreTrainedModel:()=>mc,MarianMTModel:()=>lS,MarianModel:()=>iS,MarianPreTrainedModel:()=>oc,MaskFormerForInstanceSegmentation:()=>uS,MaskFormerModel:()=>cS,MaskFormerPreTrainedModel:()=>ic,Metric3DForDepthEstimation:()=>pS,Metric3DPreTrainedModel:()=>Hp,Metric3Dv2ForDepthEstimation:()=>mS,Metric3Dv2PreTrainedModel:()=>Qp,MgpstrForSceneTextRecognition:()=>gS,MgpstrModelOutput:()=>Xp,MgpstrPreTrainedModel:()=>Yp,MimiDecoderModel:()=>em,MimiDecoderOutput:()=>Kp,MimiEncoderModel:()=>Zp,MimiEncoderOutput:()=>Jp,MimiModel:()=>wS,MimiPreTrainedModel:()=>Ia,Mistral4ForCausalLM:()=>MS,Mistral4Model:()=>bS,Mistral4PreTrainedModel:()=>cc,MistralForCausalLM:()=>yS,MistralModel:()=>vS,MistralPreTrainedModel:()=>lc,MobileBertForMaskedLM:()=>kS,MobileBertForQuestionAnswering:()=>ES,MobileBertForSequenceClassification:()=>TS,MobileBertModel:()=>xS,MobileBertPreTrainedModel:()=>_n,MobileLLMForCausalLM:()=>CS,MobileLLMModel:()=>AS,MobileLLMPreTrainedModel:()=>uc,MobileNetV1ForImageClassification:()=>PS,MobileNetV1ForSemanticSegmentation:()=>FS,MobileNetV1Model:()=>SS,MobileNetV1PreTrainedModel:()=>Oa,MobileNetV2ForImageClassification:()=>IS,MobileNetV2ForSemanticSegmentation:()=>OS,MobileNetV2Model:()=>LS,MobileNetV2PreTrainedModel:()=>Na,MobileNetV3ForImageClassification:()=>DS,MobileNetV3ForSemanticSegmentation:()=>zS,MobileNetV3Model:()=>NS,MobileNetV3PreTrainedModel:()=>Da,MobileNetV4ForImageClassification:()=>RS,MobileNetV4ForSemanticSegmentation:()=>GS,MobileNetV4Model:()=>BS,MobileNetV4PreTrainedModel:()=>za,MobileViTForImageClassification:()=>VS,MobileViTModel:()=>$S,MobileViTPreTrainedModel:()=>dc,MobileViTV2ForImageClassification:()=>jS,MobileViTV2Model:()=>US,MobileViTV2PreTrainedModel:()=>hc,ModernBertDecoderForCausalLM:()=>YS,ModernBertDecoderModel:()=>XS,ModernBertDecoderPreTrainedModel:()=>fc,ModernBertForMaskedLM:()=>WS,ModernBertForSequenceClassification:()=>HS,ModernBertForTokenClassification:()=>QS,ModernBertModel:()=>qS,ModernBertPreTrainedModel:()=>pn,Moondream1ForConditionalGeneration:()=>YA,MoonshineForConditionalGeneration:()=>KS,MoonshineModel:()=>JS,MoonshinePreTrainedModel:()=>_c,MptForCausalLM:()=>aP,MptModel:()=>nP,MptPreTrainedModel:()=>pc,MultiModalityCausalLM:()=>lP,MultiModalityPreTrainedModel:()=>tm,MusicgenForCausalLM:()=>uP,MusicgenForConditionalGeneration:()=>rm,MusicgenModel:()=>cP,MusicgenPreTrainedModel:()=>gc,NanoChatForCausalLM:()=>hP,NanoChatModel:()=>dP,NanoChatPreTrainedModel:()=>wc,NemotronHForCausalLM:()=>_P,NemotronHModel:()=>fP,NemotronHPreTrainedModel:()=>vc,NeoBertForMaskedLM:()=>mP,NeoBertForQuestionAnswering:()=>vP,NeoBertForSequenceClassification:()=>gP,NeoBertForTokenClassification:()=>wP,NeoBertModel:()=>pP,NeoBertPreTrainedModel:()=>As,NomicBertModel:()=>yP,NomicBertPreTrainedModel:()=>sm,OPTForCausalLM:()=>OP,OPTModel:()=>IP,OPTPreTrainedModel:()=>Ec,Olmo2ForCausalLM:()=>kP,Olmo2Model:()=>xP,Olmo2PreTrainedModel:()=>bc,Olmo3ForCausalLM:()=>EP,Olmo3Model:()=>TP,Olmo3PreTrainedModel:()=>Mc,OlmoForCausalLM:()=>MP,OlmoHybridForCausalLM:()=>CP,OlmoHybridModel:()=>AP,OlmoHybridPreTrainedModel:()=>xc,OlmoModel:()=>bP,OlmoPreTrainedModel:()=>yc,OpenAIPrivacyFilterForTokenClassification:()=>PP,OpenAIPrivacyFilterModel:()=>SP,OpenAIPrivacyFilterPreTrainedModel:()=>kc,OpenELMForCausalLM:()=>LP,OpenELMModel:()=>FP,OpenELMPreTrainedModel:()=>Tc,OwlViTForObjectDetection:()=>BP,OwlViTModel:()=>zP,OwlViTPreTrainedModel:()=>Cc,Owlv2ForObjectDetection:()=>DP,Owlv2Model:()=>NP,Owlv2PreTrainedModel:()=>Ac,PaliGemmaForConditionalGeneration:()=>RP,ParakeetForCTC:()=>GP,ParakeetPreTrainedModel:()=>nm,PatchTSMixerForPrediction:()=>VP,PatchTSMixerModel:()=>$P,PatchTSMixerPreTrainedModel:()=>Sc,PatchTSTForPrediction:()=>jP,PatchTSTModel:()=>UP,PatchTSTPreTrainedModel:()=>Pc,Phi3ForCausalLM:()=>QP,Phi3Model:()=>HP,Phi3PreTrainedModel:()=>Lc,Phi3VForCausalLM:()=>om,Phi3VPreTrainedModel:()=>am,PhiForCausalLM:()=>WP,PhiModel:()=>qP,PhiPreTrainedModel:()=>Fc,PreTrainedModel:()=>P,PvtForImageClassification:()=>YP,PvtModel:()=>XP,PvtPreTrainedModel:()=>Ic,PyAnnoteForAudioFrameClassification:()=>KP,PyAnnoteModel:()=>JP,PyAnnotePreTrainedModel:()=>Oc,Qwen2ForCausalLM:()=>eF,Qwen2Model:()=>ZP,Qwen2MoeForCausalLM:()=>rF,Qwen2MoeModel:()=>tF,Qwen2MoePreTrainedModel:()=>Dc,Qwen2PreTrainedModel:()=>Nc,Qwen2VLForCausalLM:()=>Rp,Qwen2VLForConditionalGeneration:()=>Bl,Qwen2VLPreTrainedModel:()=>Bp,Qwen2_5_VLForCausalLM:()=>Gp,Qwen2_5_VLForConditionalGeneration:()=>Rl,Qwen3ForCausalLM:()=>nF,Qwen3Model:()=>sF,Qwen3MoeForCausalLM:()=>oF,Qwen3MoeModel:()=>aF,Qwen3MoePreTrainedModel:()=>Bc,Qwen3NextForCausalLM:()=>lF,Qwen3NextModel:()=>iF,Qwen3NextPreTrainedModel:()=>Rc,Qwen3PreTrainedModel:()=>zc,Qwen3VLForCausalLM:()=>im,Qwen3VLForConditionalGeneration:()=>Gc,Qwen3VLMoeForCausalLM:()=>uF,Qwen3VLMoeForConditionalGeneration:()=>cF,Qwen3_5ForCausalLM:()=>lm,Qwen3_5ForConditionalGeneration:()=>$c,Qwen3_5MoeForCausalLM:()=>hF,Qwen3_5MoeForConditionalGeneration:()=>dF,RFDetrForObjectDetection:()=>mF,RFDetrModel:()=>pF,RFDetrObjectDetectionOutput:()=>cm,RFDetrPreTrainedModel:()=>Uc,RTDetrForObjectDetection:()=>D2,RTDetrModel:()=>N2,RTDetrObjectDetectionOutput:()=>un,RTDetrPreTrainedModel:()=>vl,RTDetrV2ForObjectDetection:()=>CF,RTDetrV2Model:()=>AF,RTDetrV2ObjectDetectionOutput:()=>um,RTDetrV2PreTrainedModel:()=>jc,ResNetForImageClassification:()=>_F,ResNetModel:()=>fF,ResNetPreTrainedModel:()=>Vc,RoFormerForMaskedLM:()=>xF,RoFormerForQuestionAnswering:()=>EF,RoFormerForSequenceClassification:()=>kF,RoFormerForTokenClassification:()=>TF,RoFormerModel:()=>MF,RoFormerPreTrainedModel:()=>Ss,RobertaForMaskedLM:()=>wF,RobertaForQuestionAnswering:()=>bF,RobertaForSequenceClassification:()=>vF,RobertaForTokenClassification:()=>yF,RobertaModel:()=>gF,RobertaPreTrainedModel:()=>Cs,Sam2ImageSegmentationOutput:()=>fm,Sam2Model:()=>qc,Sam2PreTrainedModel:()=>_m,Sam3TrackerModel:()=>FF,SamImageSegmentationOutput:()=>dm,SamModel:()=>SF,SamPreTrainedModel:()=>hm,SapiensForDepthEstimation:()=>IF,SapiensForNormalEstimation:()=>OF,SapiensForSemanticSegmentation:()=>LF,SapiensPreTrainedModel:()=>Ba,SegformerForImageClassification:()=>DF,SegformerForSemanticSegmentation:()=>zF,SegformerModel:()=>NF,SegformerPreTrainedModel:()=>Ra,SiglipModel:()=>BF,SiglipPreTrainedModel:()=>Wc,SiglipTextModel:()=>pm,SiglipVisionModel:()=>RF,SmolLM3ForCausalLM:()=>$F,SmolLM3Model:()=>GF,SmolLM3PreTrainedModel:()=>Hc,SmolVLMForConditionalGeneration:()=>VF,SnacDecoderModel:()=>gm,SnacEncoderModel:()=>mm,SnacModel:()=>UF,SnacPreTrainedModel:()=>Ga,SolarOpenForCausalLM:()=>qF,SolarOpenModel:()=>jF,SolarOpenPreTrainedModel:()=>Qc,SpeechT5ForSpeechToText:()=>HF,SpeechT5ForTextToSpeech:()=>QF,SpeechT5HifiGan:()=>XF,SpeechT5Model:()=>WF,SpeechT5PreTrainedModel:()=>$a,SqueezeBertForMaskedLM:()=>JF,SqueezeBertForQuestionAnswering:()=>ZF,SqueezeBertForSequenceClassification:()=>KF,SqueezeBertModel:()=>YF,SqueezeBertPreTrainedModel:()=>mn,StableLmForCausalLM:()=>tL,StableLmModel:()=>eL,StableLmPreTrainedModel:()=>Xc,Starcoder2ForCausalLM:()=>sL,Starcoder2Model:()=>rL,Starcoder2PreTrainedModel:()=>Yc,StyleTextToSpeech2Model:()=>nL,StyleTextToSpeech2PreTrainedModel:()=>wm,SupertonicForConditionalGeneration:()=>ym,SupertonicPreTrainedModel:()=>vm,Swin2SRForImageSuperResolution:()=>cL,Swin2SRModel:()=>lL,Swin2SRPreTrainedModel:()=>Jc,SwinForImageClassification:()=>oL,SwinForSemanticSegmentation:()=>iL,SwinModel:()=>aL,SwinPreTrainedModel:()=>Va,T5ForConditionalGeneration:()=>dL,T5Model:()=>uL,T5PreTrainedModel:()=>Kc,TableTransformerForObjectDetection:()=>fL,TableTransformerModel:()=>hL,TableTransformerObjectDetectionOutput:()=>bm,TableTransformerPreTrainedModel:()=>Zc,TrOCRForCausalLM:()=>_L,TrOCRPreTrainedModel:()=>Mm,UltravoxModel:()=>Xl,UltravoxPreTrainedModel:()=>$p,UniSpeechForCTC:()=>mL,UniSpeechForSequenceClassification:()=>gL,UniSpeechModel:()=>pL,UniSpeechPreTrainedModel:()=>Ua,UniSpeechSatForAudioFrameClassification:()=>bL,UniSpeechSatForCTC:()=>vL,UniSpeechSatForSequenceClassification:()=>yL,UniSpeechSatModel:()=>wL,UniSpeechSatPreTrainedModel:()=>gn,VaultGemmaForCausalLM:()=>xL,VaultGemmaModel:()=>ML,VaultGemmaPreTrainedModel:()=>eu,ViTForImageClassification:()=>EL,ViTMAEModel:()=>AL,ViTMAEPreTrainedModel:()=>xm,ViTMSNForImageClassification:()=>SL,ViTMSNModel:()=>CL,ViTMSNPreTrainedModel:()=>ru,ViTModel:()=>TL,ViTPreTrainedModel:()=>tu,VisionEncoderDecoderModel:()=>kL,VitMatteForImageMatting:()=>PL,VitMattePreTrainedModel:()=>km,VitPoseForPoseEstimation:()=>FL,VitPosePreTrainedModel:()=>Tm,VitsModel:()=>LL,VitsModelOutput:()=>Em,VitsPreTrainedModel:()=>Am,VoxtralForConditionalGeneration:()=>IL,VoxtralRealtimeForConditionalGeneration:()=>Pm,VoxtralRealtimePreTrainedModel:()=>Sm,Wav2Vec2BertForCTC:()=>$L,Wav2Vec2BertForSequenceClassification:()=>VL,Wav2Vec2BertModel:()=>GL,Wav2Vec2BertPreTrainedModel:()=>ja,Wav2Vec2ForAudioFrameClassification:()=>NC,Wav2Vec2ForCTC:()=>IC,Wav2Vec2ForSequenceClassification:()=>OC,Wav2Vec2Model:()=>LC,Wav2Vec2PreTrainedModel:()=>Nr,WavLMForAudioFrameClassification:()=>HL,WavLMForCTC:()=>jL,WavLMForSequenceClassification:()=>qL,WavLMForXVector:()=>WL,WavLMModel:()=>UL,WavLMPreTrainedModel:()=>Ps,WeSpeakerResNetModel:()=>QL,WeSpeakerResNetPreTrainedModel:()=>Lm,WhisperForConditionalGeneration:()=>Im,WhisperModel:()=>YL,WhisperPreTrainedModel:()=>nu,XLMForQuestionAnswering:()=>rI,XLMForSequenceClassification:()=>eI,XLMForTokenClassification:()=>tI,XLMModel:()=>KL,XLMPreTrainedModel:()=>Fs,XLMRobertaForMaskedLM:()=>nI,XLMRobertaForQuestionAnswering:()=>iI,XLMRobertaForSequenceClassification:()=>aI,XLMRobertaForTokenClassification:()=>oI,XLMRobertaModel:()=>sI,XLMRobertaPreTrainedModel:()=>Ls,XLMWithLMHeadModel:()=>ZL,XVectorOutput:()=>Fm,YolosForObjectDetection:()=>cI,YolosModel:()=>lI,YolosObjectDetectionOutput:()=>Om,YolosPreTrainedModel:()=>au,YoutuForCausalLM:()=>dI,YoutuModel:()=>uI,YoutuPreTrainedModel:()=>ou});var cn=class extends P{},SE=class extends cn{},PE=class extends cn{async _call(e){return new ne(await super._call(e))}},FE=class extends cn{async _call(e){return new ht(await super._call(e))}},LE=class extends cn{async _call(e){return new Je(await super._call(e))}},nl=class extends P{},IE=class extends nl{},OE=class extends nl{},al=class extends P{},NE=class extends al{},DE=class extends al{},ol=class extends P{},zE=class extends ol{},BE=class extends ol{},il=class extends P{},RE=class extends il{},GE=class extends il{},Aa=class extends P{},$E=class extends Aa{},VE=class extends Aa{},UE=class extends Aa{async _call(e){return new ne(await super._call(e))}},ll=class extends P{},jE=class extends ll{},qE=class extends ll{async _call(e){return new ne(await super._call(e))}},vs=class extends P{},WE=class extends vs{},HE=class extends vs{async _call(e){return new Je(await super._call(e))}},QE=class extends vs{async _call(e){return new ne(await super._call(e))}},XE=class extends vs{async _call(e){return new He(await super._call(e))}},YE=class extends vs{async _call(e){return new ht(await super._call(e))}},cl=class extends P{},JE=class extends cl{},KE=class extends cl{},ul=class extends P{},ZE=class extends ul{},e2=class extends ul{},dl=class extends P{},t2=class extends dl{},r2=class extends dl{},ys=class extends P{},s2=class extends ys{},n2=class extends ys{async _call(e){return new Je(await super._call(e))}},a2=class extends ys{async _call(e){return new ne(await super._call(e))}},o2=class extends ys{async _call(e){return new He(await super._call(e))}},i2=class extends ys{async _call(e){return new ht(await super._call(e))}},l2=4299n,_p=6561n,pp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);k(this,"main_input_name","input_ids");k(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},mp=class extends pp{async encode_speech(e){return xe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:c=null,audio_tokens:d=null,speaker_embeddings:h=null,speaker_features:_=null,...p}){let w;if(!a){const y=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(y.includes("exaggeration")){if(!(s instanceof U)){const T=e.dims[0];if(s==null)s=ct([T],.5);else if(typeof s=="number")s=ct([T],s);else if(Array.isArray(s))s=new U("float32",s,[T]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=s}if(y.includes("position_ids")&&(M.position_ids=n),{inputs_embeds:a}=await xe(this.sessions.embed_tokens,M),c&&d&&h&&_&&(w={audio_features:c,audio_tokens:d,speaker_embeddings:h,speaker_features:_}),w||r)w??(w=await this.encode_speech(r)),a=ze([w.audio_features,a],1),t=yt([a.dims[0],a.dims[1]]);else{const T=a.dims[1];if(!o||T!==1)throw new Error("Incorrect state encountered during generation.");const A=o.get_seq_length();t=yt([a.dims[0],A+T])}}return{...await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...w}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const s=Array.from({length:e.length},(n,a)=>e[a].length-e[a].findLastIndex(o=>o==_p)-1);t.position_ids=new U("int64",s,[e.length,1])}else{const n=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=_p?0:o++)});t.position_ids=new U("int64",n.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ln(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:s,speaker_features:n}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=ct([a.dims[0],3],l2),i=ze([r,a,o],1),{waveform:l}=await xe(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:n,speaker_embeddings:s});return l}},gp=class extends P{},c2=class extends gp{},wp=class extends P{},u2=class extends wp{},Ca=class extends P{},d2=class extends Ca{},vp=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},yp=class extends Ca{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Kr=class extends P{},h2=class extends Kr{},f2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},bp=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},p2=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},hl=class extends P{},m2=class extends hl{},g2=class extends hl{},fl=class extends P{},w2=class extends fl{},v2=class extends fl{},_l=class extends P{},y2=class extends _l{},b2=class extends _l{},pl=class extends P{},M2=class extends pl{},x2=class extends pl{},ml=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"])}},k2=class extends ml{},T2=class extends ml{},bs=class extends P{},E2=class extends bs{},A2=class extends bs{async _call(e){return new Je(await super._call(e))}},C2=class extends bs{async _call(e){return new ne(await super._call(e))}},S2=class extends bs{async _call(e){return new He(await super._call(e))}},P2=class extends bs{async _call(e){return new ht(await super._call(e))}},gl=class extends P{},F2=class extends gl{},L2=class extends gl{async _call(e){return new ne(await super._call(e))}},wl=class extends P{},I2=class extends wl{},O2=class extends wl{async _call(e){return new ne(await super._call(e))}},vl=class extends P{},N2=class extends vl{},D2=class extends vl{async _call(e){return new un(await super._call(e))}},un=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},yl=class extends P{},z2=class extends yl{},B2=class extends yl{async _call(e){return new un(await super._call(e))}},Mp=class extends Ye{constructor({audio_codes:e}){super(),this.audio_codes=e}},xp=class extends Ye{constructor({audio_values:e}){super(),this.audio_values=e}},Sa=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},R2=class extends Sa{async encode(e){return new Mp(await xe(this.sessions.encoder_model,e))}async decode(e){return new xp(await xe(this.sessions.decoder_model,e))}},kp=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Tp=class extends Sa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Ms=class extends P{},G2=class extends Ms{},$2=class extends Ms{async _call(e){return new Je(await super._call(e))}},V2=class extends Ms{async _call(e){return new ne(await super._call(e))}},U2=class extends Ms{async _call(e){return new He(await super._call(e))}},j2=class extends Ms{async _call(e){return new ht(await super._call(e))}},bl=class extends P{},q2=class extends bl{},W2=class extends bl{},xs=class extends P{},H2=class extends xs{},Q2=class extends xs{async _call(e){return new Je(await super._call(e))}},X2=class extends xs{async _call(e){return new ne(await super._call(e))}},Y2=class extends xs{async _call(e){return new He(await super._call(e))}},J2=class extends xs{async _call(e){return new ht(await super._call(e))}},Ep=class extends P{},K2=class extends Ep{},Ml=class extends P{},Z2=class extends Ml{},eA=class extends Ml{async _call(e){return new ne(await super._call(e))}},Ap=class extends P{},tA=class extends Ap{},Cp=class extends P{},rA=class extends Cp{},Pa=class extends P{},sA=class extends Pa{},nA=class extends Pa{async _call(e){return new xl(await super._call(e))}},aA=class extends Pa{async _call(e){return new Sp(await super._call(e))}},xl=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Sp=class extends Ye{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},kl=class extends P{},oA=class extends kl{},iA=class extends kl{async _call(e){return new ne(await super._call(e))}},Tl=class extends P{},lA=class extends Tl{},cA=class extends Tl{async _call(e){return new ne(await super._call(e))}},Pp=class extends P{},uA=class extends Pp{},Fp=class extends P{},dA=class extends Fp{},ks=class extends P{},hA=class extends ks{},fA=class extends ks{async _call(e){return new ne(await super._call(e))}},_A=class extends ks{async _call(e){return new He(await super._call(e))}},pA=class extends ks{async _call(e){return new ht(await super._call(e))}},mA=class extends ks{async _call(e){return new Je(await super._call(e))}},Lp=class extends P{},gA=class extends Lp{},El=class extends P{},wA=class extends El{},vA=class extends El{},Al=class extends P{},yA=class extends Al{},bA=class extends Al{async _call(e){return new ne(await super._call(e))}},Ts=class extends P{},MA=class extends Ts{},xA=class extends Ts{async _call(e){return new Je(await super._call(e))}},kA=class extends Ts{async _call(e){return new ne(await super._call(e))}},TA=class extends Ts{async _call(e){return new He(await super._call(e))}},EA=class extends Ts{async _call(e){return new ht(await super._call(e))}},Cl=class extends P{},AA=class extends Cl{},CA=class extends Cl{},dn=class extends P{},SA=class extends dn{},PA=class extends dn{async _call(e){return new Je(await super._call(e))}},FA=class extends dn{async _call(e){return new ne(await super._call(e))}},LA=class extends dn{async _call(e){return new He(await super._call(e))}},hn=class extends P{},IA=class extends hn{},OA=class extends hn{async _call(e){return new Je(await super._call(e))}},NA=class extends hn{async _call(e){return new ne(await super._call(e))}},DA=class extends hn{async _call(e){return new He(await super._call(e))}},Sl=class extends P{},zA=class extends Sl{},BA=class extends Sl{},Pl=class extends P{},RA=class extends Pl{},GA=class extends Pl{},Fl=class extends P{},$A=class extends Fl{},VA=class extends Fl{},Ll=class extends P{},UA=class extends Ll{},jA=class extends Ll{async _call(e){return new ne(await super._call(e))}},Ip=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);k(this,"main_input_name","inputs_embeds")}},qA=class extends Ip{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:s}){return{inputs_embeds:ze([t,e],1),attention_mask:ze([yt(t.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:s}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,a;return e&&(n=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),n&&a?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:a,input_ids:e,attention_mask:s}):r=n||a,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:n,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:d}=await Or(this,{inputs_embeds:i,attention_mask:r});a=d}if(!l){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:s})}return await pr(this,{inputs_embeds:l,attention_mask:n,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},Il=class extends P{},WA=class extends Il{},HA=class extends Il{},Ol=class extends P{},QA=class extends Ol{},XA=class extends Ol{},Op=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},mr=class extends Op{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return rl({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},YA=class extends mr{},JA=class extends mr{},Np=class extends P{},KA=class extends Np{},Dp=class extends mr{},ZA=class extends Dp{},zp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},Fa=class extends zp{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:s=null,input_features_mask:n=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,...h}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await xe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:p}=await this._encode_vision({pixel_values:r,...h});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(s){const{audio_features:p}=await xe(this.sessions.audio_encoder,{input_features:s,input_features_mask:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await pr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d},!0)}_encode_vision(e){return xe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return rl({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return fp({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},eC=class extends Fa{},Nl=class extends Fa{constructor(){super(...arguments);k(this,"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(t){return xe(this.sessions.vision_encoder,{pixel_values:t.pixel_values,pixel_position_ids:t.image_position_ids})}},tC=class extends Nl{},Dl=class extends P{},rC=class extends Dl{},sC=class extends Dl{},zl=class extends P{},nC=class extends zl{},aC=class extends zl{},Bp=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},Bl=class extends Bp{constructor(){super(...arguments);k(this,"image_grid_thw_name","grid_thw")}_get_text_only_rope_index(t,r){if(r){const{data:s,dims:n}=dp(r),a=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),o=Array.from({length:n[0]},(i,l)=>je(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new U("int64",a,[3,...n]),new U("int64",o,[o.length,1])]}else{const[s,n]=t.dims,a=BigInt64Array.from({length:3*s*n},(o,i)=>BigInt(Math.floor(i%n/s)));return[new U("int64",a,[3,...t.dims]),Kf([s,1])]}}_reorder_and_write_positions(t,r,s,n){const a=t.reduce((c,d)=>c+d.length,0),o=new Array(a);let i=0;for(let c=0;c<3;++c)for(const d of t){const h=d.length/3;for(let _=c*h;_<(c+1)*h;++_)o[i++]=d[_]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let d=0;d<3;++d)s[d][n][c]=o[d*a/3+l];++l}return o}_get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:a}){const{image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,c=t,h=c.reduce((T,A,S)=>(A==l&&T.push(S),T),[]).map(T=>c[T+1]),_=h.filter(T=>T==o).length,p=h.filter(T=>T==i).length,w=[];let v=0,y=_,M=p;for(let T=0;T<h.length;++T){const A=c.findIndex((X,J)=>J>v&&X==o),S=c.findIndex((X,J)=>J>v&&X==i),C=y>0&&A!==-1?A:c.length+1,I=M>0&&S!==-1?S:c.length+1;let x,R,z,$;C<I?([R,z,$]=r[a.image_index],++a.image_index,--y,x=C):([R,z,$]=s[a.video_index],++a.video_index,--M,x=I);const[Q,H,D]=[Number(R),Math.floor(Number(z)/n),Math.floor(Number($)/n)],O=x-v,te=w.length>0?je(w.at(-1))[0]+1:0;w.push(Array.from({length:3*O},(X,J)=>te+J%O));const W=O+te,ee=Q*H*D,G=Array.from({length:ee},(X,J)=>W+Math.floor(J/(H*D))),L=Array.from({length:ee},(X,J)=>W+Math.floor(J/D)%H),V=Array.from({length:ee},(X,J)=>W+J%D);w.push([G,L,V].flat()),v=x+ee}if(v<c.length){const T=w.length>0?je(w.at(-1))[0]+1:0,A=c.length-v;w.push(Array.from({length:3*A},(S,C)=>T+C%A))}return w}get_rope_index(t,r,s,n){const{vision_config:a}=this.config,o=a.spatial_merge_size??2;if(r||s){const i=t.tolist();n||(n=Jf(t));const l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:t.dims[0]},()=>Array.from({length:t.dims[1]},()=>0))),d=r?r.tolist():[],h=s?s.tolist():[],_={image_index:0,video_index:0},p=[];for(let w=0;w<i.length;++w){const v=i[w].filter((T,A)=>l[w][A]==1),y=this._get_multimodal_rope_positions({filtered_ids:v,image_grid_thw_list:d,video_grid_thw_list:h,spatial_merge_size:o,state:_}),M=this._reorder_and_write_positions(y,l[w],c,w);p.push(je(M)[0]+1-i[w].length)}return[new U("int64",c.flat(1/0),[3,t.dims[0],t.dims[1]]),new U("int64",p,[p.length,1])]}else return this._get_text_only_rope_index(t,n)}async encode_image({pixel_values:t,image_grid_thw:r}){return(await xe(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return rl({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,s){if(!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;const a=r.past_key_values.get_seq_length();if(a<r.input_ids.dims[1]){const[o,i]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=i,r.position_ids=o.slice(null,null,[a,null]),r.input_ids=r.input_ids.slice(null,[a,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));const o=BigInt(a),i=r.rope_deltas.map(l=>o+l);r.position_ids=dr([i,i,i],0)}}return r}},Rp=class extends Bl{},Rl=class extends Bl{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw")}},Gp=class extends Rp{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw")}},oC=class extends Rl{get_vision_position_ids(e,t,r,s){const n=Math.floor(t[0]/r),a=Math.floor(t[1]/s),o=Math.floor(t[2]/s),i=a*o*n,l=Array.from({length:i},()=>e),c=Array.from({length:i},(h,_)=>e+Math.floor(_/(o*n))),d=Array.from({length:i},(h,_)=>e+_%o);return[...l,...c,...d]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:s,state:n}){const{image_token_id:a}=this.config,o=[];let i=0,l=e[0]==a?1:0;for(let h=1;h<=e.length;++h){const _=h<e.length?e[h]==a?1:0:-1;_!==l&&(o.push([l,i,h]),i=h,l=_)}let c=0;const d=[];for(const[h,_,p]of o)if(h===0){const w=p-_;d.push(Array.from({length:3*w},(v,y)=>c+y%w)),c+=w}else{const w=t[n.image_index++].map(Number),v=w[0];d.push(this.get_vision_position_ids(c,w,v,s)),c+=Math.max(w[1],w[2])/s}return d}},Gl=class extends P{},iC=class extends Gl{},lC=class extends Gl{},$l=class extends P{},cC=class extends $l{},uC=class extends $l{},Vl=class extends P{},dC=class extends Vl{},hC=class extends Vl{},Ul=class extends P{},fC=class extends Ul{},_C=class extends Ul{},jl=class extends P{},pC=class extends jl{},mC=class extends jl{},ql=class extends P{},gC=class extends ql{},wC=class extends ql{},Wl=class extends P{},vC=class extends Wl{},yC=class extends Wl{},Hl=class extends P{},bC=class extends Hl{},MC=class extends Hl{},Ql=class extends P{},xC=class extends Ql{},kC=class extends Ql{},$p=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}},Xl=class extends $p{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return fp({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},TC=class extends Xl{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","input_features","past_key_values"])}},Vp=class extends P{},EC=class extends Vp{},Up=class extends P{},AC=class extends Up{},Yl=class extends P{},CC=class extends Yl{},SC=class extends Yl{},Jl=class extends P{},PC=class extends Jl{},FC=class extends Jl{async _call(e){return new ne(await super._call(e))}},Nr=class extends P{},LC=class extends Nr{},IC=class extends Nr{async _call(e){return new Jr(await super._call(e))}},OC=class extends Nr{async _call(e){return new ne(await super._call(e))}},NC=class extends Nr{async _call(e){return new He(await super._call(e))}},DC=class extends P{},zC=class extends Nr{},BC=class extends Nr{async _call(e){return new Jr(await super._call(e))}},RC=class extends Nr{async _call(e){return new ne(await super._call(e))}},Kl=class extends P{},GC=class extends Kl{},$C=class extends Kl{},jp=class extends mr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},Zl=class extends P{},VC=class extends Zl{},UC=class extends Zl{async _call(e){return new ne(await super._call(e))}},ec=class extends P{},jC=class extends ec{},qC=class extends ec{},La=class extends P{},WC=class extends La{async forward(e){const t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=yt([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=ct([0,3,l,l],0)}const{text_embeddings:s,image_embeddings:n,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=s,i.l2norm_text_embeddings=a),r||(i.image_embeddings=n,i.l2norm_image_embeddings=o),i}},qp=class extends La{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},HC=class extends La{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},tc=class extends P{},QC=class extends tc{},XC=class extends tc{},YC=class extends mr{},rc=class extends P{},JC=class extends rc{},KC=class extends rc{},ZC=class extends mr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"])}},sc=class extends P{},eS=class extends sc{},tS=class extends sc{},Wp=class extends P{},rS=class extends Wp{},nc=class extends P{},sS=class extends nc{},nS=class extends nc{},ac=class extends P{},aS=class extends ac{},oS=class extends ac{},oc=class extends P{},iS=class extends oc{},lS=class extends oc{},ic=class extends P{},cS=class extends ic{},uS=class extends ic{},fn=class extends P{},dS=class extends fn{},hS=class extends fn{},fS=class extends fn{async _call(e){return new ne(await super._call(e))}},_S=class extends fn{},Hp=class extends P{},pS=class extends Hp{},Qp=class extends P{},mS=class extends Qp{},Xp=class extends Ye{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Yp=class extends P{},gS=class extends Yp{async _call(e){return new Xp(await super._call(e))}},Jp=class extends Ye{constructor({audio_codes:e}){super(),this.audio_codes=e}},Kp=class extends Ye{constructor({audio_values:e}){super(),this.audio_values=e}},Ia=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},wS=class extends Ia{async encode(e){return new Jp(await xe(this.sessions.encoder_model,e))}async decode(e){return new Kp(await xe(this.sessions.decoder_model,e))}},Zp=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},em=class extends Ia{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},lc=class extends P{},vS=class extends lc{},yS=class extends lc{},cc=class extends P{},bS=class extends cc{},MS=class extends cc{},_n=class extends P{},xS=class extends _n{},kS=class extends _n{async _call(e){return new Je(await super._call(e))}},TS=class extends _n{async _call(e){return new ne(await super._call(e))}},ES=class extends _n{async _call(e){return new ht(await super._call(e))}},uc=class extends P{},AS=class extends uc{},CS=class extends uc{},Oa=class extends P{},SS=class extends Oa{},PS=class extends Oa{async _call(e){return new ne(await super._call(e))}},FS=class extends Oa{},Na=class extends P{},LS=class extends Na{},IS=class extends Na{async _call(e){return new ne(await super._call(e))}},OS=class extends Na{},Da=class extends P{},NS=class extends Da{},DS=class extends Da{async _call(e){return new ne(await super._call(e))}},zS=class extends Da{},za=class extends P{},BS=class extends za{},RS=class extends za{async _call(e){return new ne(await super._call(e))}},GS=class extends za{},dc=class extends P{},$S=class extends dc{},VS=class extends dc{async _call(e){return new ne(await super._call(e))}},hc=class extends P{},US=class extends hc{},jS=class extends hc{async _call(e){return new ne(await super._call(e))}},pn=class extends P{},qS=class extends pn{},WS=class extends pn{async _call(e){return new Je(await super._call(e))}},HS=class extends pn{async _call(e){return new ne(await super._call(e))}},QS=class extends pn{async _call(e){return new He(await super._call(e))}},fc=class extends P{},XS=class extends fc{},YS=class extends fc{},_c=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},JS=class extends _c{},KS=class extends _c{},Es=class extends P{},ZS=class extends Es{},eP=class extends Es{async _call(e){return new Je(await super._call(e))}},tP=class extends Es{async _call(e){return new ne(await super._call(e))}},rP=class extends Es{async _call(e){return new He(await super._call(e))}},sP=class extends Es{async _call(e){return new ht(await super._call(e))}},pc=class extends P{},nP=class extends pc{},aP=class extends pc{},mc=class extends P{},oP=class extends mc{},iP=class extends mc{},tm=class extends P{},lP=class extends tm{constructor(...t){super(...t);k(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(t){const r=this._generation_mode??"text";let s;if(r==="text"||!t.past_key_values){const l=this.sessions.prepare_inputs_embeds,c=Ze(t,l.inputNames);s=await xe(l,c)}else{const l=this.sessions.gen_img_embeds,c=Ze({image_ids:t.input_ids},l.inputNames);s=await xe(l,c)}const n={...t,...s},a=await pr(this,n),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await xe(o,Ze(a,o.inputNames));return{...s,...a,...i}}prepare_inputs_for_generation(t,r,s){const n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=ze([r.input_ids,r.input_ids],0):(r.input_ids=ze([r.input_ids,Li(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ze([r.attention_mask,Li(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=ct([0,0,3,384,384],1)),n&&(r.images_seq_mask=new U("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new U("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(t){return this._generation_mode="text",super.generate(t)}async generate_images(t){this._generation_mode="image";const r=(t.inputs??t[this.main_input_name]).dims[1],n=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await xe(a,{generated_tokens:n}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(const c of i){const d=qt.fromTensor(c);l.push(d)}return l}},gc=class extends P{},cP=class extends gc{},uP=class extends gc{},rm=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(t){const[r,s]=t.dims,n=this.config.decoder.num_codebooks,a=s-n;let o=0;for(let c=0;c<t.size;++c){if(t.data[c]==this.config.decoder.pad_token_id)continue;const d=c%s,h=Math.floor(c/s)%n,_=d-h;_>0&&_<=a&&(t.data[o++]=t.data[c])}const i=Math.floor(r/n),l=o/(i*n);return new U(t.type,t.data.slice(0,o),[i,n,l])}prepare_inputs_for_generation(t,r,s){const n=BigInt(this.config.decoder.pad_token_id);let a=structuredClone(t);for(let o=0;o<a.length;++o)for(let i=0;i<a[o].length;++i)o%this.config.decoder.num_codebooks>=i&&(a[o][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(a=a.concat(a)),Ta(this,a,r)}async generate(t){const r=await super.generate(t),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await xe(this.sessions.encodec_decode,{audio_codes:s});return n}},wc=class extends P{},dP=class extends wc{},hP=class extends wc{},vc=class extends P{},fP=class extends vc{},_P=class extends vc{},As=class extends P{},pP=class extends As{},mP=class extends As{async _call(e){return new Je(await super._call(e))}},gP=class extends As{async _call(e){return new ne(await super._call(e))}},wP=class extends As{async _call(e){return new He(await super._call(e))}},vP=class extends As{async _call(e){return new ht(await super._call(e))}},sm=class extends P{},yP=class extends sm{},yc=class extends P{},bP=class extends yc{},MP=class extends yc{},bc=class extends P{},xP=class extends bc{},kP=class extends bc{},Mc=class extends P{},TP=class extends Mc{},EP=class extends Mc{},xc=class extends P{},AP=class extends xc{},CP=class extends xc{},kc=class extends P{},SP=class extends kc{},PP=class extends kc{async _call(e){return new ne(await super._call(e))}},Tc=class extends P{},FP=class extends Tc{},LP=class extends Tc{},Ec=class extends P{},IP=class extends Ec{},OP=class extends Ec{},Ac=class extends P{},NP=class extends Ac{},DP=class extends Ac{},Cc=class extends P{},zP=class extends Cc{},BP=class extends Cc{},RP=class extends mr{},nm=class extends P{},GP=class extends nm{async _call(e){return new Jr(await super._call(e))}},Sc=class extends P{},$P=class extends Sc{},VP=class extends Sc{},Pc=class extends P{},UP=class extends Pc{},jP=class extends Pc{},Fc=class extends P{},qP=class extends Fc{},WP=class extends Fc{},Lc=class extends P{},HP=class extends Lc{},QP=class extends Lc{},am=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},om=class extends am{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!a){let h;if(r&&e.dims[1]!==1){if(!s)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:h}=await xe(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}))}else{const _=this.config.normalized_config.hidden_size;h=new U("float32",[],[0,_])}({inputs_embeds:a}=await xe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:h}))}return await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:n,generation_config:i,logits_processor:l},!1)}},Ic=class extends P{},XP=class extends Ic{},YP=class extends Ic{async _call(e){return new ne(await super._call(e))}},Oc=class extends P{},JP=class extends Oc{},KP=class extends Oc{async _call(e){return new He(await super._call(e))}},Nc=class extends P{},ZP=class extends Nc{},eF=class extends Nc{},Dc=class extends P{},tF=class extends Dc{},rF=class extends Dc{},zc=class extends P{},sF=class extends zc{},nF=class extends zc{},Bc=class extends P{},aF=class extends Bc{},oF=class extends Bc{},Rc=class extends P{},iF=class extends Rc{},lF=class extends Rc{},Gc=class extends Rl{},im=class extends Gp{},cF=class extends Gc{},uF=class extends im{},$c=class extends Gc{},lm=class extends $c{},dF=class extends $c{},hF=class extends lm{},Vc=class extends P{},fF=class extends Vc{},_F=class extends Vc{async _call(e){return new ne(await super._call(e))}},Uc=class extends P{},pF=class extends Uc{},mF=class extends Uc{async _call(e){return new cm(await super._call(e))}},cm=class extends un{},Cs=class extends P{},gF=class extends Cs{},wF=class extends Cs{async _call(e){return new Je(await super._call(e))}},vF=class extends Cs{async _call(e){return new ne(await super._call(e))}},yF=class extends Cs{async _call(e){return new He(await super._call(e))}},bF=class extends Cs{async _call(e){return new ht(await super._call(e))}},Ss=class extends P{},MF=class extends Ss{},xF=class extends Ss{async _call(e){return new Je(await super._call(e))}},kF=class extends Ss{async _call(e){return new ne(await super._call(e))}},TF=class extends Ss{async _call(e){return new He(await super._call(e))}},EF=class extends Ss{async _call(e){return new ht(await super._call(e))}},jc=class extends P{},AF=class extends jc{},CF=class extends jc{async _call(e){return new um(await super._call(e))}},um=class extends un{},dm=class extends Ye{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},hm=class extends P{},SF=class extends hm{async get_image_embeddings({pixel_values:e}){return await Or(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??(e.input_labels=yt(e.input_points.dims.slice(0,-1)));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await xe(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new dm(await super._call(e))}},fm=class extends Ye{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},_m=class extends P{},qc=class extends _m{async get_image_embeddings({pixel_values:e}){return await Or(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const a=e.input_points.dims;e.input_labels??(e.input_labels=yt(a.slice(0,-1))),e.input_boxes??(e.input_boxes=ct([a[0],0,4],0))}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=ct([a[0],a[1],0],-1n),e.input_points=ct([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const s=this.sessions.prompt_encoder_mask_decoder,n=Ze(e,s.inputNames);return await xe(s,n)}async _call(e){return new fm(await super._call(e))}},PF=class extends qc{},FF=class extends qc{},Ba=class extends P{},LF=class extends Ba{},IF=class extends Ba{},OF=class extends Ba{},Ra=class extends P{},NF=class extends Ra{},DF=class extends Ra{},zF=class extends Ra{},Wc=class extends P{},BF=class extends Wc{},pm=class extends Wc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},RF=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Hc=class extends P{},GF=class extends Hc{},$F=class extends Hc{},VF=class extends jp{},Ga=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"])}},UF=class extends Ga{async encode(e){return await xe(this.sessions.encoder_model,e)}async decode(e){return await xe(this.sessions.decoder_model,e)}},mm=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},gm=class extends Ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Qc=class extends P{},jF=class extends Qc{},qF=class extends Qc{},$a=class extends P{},WF=class extends $a{},HF=class extends $a{},QF=class extends $a{async generate_speech(e,t,{threshold:r=.5,minlenratio:s=0,maxlenratio:n=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Or(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),h=Math.floor(c*s),_=this.config.num_mel_bins;let p=[],w=null,v=null,y=0;for(;;){++y;const A=op(!!v);let S;v?S=v.output_sequence_out:S=new U("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:A,output_sequence:S,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};tl(this,C,w),v=await xe(this.sessions.decoder_model_merged,C),w=el(v,w);const{prob:I,spectrum:x}=v;if(p.push(x),y>=h&&(Array.from(I.data).filter(R=>R>=r).length>0||y>=d))break}const M=ze(p),{waveform:T}=await xe(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:T}}},XF=class extends P{constructor(){super(...arguments);k(this,"main_input_name","spectrogram")}},mn=class extends P{},YF=class extends mn{},JF=class extends mn{async _call(e){return new Je(await super._call(e))}},KF=class extends mn{async _call(e){return new ne(await super._call(e))}},ZF=class extends mn{async _call(e){return new ht(await super._call(e))}},Xc=class extends P{},eL=class extends Xc{},tL=class extends Xc{},Yc=class extends P{},rL=class extends Yc{},sL=class extends Yc{},wm=class extends P{},nL=class extends wm{},vm=class extends P{},ym=class extends vm{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:s=5,speed:n=1.05}){const{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:c,durations:d}=await xe(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),h=d.div(n).mul_(a),_=i*o,p=h.data,w=Int32Array.from(p,z=>Math.ceil(z/_)),v=Math.max(...w),y=e.dims[0],M=new BigInt64Array(y*v);for(let z=0;z<y;++z)M.fill(1n,z*v,z*v+w[z]);const T=new U("int64",M,[y,v]),A=l*o,S=A*v;let C=Fx([y,A,v]);const I=C.data;for(let z=0;z<y;++z)if(w[z]!==v)for(let $=0;$<A;++$)I.fill(0,z*S+$*v+w[z],z*S+($+1)*v);const x=ct([y],s);for(let z=0;z<s;++z){const $=ct([y],z);({denoised_latents:C}=await xe(this.sessions.latent_denoiser,{style:r,noisy_latents:C,latent_mask:T,encoder_outputs:c,attention_mask:t,timestep:$,num_inference_steps:x}))}const{waveform:R}=await xe(this.sessions.voice_decoder,{latents:C});return{waveform:R,durations:h}}},Va=class extends P{},aL=class extends Va{},oL=class extends Va{async _call(e){return new ne(await super._call(e))}},iL=class extends Va{},Jc=class extends P{},lL=class extends Jc{},cL=class extends Jc{},Kc=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}},uL=class extends Kc{},dL=class extends Kc{},Zc=class extends P{},hL=class extends Zc{},fL=class extends Zc{async _call(e){return new bm(await super._call(e))}},bm=class extends xl{},Mm=class extends P{},_L=class extends Mm{},Ua=class extends P{},pL=class extends Ua{},mL=class extends Ua{async _call(e){return new Jr(await super._call(e))}},gL=class extends Ua{async _call(e){return new ne(await super._call(e))}},gn=class extends P{},wL=class extends gn{},vL=class extends gn{async _call(e){return new Jr(await super._call(e))}},yL=class extends gn{async _call(e){return new ne(await super._call(e))}},bL=class extends gn{async _call(e){return new He(await super._call(e))}},eu=class extends P{},ML=class extends eu{},xL=class extends eu{},kL=class extends P{constructor(){super(...arguments);k(this,"main_input_name","pixel_values");k(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"])}},tu=class extends P{},TL=class extends tu{},EL=class extends tu{async _call(e){return new ne(await super._call(e))}},xm=class extends P{},AL=class extends xm{},ru=class extends P{},CL=class extends ru{},SL=class extends ru{async _call(e){return new ne(await super._call(e))}},km=class extends P{},PL=class extends km{async _call(e){return new tE(await super._call(e))}},Tm=class extends P{},FL=class extends Tm{},Em=class extends Ye{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Am=class extends P{},LL=class extends Am{async _call(e){return new Em(await super._call(e))}},IL=class extends Xl{},Cm=2,OL=1,su=new WeakMap;function NL(e,t){var v,y;const{text_config:r,audio_config:s}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=s,i=a+o,l=new Ji,c=ba(s),d={batch_size:1};let h="float32";for(const M of n.inputMetadata){if(M.name==="past_padding_cache"){h=M.type;continue}if(!c.has(M.name))continue;const T=cp(M.shape,d),A=T.reduce((C,I)=>C*I,1),S=sn[M.type];l[M.name]=new U(M.type,new S(A),T)}const _=sn[h],p=new U(h,new _(i*Cm),[1,i,Cm]),w=((v=t[Symbol.asyncIterator])==null?void 0:v.call(t))??((y=t[Symbol.iterator])==null?void 0:y.call(t));if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function DL(e,t){const r=t.dims[2],s=Math.floor((OL+r-3)/2)+1,n=new U("int64",BigInt64Array.from({length:s},(d,h)=>BigInt(e.enc_past_seq_len+h)),[1,s]),a=e.enc_past_seq_len+s,o=yt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await xe(e.encoder_session,{input_features:t,attention_mask:o,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=l;for(const d in c)if(d.startsWith("present.")){const h=d.replace("present","past_key_values"),_=e.enc_kv_cache[h];(_==null?void 0:_.location)==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[h]=c[d]}return e.enc_past_seq_len=a,i}async function zL(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){const r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=!0;break}const s=await DL(e,r.value);e.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),e.audio_embed_total_tokens+=s.dims[1]}}function BL(e,t,r){if(e.audio_embed_queue.length===0)return;const s=t.data;let n=0,a=r;for(;a>0&&e.audio_embed_queue.length>0;){const o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)s[n*e.text_hidden_size+d]+=o.data[c+d];n+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-a}var RL=class extends Ma{constructor(e){super(),this._s=e}_call(e){const t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},Sm=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values"])}},Pm=class extends Sm{async forward({input_ids:e,past_key_values:t,...r}){const s=e.dims[1],n=su.get(this);n&&await zL(n,n.audio_consumed+s);const{inputs_embeds:a}=await xe(this.sessions.embed_tokens,{input_ids:e});n&&BL(n,a,s);const o={inputs_embeds:a,...r};tl(this,o,t);const i=this.sessions.decoder_model_merged,l=Ze(o,i.inputNames);return await xe(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const s=NL(this,e);su.set(this,s);const n=new rp;n.push(new RL(s)),t&&n.extend(t);try{return await super.generate({...r,stopping_criteria:n})}finally{s.enc_kv_cache.dispose(),su.delete(this)}}},ja=class extends P{},GL=class extends ja{},$L=class extends ja{async _call(e){return new Jr(await super._call(e))}},VL=class extends ja{async _call(e){return new ne(await super._call(e))}},Fm=class extends Ye{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Ps=class extends P{},UL=class extends Ps{},jL=class extends Ps{async _call(e){return new Jr(await super._call(e))}},qL=class extends Ps{async _call(e){return new ne(await super._call(e))}},WL=class extends Ps{async _call(e){return new Fm(await super._call(e))}},HL=class extends Ps{async _call(e){return new He(await super._call(e))}},Lm=class extends P{},QL=class extends Lm{},XL=class extends tp{constructor(){super(...arguments);k(this,"return_timestamps",null);k(this,"return_token_timestamps",null);k(this,"num_frames",null);k(this,"alignment_heads",null);k(this,"task",null);k(this,"language",null);k(this,"no_timestamps_token_id",null);k(this,"prompt_ids",null);k(this,"is_multilingual",null);k(this,"lang_to_id",null);k(this,"task_to_id",null);k(this,"max_initial_timestamp_index",1)}},nu=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",!1);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}},YL=class extends nu{},Im=class extends nu{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,XL)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const s=e.task;if(e.is_multilingual){r||(ue.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${E1(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[s??"transcribe"])}else if(r||s)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(ue.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,...n}){t=this._prepare_generation_config(t,n);const a=n.decoder_input_ids instanceof U?Ii(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new Yi),r.push(new oE(t,a))),t.begin_suppress_tokens&&(r??(r=new Yi),r.push(new ep(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&ue.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:n});const o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...n});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:s,kwargs:n}){const a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,i=t.return_token_timestamps,l=e,c=l.dims[2],d=2,h=this.config.max_source_positions,_=d*h;let p=0;const w=[],v=[];for(;p<c;){const M=Math.min(p+_,c),T=l.slice(null,null,[p,M]);let A;const S=T.dims[2];if(S<_){const W=l.dims[1],ee=new Float32Array(W*_),G=T.data;for(let L=0;L<W;++L)ee.set(G.subarray(L*S,(L+1)*S),L*_);A=new U("float32",ee,[1,W,_])}else A=T;if(r)for(const W of r)"begin_index"in W&&(W.begin_index=s.length);const C=await super.generate({inputs:A,generation_config:t,logits_processor:r,decoder_input_ids:s,...n}),x=(i?C.sequences:C)[0].tolist().map(Number).slice(s.length);let R;if(i){C.token_timestamps=this._extract_token_timestamps(C,t.alignment_heads,Math.floor((M-p)/d),.02,s.length);const W=p/d*.02;R=C.token_timestamps[0].tolist().slice(s.length).map(ee=>ee+W)}if(x.length>0&&x.at(-1)===o&&x.pop(),x.length===0)break;const z=x.map(W=>W>=a),$=x.length>=2&&z[x.length-1]&&!z[x.length-2],Q=[];for(let W=0;W<x.length-1;++W)z[W]&&z[W+1]&&Q.push(W+1);let H,D=x.length;if(Q.length>0)if($)H=M-p;else{const W=Q.at(-1);H=(x[W-1]-a)*d,D=W}else H=M-p;const O=Math.floor(p/d),te=a+1500;for(let W=0;W<D;++W)x[W]>=a&&(x[W]=Math.min(x[W]+O,te));w.push(...x.slice(0,D)),R&&v.push(...R.slice(0,D)),p+=H}w.push(o);const y=[...s,...w];if(i){const M=new U("int64",y.map(BigInt),[1,y.length]),T=[...new Array(s.length).fill(0),...v,0],A=new U("float32",new Float32Array(T),[1,T.length]);return{sequences:M,token_timestamps:A}}return new U("int64",y.map(BigInt),[1,y.length])}_extract_token_timestamps(e,t,r=null,s=.02,n=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&ue.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&&(ue.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(y,M)=>ze(o.map(T=>T[M]),2)),l=dr(t.map(([y,M])=>{if(y>=i.length)throw new Error(`Layer index ${y} is out of bounds for cross attentions (length ${i.length}).`);return r?i[y].slice(null,M,null,[0,r]):i[y].slice(null,M)})).transpose(1,0,2,3),[c,d]=Px(l,-2,0,!0),h=l.clone();for(let y=0;y<h.dims[0];++y){const M=h[y];for(let T=0;T<M.dims[0];++T){const A=M[T],S=c[y][T][0].data,C=d[y][T][0].data;for(let I=0;I<A.dims[0];++I){let x=A[I].data;for(let R=0;R<x.length;++R)x[R]=(x[R]-C[R])/S[R];x.set(hx(x,a))}}}const _=n>0?h.slice(null,null,[n,h.dims[2]],null):h,p=[Si(_,1)],w=e.sequences.dims,v=new U("float32",new Float32Array(w[0]*w[1]),w);for(let y=0;y<w[0];++y){const M=p[y].neg().squeeze_(0),[T,A]=_x(M.tolist()),S=Array.from({length:T.length-1},(R,z)=>T[z+1]-T[z]),C=Jt([1],S).map(R=>!!R),I=[];for(let R=0;R<C.length;++R)C[R]&&I.push(A[R]*s);const x=new Array(n).fill(0);x.push(...I),I.length>0&&x.push(I.at(-1)),v[y].data.set(x)}return v}},JL=class extends Im{},Fs=class extends P{},KL=class extends Fs{},ZL=class extends Fs{async _call(e){return new Je(await super._call(e))}},eI=class extends Fs{async _call(e){return new ne(await super._call(e))}},tI=class extends Fs{async _call(e){return new He(await super._call(e))}},rI=class extends Fs{async _call(e){return new ht(await super._call(e))}},Ls=class extends P{},sI=class extends Ls{},nI=class extends Ls{async _call(e){return new Je(await super._call(e))}},aI=class extends Ls{async _call(e){return new ne(await super._call(e))}},oI=class extends Ls{async _call(e){return new He(await super._call(e))}},iI=class extends Ls{async _call(e){return new ht(await super._call(e))}},au=class extends P{},lI=class extends au{},cI=class extends au{async _call(e){return new Om(await super._call(e))}},Om=class extends Ye{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},ou=class extends P{},uI=class extends ou{},dI=class extends ou{},hI=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),fI=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"]]),_I=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),pI=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"]]),Nm=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),Dm=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),zm=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Bm=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"]]),Rm=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),Gm=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),$m=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"]]),mI=new Map([["multi_modality","MultiModalityCausalLM"]]),Vm=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"]]),Um=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"]]),jm=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),qm=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"]]),Wm=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),gI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Hm=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"]]),Qm=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Xm=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Is=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Ym=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Jm=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Km=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Zm=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),eg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),tg=new Map([["wavlm","WavLMForXVector"]]),rg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),sg=new Map([["vitmatte","VitMatteForImageMatting"]]),wI=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),ng=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),ag=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),og=new Map([["sapiens","SapiensForNormalEstimation"]]),ig=new Map([["vitpose","VitPoseForPoseEstimation"]]),lg=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),cg=[[hI,q.EncoderOnly],[fI,q.EncoderDecoder],[pI,q.DecoderOnlyWithoutHead],[_I,q.AutoEncoder],[Bm,q.EncoderOnly],[Rm,q.EncoderOnly],[Gm,q.Seq2Seq],[Nm,q.Seq2Seq],[$m,q.DecoderOnly],[mI,q.MultiModality],[Vm,q.EncoderOnly],[Um,q.EncoderOnly],[jm,q.Vision2Seq],[qm,q.ImageTextToText],[Wm,q.AudioTextToText],[Hm,q.EncoderOnly],[Is,q.EncoderOnly],[Jm,q.EncoderOnly],[Ym,q.EncoderOnly],[sg,q.EncoderOnly],[wI,q.EncoderOnly],[ng,q.EncoderOnly],[ag,q.EncoderOnly],[og,q.EncoderOnly],[ig,q.EncoderOnly],[Qm,q.EncoderOnly],[Xm,q.EncoderOnly],[Km,q.MaskGeneration],[Zm,q.EncoderOnly],[eg,q.EncoderOnly],[Dm,q.Seq2Seq],[zm,q.EncoderOnly],[tg,q.EncoderOnly],[rg,q.EncoderOnly],[lg,q.EncoderOnly]];for(const[e,t]of cg)for(const r of e.values()){_r.set(r,t);const s=sl[r];ws.set(s,r),Zi.set(r,s)}var vI=[["MusicgenForConditionalGeneration",rm,q.Musicgen],["Phi3VForCausalLM",om,q.Phi3V],["CLIPTextModelWithProjection",bp,q.EncoderOnly],["SiglipTextModel",pm,q.EncoderOnly],["JinaCLIPTextModel",qp,q.EncoderOnly],["ClapTextModelWithProjection",vp,q.EncoderOnly],["ClapAudioModelWithProjection",yp,q.EncoderOnly],["DacEncoderModel",kp,q.EncoderOnly],["DacDecoderModel",Tp,q.EncoderOnly],["MimiEncoderModel",Zp,q.EncoderOnly],["MimiDecoderModel",em,q.EncoderOnly],["SnacEncoderModel",mm,q.EncoderOnly],["SnacDecoderModel",gm,q.EncoderOnly],["Gemma3nForConditionalGeneration",Fa,q.ImageAudioTextToText],["Gemma4ForConditionalGeneration",Nl,q.ImageAudioTextToText],["SupertonicForConditionalGeneration",ym,q.Supertonic],["ChatterboxModel",mp,q.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Pm,q.VoxtralRealtime]];for(const[e,t,r]of vI)_r.set(e,r),ws.set(t,e),Zi.set(e,t);var ug=new Map([["modnet",Is],["birefnet",Is],["isnet",Is],["ben",Is]]);for(const[e,t]of ug.entries())t.set(e,"PreTrainedModel"),_r.set(e,q.EncoderOnly),Zi.set(e,P);var yI=new Set(ug.keys());_r.set("PreTrainedModel",q.EncoderOnly),ws.set(P,"PreTrainedModel");var Ae={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Bm,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Rm,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Dm,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:zm,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Vm,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Um,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Hm,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Is,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Ym,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Jm,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Qm,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Xm,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Km,MODEL_FOR_CTC_MAPPING_NAMES:Zm,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:eg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:tg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:rg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:gI,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:sg,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:ng,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:ag,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:og,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:ig,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:lg,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:qm,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Wm,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Gm,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Nm,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:$m,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:jm};ME(Ae);var Ce=(oo=class{static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(const t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:h={}}={}){const _={progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h};if(_.config=await on.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const{model_type:p}=_.config;for(const w of this.MODEL_CLASS_MAPPINGS){let v=w.get(p);if(!v){for(const y of w.values())if(y[0]===p){v=y;break}if(!v)continue}return await sl[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return yI.has(p)||ue.warn(`Unknown model class "${p}", attempting to construct from base class.`),await P.from_pretrained(e,_);throw Error(`Unsupported model type: ${p}`)}},k(oo,"MODEL_CLASS_MAPPINGS",null),k(oo,"BASE_IF_FAIL",!1),oo),wn=(io=class extends Ce{},k(io,"MODEL_CLASS_MAPPINGS",cg.map(e=>e[0])),k(io,"BASE_IF_FAIL",!0),io),dg=(pu=class extends Ce{},k(pu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),pu),bI=(mu=class extends Ce{},k(mu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),mu),iu=(gu=class extends Ce{},k(gu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),gu),MI=(wu=class extends Ce{},k(wu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),wu),xI=(vu=class extends Ce{},k(vu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),vu),kI=(yu=class extends Ce{},k(yu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),yu),TI=(bu=class extends Ce{},k(bu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),bu),EI=(Mu=class extends Ce{},k(Mu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),Mu),AI=(xu=class extends Ce{},k(xu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),xu),CI=(ku=class extends Ce{},k(ku,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),ku),SI=(Tu=class extends Ce{},k(Tu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),Tu),hg=(Eu=class extends Ce{},k(Eu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),Eu),fg=(Au=class extends Ce{},k(Au,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),Au),_g=(Cu=class extends Ce{},k(Cu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),Cu),PI=(Su=class extends Ce{},k(Su,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),Su),FI=(Pu=class extends Ce{},k(Pu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),Pu);Fu=class extends Ce{},k(Fu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);var LI=(Lu=class extends Ce{},k(Lu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_CTC_MAPPING_NAMES]),Lu),II=(Iu=class extends Ce{},k(Iu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),Iu);Ou=class extends Ce{},k(Ou,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]),Nu=class extends Ce{},k(Nu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);var OI=(Du=class extends Ce{},k(Du,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),Du);zu=class extends Ce{},k(zu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);var NI=(Bu=class extends Ce{},k(Bu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),Bu),DI=(Ru=class extends Ce{},k(Ru,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),Ru);Gu=class extends Ce{},k(Gu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]),$u=class extends Ce{},k($u,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]);var zI=(Vu=class extends Ce{},k(Vu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),Vu);Uu=class extends Ce{},k(Uu,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]),ju=class extends Ce{},k(ju,"MODEL_CLASS_MAPPINGS",[Ae.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]);async function Ht(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>qt.read(t)))}async function Os(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?N1(r,t):r instanceof Float64Array?new Float32Array(r):r))}function lu(e,t){t&&(e=e.map(o=>o|0));const[r,s,n,a]=e;return{xmin:r,ymin:s,xmax:n,ymax:a}}var Ve=class extends vt{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}},BI=class extends Ve{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),{problem_type:n,id2label:a}=this.model.config,o=n==="multi_label_classification"?l=>l.sigmoid():l=>new U("float32",nt(l.data),l.dims),i=[];for(const l of s.logits){const c=o(l),d=await fs(c,t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:a?a[w]:`LABEL_${w}`,score:h[v]}));t===1?i.push(...p):i.push(p)}return Array.isArray(e)||t===1?i:i[0]}},RI=class extends Ve{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:r="none"}={}){if(r!=="none"&&r!=="simple")throw new Error(`Invalid aggregation_strategy: "${r}". Must be one of "none" or "simple".`);const s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),o=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let c=0;c<o.dims[0];++c){const d=n.input_ids[c].tolist(),h=o[c],_=[];for(let p=0;p<h.dims[0];++p){const w=h[p],v=je(w.data)[1],y=i?i[v]:`LABEL_${v}`;if(t.includes(y))continue;const M=this.tokenizer.decode([d[p]],{skip_special_tokens:!0});if(M==="")continue;const T=nt(w.data);_.push({entity:y,score:T[v],index:p,word:M})}l.push(r==="simple"?$I(_,d,this.tokenizer):_)}return s?l:l[0]}};function GI(e){const t=e[0];return e[1]==="-"&&(t==="B"||t==="I"||t==="E"||t==="S")?[t,e.slice(2)]:["I",e]}function $I(e,t,r){const s=[];let n=null;for(let a=0;a<e.length;++a){const[o,i]=GI(e[a].entity);n===i&&o!=="B"&&o!=="S"?(s[s.length-1].end=a+1,o==="E"&&(n=null)):(s.push({tag:i,start:a,end:a+1}),n=o==="S"?null:i)}return s.map(({tag:a,start:o,end:i})=>{let l=0;const c=[];for(let d=o;d<i;++d)l+=e[d].score,c.push(t[e[d].index]);return{entity_group:a,score:l/(i-o),word:r.decode(c,{skip_special_tokens:!0})}})}var VI=class extends Ve{async _call(e,t,{top_k:r=1}={}){const s=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),n=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(s),i=s.input_ids.tolist(),l=s.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,h=[];for(let _=0;_<a.dims[0];++_){const p=i[_],w=p.findIndex(C=>C==d),v=a[_].tolist(),y=o[_].tolist();for(let C=1;C<v.length;++C)(l[_]==0||C<=w||c.findIndex(I=>I==p[C])!==-1)&&(v[C]=-1/0,y[C]=-1/0);const M=nt(v).map((C,I)=>[C,I]),T=nt(y).map((C,I)=>[C,I]);M[0][0]=0,T[0][0]=0;const A=zy(M,T).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,I)=>I[2]-C[2]),S=[];for(let C=0;C<Math.min(A.length,r);++C){const[I,x,R]=A[C],z=p.slice(I,x+1),$=this.tokenizer.decode(z,{skip_special_tokens:!0});S.push({answer:$,score:R})}r===1?h.push(...S):h.push(S)}return n?h:h[0]}},UI=class extends Ve{async _call(e,{top_k:t=5}={}){const{mask_token_id:r,mask_token:s}=this.tokenizer,n=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(n),o=[],i=n.input_ids.tolist();for(let l=0;l<i.length;++l){const c=i[l],d=c.findIndex(v=>v==r);if(d===-1)throw Error(`Mask token (${s}) not found in text.`);const h=a[l][d],_=await fs(new U("float32",nt(h.data),h.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((v,y)=>{const M=c.slice();return M[d]=v,{score:p[y],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},cu=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256});k(this,"_key","generated_text")}async _call(t,r={}){Array.isArray(t)||(t=[t]),this.model.config.prefix&&(t=t.map(l=>this.model.config.prefix+l));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(t=t.map(l=>s[this.task].prefix+l));const n=this.tokenizer,a={padding:!0,truncation:!0};let o;this.task==="translation"&&"_build_translation_inputs"in n?o=n._build_translation_inputs(t,a,r):o=n(t,a);const i=await this.model.generate({...o,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}},jI=class extends cu{constructor(){super(...arguments);k(this,"_key","summary_text")}},qI=class extends cu{constructor(){super(...arguments);k(this,"_key","translation_text")}};function pg(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var WI=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r={}){const{add_special_tokens:s,return_full_text:n,tools:a,documents:o,chat_template:i,tokenizer_encode_kwargs:l,...c}=r;let d=!1,h=!1,_=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,p=l,w;if(typeof t=="string")w=t=[t];else if(Array.isArray(t)&&t.every(C=>typeof C=="string"))d=!0,w=t;else{if(pg(t))t=[t];else if(Array.isArray(t)&&t.every(pg))d=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");h=!0;const C={tokenize:!1,add_generation_prompt:!0,...Ze({tools:a,documents:o,chat_template:i},["tools","documents","chat_template"]),...p};w=t.map(I=>this.tokenizer.apply_chat_template(I,C)),_=!1,p=void 0}const v=h?!1:n??!0;this.tokenizer.padding_side="left";const y=this.tokenizer(w,{add_special_tokens:_,padding:!0,truncation:!0,...p}),M=await this.model.generate({...y,...this._default_generation_config,...c}),T=this.tokenizer.batch_decode(M,{skip_special_tokens:!0});let A;!v&&y.input_ids.dims.at(-1)>0&&(A=this.tokenizer.batch_decode(y.input_ids,{skip_special_tokens:!0}).map(C=>C.length));const S=Array.from({length:t.length},C=>[]);for(let C=0;C<T.length;++C){const I=Math.floor(C/M.dims[0]*t.length);A&&(T[C]=T[C].slice(A[I])),S[I].push({generated_text:h?[...t[I],{role:"assistant",content:T[C]}]:T[C]})}return!d&&S.length===1?S[0]:S}},HI=class extends Ve{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ue.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&&(ue.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:s=!1}={}){const n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>r.replace("{}",l)),o=s||t.length===1,i=[];for(const l of e){const c=[];for(const _ of a){const p=this.tokenizer(l,{text_pair:_,padding:!0,truncation:!0}),w=await this.model(p);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id])}const h=(o?c.map(_=>nt(_)[1]):nt(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:h.map(_=>t[_[1]]),scores:h.map(_=>_[0])})}return n?i:i[0]}},QI=class extends Ve{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await Os(e,r),n=this.model.config.id2label,a=[];for(const o of s){const i=await this.processor(o),c=(await this.model(i)).logits[0],d=await fs(new U("float32",nt(c.data),c.dims),t),h=d[0].tolist(),p=d[1].tolist().map((w,v)=>({label:n?n[w]:`LABEL_${w}`,score:h[v]}));a.push(p)}return Array.isArray(e)?a:a[0]}},XI=class extends Ve{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const n=t.map(c=>r.replace("{}",c)),a=this.tokenizer(n,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await Os(e,o),l=[];for(const c of i){const d=await this.processor(c),h=await this.model({...a,...d}),_=nt(h.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})))}return s?l[0]:l}},YI=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{})}async _call(t,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(t,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(t,r);case"moonshine":return this._call_moonshine(t,r);case"cohere_asr":return this._call_cohere_asr(t,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(t,r){r.language&&ue.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ue.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Os(n,a),i=[];for(const l of o){const c=await this.processor(l),h=(await this.model(c)).logits[0],_=[];for(const w of h)_.push(je(w.data)[1]);const p=this.tokenizer.decode(_,{skip_special_tokens:!0}).trim();i.push({text:p})}return s?i[0]:i}async _call_whisper(t,r){const s=r.return_timestamps??!1,n=r.chunk_length_s??0,a=r.force_full_sequences??!1;let o=r.stride_length_s??null;const i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);const l=!Array.isArray(t),c=l?[t]:t,d=this.processor.feature_extractor.config,h=d.chunk_length/this.model.config.max_source_positions,_=d.hop_length,p=d.sampling_rate,w=await Os(c,p),v=[];for(const y of w){let M=[];if(n>0){if(o===null)o=n/6;else if(n<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const S=p*n,C=p*o,I=S-2*C;let x=0;for(;;){const R=x+S,z=y.subarray(x,R),$=await this.processor(z),Q=x===0,H=R>=y.length;if(M.push({stride:[z.length,Q?0:C,H?0:C],input_features:$.input_features,is_last:H}),H)break;x+=I}}else M=[{stride:[y.length,0,0],input_features:(await this.processor(y)).input_features,is_last:!0}];for(const S of M){i.num_frames=Math.floor(S.stride[0]/_);const C=await this.model.generate({inputs:S.input_features,...i});if(s==="word"){const I=C.sequences.tolist()[0],x=C.token_timestamps.tolist()[0],R=this.tokenizer.timestamp_begin,z=Math.max(I.findIndex($=>Number($)>=R),0);S.tokens=I.slice(z),S.token_timestamps=x.slice(z).map($=>rn($,2))}else S.tokens=C[0].tolist();S.stride=S.stride.map(I=>I/p)}const[T,A]=this.tokenizer._decode_asr(M,{time_precision:h,return_timestamps:s,force_full_sequences:a});v.push({text:T,...A})}return l?v[0]:v}async _call_moonshine(t,r){const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Os(n,a),i=[];for(const l of o){const c=await this.processor(l),d=Math.floor(l.length/a)*6,h=await this.model.generate({max_new_tokens:d,...r,...c}),_=this.processor.batch_decode(h,{skip_special_tokens:!0})[0];i.push({text:_})}return s?i[0]:i}async _call_cohere_asr(t,r){const s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor,o=a.config.sampling_rate,i=await Os(n,o),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),d=[];for(const h of i){const _=a.split_audio(h),p=[];for(const v of _){const y=await this.processor(v),M=await this.model.generate({...y,decoder_input_ids:c,...r}),T=this.tokenizer.decode(M[0].tolist(),{skip_special_tokens:!0}).trim();p.push(T)}const w=this.processor.constructor.join_chunks(p,l);d.push({text:w})}return s?d[0]:d}},JI=class extends Ve{constructor(t){super(t);k(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=t.vocoder??null}async _prepare_speaker_embeddings(t,r){if((typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await be.fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new U("float32",t,[t.length]);else if(!(t instanceof U))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(t.dims[0]===1)t=t.repeat(r,1);else if(t.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${t.dims[0]}.`)}return t}_postprocess_waveform(t,r,s,n=null){const a=r.data,[o,i]=r.dims,l=n?n.data:null,c=[];for(let d=0;d<o;++d){const h=l?Math.min(Math.ceil(l[d]),i):i,_=d*i;c.push(new q1(a.slice(_,_+h),s))}return Array.isArray(t)?c:c[0]}async _call(t,r){return this.processor?this._call_text_to_spectrogram(t,r):this.model.config.model_type==="supertonic"?this._call_supertonic(t,r):this._call_text_to_waveform(t)}async _call_supertonic(t,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:a,style_dim:o}=this.model.config,i=this.tokenizer(t,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,o);const{waveform:c,durations:d}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(t,c,a,d)}async _call_text_to_waveform(t){const r=this.tokenizer(t,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(t,s,n)}async _call_text_to_spectrogram(t,{speaker_embeddings:r}){this.vocoder||(ue.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await wn.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:s}=this.tokenizer(t,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);const{waveform:a}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(t,a,o)}},KI=class extends Ve{async _call(e,t={}){const r=Array.isArray(e),s=await Ht(e),{pixel_values:n}=await this.processor(s),a=[];for(const o of n){o.dims=[1,...o.dims];const i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(c=>({generated_text:c.trim()}));a.push(l)}return r?a:a[0]}},ZI=class extends Ve{async _call(e,{top_k:t=5}={}){const r=await Ht(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s}),{id2label:a}=this.model.config,o=[];for(const i of n.logits){const l=await fs(new U("float32",nt(i.data),i.dims),t),c=l[0].tolist(),h=l[1].tolist().map((_,p)=>({label:a?a[_]:`LABEL_${_}`,score:c[p]}));o.push(h)}return Array.isArray(e)?o:o[0]}},mg={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},gg=class extends Ve{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:n=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const l=await Ht(e),c=l.map(M=>[M.height,M.width]),d=await this.processor(l),{inputNames:h,outputNames:_}=this.model.sessions.model;if(!h.includes("pixel_values")){if(h.length!==1)throw Error(`Expected a single input name, but got ${h.length} inputs: ${h}.`);const M=h[0];if(M in d)throw Error(`Input name ${M} already exists in the inputs.`);d[M]=d.pixel_values}const p=await this.model(d);let w=null;if(o!==null)w=mg[o];else if(this.processor.image_processor){for(const[M,T]of Object.entries(mg))if(T in this.processor.image_processor){w=this.processor.image_processor[T].bind(this.processor.image_processor),o=M;break}}const v=this.model.config.id2label,y=[];if(o)if(o==="panoptic"||o==="instance"){const M=w(p,t,r,s,n,a??c)[0],T=M.segmentation;for(const A of M.segments_info){const S=new Uint8ClampedArray(T.data.length);for(let I=0;I<T.data.length;++I)T.data[I]===A.id&&(S[I]=255);const C=new qt(S,T.dims[1],T.dims[0],1);y.push({score:A.score,label:v[A.label_id],mask:C})}}else if(o==="semantic"){const{segmentation:M,labels:T}=w(p,a??c)[0];for(const A of T){const S=new Uint8ClampedArray(M.data.length);for(let I=0;I<M.data.length;++I)M.data[I]===A&&(S[I]=255);const C=new qt(S,M.dims[1],M.dims[0],1);y.push({score:null,label:v[A],mask:C})}}else throw Error(`Subtask ${o} not supported.`);else{const T=p[_[0]];for(let A=0;A<c.length;++A){const S=c[A],C=T[A];C.data.some(x=>x<-1e-5||x>1+1e-5)&&C.sigmoid_();const I=await qt.fromTensor(C.mul_(255).to("uint8")).resize(S[1],S[0]);y.push({label:null,score:null,mask:I})}}return y}},eO=class extends gg{async _call(e,t={}){const r=await Ht(e),s=await super._call(e,t),n=r.map((a,o)=>{const i=a.clone();return i.putAlpha(s[o].mask),i});return Array.isArray(e)?n:n[0]}},tO=class extends Ve{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const s=Array.isArray(e),n=await Ht(e),a=t.map(h=>r.replace("{}",h)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(n),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>nt(h.data),d=[];for(const h of l.logits_per_image){const p=[...c(h)].map((w,v)=>({score:w,label:t[v]}));p.sort((w,v)=>v.score-w.score),d.push(p)}return s?d:d[0]}},rO=class extends Ve{async _call(e,{threshold:t=.9,percentage:r=!1}={}){const s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const n=await Ht(e),a=r?null:n.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(n),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=c.map(_=>_.boxes.map((p,w)=>({score:_.scores[w],label:d[_.classes[w]],box:lu(p,!r)})));return s?h:h[0]}},sO=class extends Ve{async _call(e,t,{threshold:r=.1,top_k:s=null,percentage:n=!1}={}){const a=Array.isArray(e),o=await Ht(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){const h=o[d],_=n?null:[[h.height,h.width]],p=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:p});let v;if("post_process_grounded_object_detection"in this.processor){const y=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];v=y.boxes.map((M,T)=>({score:y.scores[T],label:y.labels[T],box:lu(M,!n)}))}else{const y=this.processor.image_processor.post_process_object_detection(w,r,_,!0)[0];v=y.boxes.map((M,T)=>({score:y.scores[T],label:t[y.classes[T]],box:lu(M,!n)}))}v.sort((y,M)=>M.score-y.score),s!==null&&(v=v.slice(0,s)),c.push(v)}return a?c:c[0]}},nO=class extends Ve{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256})}async _call(t,r,s={}){if(Array.isArray(t)){if(t.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");t=t[0]}const n=(await Ht(t))[0],{pixel_values:a}=await this.processor(n),o=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:a,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),d=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/);let h=null;return d&&d.length>=2&&(h=d[1].trim()),[{answer:h}]}},aO=class extends Ve{async _call(e){const t=await Ht(e),r=await this.processor(t),s=await this.model(r),n=[];for(const a of s.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(qt.fromTensor(o))}return Array.isArray(e)?n:n[0]}},oO=class extends Ve{async _call(e){const t=await Ht(e),r=await this.processor(t),{predicted_depth:s}=await this.model(r),n=[];for(let a=0;a<t.length;++a){const o=s[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,h=(await jt(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=h.min().item(),p=h.max().item(),w=h.sub(_).div_(p-_).mul_(255).to("uint8").unsqueeze(0),v=qt.fromTensor(w);n.push({predicted_depth:h,depth:v})}return Array.isArray(e)?n:n[0]}},iO=class extends Ve{async _call(e,{pooling:t="none",normalize:r=!1,quantize:s=!1,precision:n="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=Sx(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),s&&(i=Lx(i,n)),i}},lO=class extends Ve{async _call(e,{pool:t=null}={}){const r=await Ht(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s});let a;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=n.pooler_output}else a=n.last_hidden_state??n.logits??n.image_embeds;return a}},qa=Object.freeze({"text-classification":{pipeline:BI,model:dg,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:RI,model:bI,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:VI,model:AI,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:UI,model:EI,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:jI,model:iu,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:qI,model:iu,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:cu,model:iu,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:WI,model:TI,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:HI,model:dg,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:QI,model:II,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:XI,model:wn,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:YI,model:[MI,LI],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:JI,model:[kI,xI],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:KI,model:CI,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ZI,model:SI,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:gg,model:[hg,fg,_g],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:eO,model:[hg,fg,_g],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:tO,model:wn,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:rO,model:PI,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:sO,model:FI,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:nO,model:OI,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:aO,model:NI,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:oO,model:DI,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:iO,model:wn,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:lO,model:[zI,wn],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),wg=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function cO(e){if(!e)throw new Error("modelId is required");return(await en(e,an,{})).exists?[an]:[]}async function uO(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await ap(e,{config:t,dtype:r,device:s,model_file_name:n});if(a){const l=await e_(e);i.push(...l)}if(o){const l=await cO(e);i.push(...l)}return i}async function dO(e,t,r={}){e=wg[e]??e;const s=qa[e];if(!s)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(qa).join(", ")}]`);const{type:n}=s,i=await uO(t,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){const l=await np(t,r),c=sp(l),d=yE(c);if(d){const h=Object.values(d).map(_=>`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||h.some(p=>_.startsWith(p)))}}return i}async function hO(e,t=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:_={}}={}){e=wg[e]??e;const p=qa[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(qa)}]`);t||(t=p.default.model,ue.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype&&(l=p.default.dtype));const w=await dO(e,t,{device:i,dtype:l});let v={};r&&(await Promise.all(w.map(async Q=>en(t,Q)))).forEach((Q,H)=>{Q.exists&&(v[w[H]]={loaded:0,total:Q.size??0})});const y={progress_callback:r?new pi(r,v):void 0,config:s,cache_dir:n,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:h,session_options:_},M=w.includes("tokenizer.json"),T=w.includes("preprocessor_config.json"),A=p.model;let S;if(Array.isArray(A)){const $=s??await on.from_pretrained(t,y),{model_type:Q}=$,H=A.find(D=>D.supports(Q));if(!H)throw Error(`Unsupported model type "${Q}" for task "${e}". None of the candidate model classes support this type.`);S=H.from_pretrained(t,{...y,config:$})}else S=A.from_pretrained(t,y);const[C,I,x]=await Promise.all([M?Te.from_pretrained(t,y):null,T?HT.from_pretrained(t,y):null,S]),R={task:e,model:x};C&&(R.tokenizer=C),I&&(R.processor=I),Pr(r,{status:"ready",task:e,model:t});const z=p.pipeline;return new z(R)}fe.IS_PROCESS_AVAILABLE;let gr=null;const vg="onnx-community/moonshine-base-ONNX";function Ct(e,t,r){self.postMessage({type:"log",level:e,message:t,meta:r})}async function fO(){if(gr)return;Ct("info","load: begin",{model:vg}),self.postMessage({type:"status",status:"loading",message:"Downloading speech model…"});let e=!1,t="downloading";const r=setTimeout(()=>{!e&&!gr&&(t="cache-loading",self.postMessage({type:"status",status:"loading",message:"Loading speech model from cache…"}),Ct("info","load: no download progress within 1.5s, assuming cache hit"))},1500),s=setInterval(()=>{if(gr)return;const n=t==="downloading"?"Downloading speech model…":"Loading speech model from cache…";self.postMessage({type:"status",status:"loading",message:n})},1e4);try{const n=Date.now();gr=await hO("automatic-speech-recognition",vg,{dtype:"fp32",device:"wasm",progress_callback:o=>{o.status==="progress_total"&&typeof o.progress=="number"?(e=!0,self.postMessage({type:"progress",pct:o.progress})):(o.status==="download"||o.status==="initiate")&&(e=!0,Ct("debug","pipeline: "+o.status,{file:o.file}))}}),Ct("info","load: pipeline ready",{ms:Date.now()-n});const a=Date.now();try{await Promise.race([gr(new Float32Array(16e3)),new Promise((o,i)=>setTimeout(()=>i(new Error("warmup timeout")),1e4))]),Ct("info","load: warmup done",{ms:Date.now()-a})}catch(o){const i=o instanceof Error?o.message:String(o);Ct("warn","load: warmup failed (best-effort, ignored)",{error:i,ms:Date.now()-a})}self.postMessage({type:"status",status:"ready",message:"Speech model ready"})}finally{clearTimeout(r),clearInterval(s)}}self.onmessage=async e=>{var r,s;const{type:t}=e.data;if(t==="load"){try{await fO()}catch(n){const a=n instanceof Error?n.message:"Model load failed",o=n instanceof Error?n.stack:"";console.error("[speechWorker] load failed:",a,o),Ct("error","load: failed",{error:a,stack:o}),self.postMessage({type:"error",error:a})}return}if(t==="transcribe"){const n=e.data.audio,a=e.data.seq??0;if(!gr){Ct("warn","transcribe: model not loaded, dropping segment",{samples:n==null?void 0:n.length,seq:a}),self.postMessage({type:"error",error:"Model not loaded",seq:a});return}const o=Date.now();try{const l=((r=(await gr(n)).text)==null?void 0:r.trim())??"";Ct("debug","transcribe: ok",{ms:Date.now()-o,samples:n.length,chars:l.length,seq:a}),self.postMessage({type:"result",text:l,seq:a})}catch(i){const l=i instanceof Error?i.message:"Transcription failed";Ct("error","transcribe: failed",{error:l,ms:Date.now()-o,seq:a}),self.postMessage({type:"error",error:l,seq:a})}return}if(t==="transcribe-partial"){const n=e.data.audio,a=e.data.seq??0;if(!gr){Ct("warn","transcribe-partial: model not loaded, dropping",{samples:n==null?void 0:n.length,seq:a}),self.postMessage({type:"partial-error",seq:a,error:"Model not loaded"});return}const o=Date.now();try{const l=((s=(await gr(n)).text)==null?void 0:s.trim())??"";Ct("debug","transcribe-partial: ok",{ms:Date.now()-o,samples:n.length,chars:l.length,seq:a}),self.postMessage({type:"partial",text:l,seq:a})}catch(i){const l=i instanceof Error?i.message:"Partial transcription failed";Ct("warn","transcribe-partial: failed",{error:l,ms:Date.now()-o,seq:a}),self.postMessage({type:"partial-error",seq:a,error:l})}return}}})();