>>2>>>0],A=io[x];if(A===void 0)throw c=`parameter ${m}`,x=Id(x),d=Wt(x),It(x),new en(`${c} has unknown type ${d}`);p[y]=A}return p},Av=(c,d,p)=>{var m=[];return c=c(m,p),m.length&&((T(),N)[d>>>2>>>0]=Lt(m)),c},Pv={},Is=c=>{var d=Pv[c];return d===void 0?Wt(c):d};function Fv(c,d,p){var[m,...y]=Sv(c,d>>>0);d=m.Sc.bind(m);var x=y.map($=>$.Rc.bind($));c--;var A={toValue:Ct};switch(c=x.map(($,q)=>{var ve=`argFromPtr${q}`;return A[ve]=$,`${ve}(args${q?"+"+8*q:""})`}),p){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:A.getStringOrSymbol=Is,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${c})`,m.fe||(A.toReturnWire=d,A.emval_returnValue=Av,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) {
+ ${L}
+ }`,p=new Function(Object.keys(A),L)(...Object.values(A)),L=`methodCaller<(${y.map($=>$.name)}) => ${m.name}>`,Cv(Object.defineProperty(p,"name",{value:L}))}function Lv(c,d){return d>>>=0,(c=Ct(c>>>0))==Ct(d)}function Iv(c){return(c>>>=0)?(c=Is(c),Lt(globalThis[c])):Lt(globalThis)}function Ov(c){return c=Is(c>>>0),Lt(t[c])}function Nv(c,d){return d>>>=0,c=Ct(c>>>0),d=Ct(d),Lt(c[d])}function Dv(c){9<(c>>>=0)&&(Fr[c+1]+=1)}function pd(c,d,p,m,y){return po[c>>>0](d>>>0,p>>>0,m>>>0,y>>>0)}function Bv(c,d,p,m,y){return pd(c>>>0,d>>>0,p>>>0,m>>>0,y>>>0)}function zv(){return Lt([])}function Rv(c){c=Ct(c>>>0);for(var d=Array(c.length),p=0;p>>0))}function Gv(){return Lt({})}function Vv(c){for(var d=Ct(c>>>=0);d.length;){var p=d.pop();d.pop()(p)}lo(c)}function Uv(c,d,p){d>>>=0,p>>>=0,c=Ct(c>>>0),d=Ct(d),p=Ct(p),c[d]=p}function Wv(c,d){c=dt(c),d>>>=0,c=new Date(1e3*c),(T(),D)[d>>>2>>>0]=c.getUTCSeconds(),(T(),D)[d+4>>>2>>>0]=c.getUTCMinutes(),(T(),D)[d+8>>>2>>>0]=c.getUTCHours(),(T(),D)[d+12>>>2>>>0]=c.getUTCDate(),(T(),D)[d+16>>>2>>>0]=c.getUTCMonth(),(T(),D)[d+20>>>2>>>0]=c.getUTCFullYear()-1900,(T(),D)[d+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(T(),D)[d+28>>>2>>>0]=c}var md=c=>c%4==0&&(c%100!=0||c%400==0),gd=[0,31,60,91,121,152,182,213,244,274,305,335],wd=[0,31,59,90,120,151,181,212,243,273,304,334];function jv(c,d){c=dt(c),d>>>=0,c=new Date(1e3*c),(T(),D)[d>>>2>>>0]=c.getSeconds(),(T(),D)[d+4>>>2>>>0]=c.getMinutes(),(T(),D)[d+8>>>2>>>0]=c.getHours(),(T(),D)[d+12>>>2>>>0]=c.getDate(),(T(),D)[d+16>>>2>>>0]=c.getMonth(),(T(),D)[d+20>>>2>>>0]=c.getFullYear()-1900,(T(),D)[d+24>>>2>>>0]=c.getDay();var p=(md(c.getFullYear())?gd:wd)[c.getMonth()]+c.getDate()-1|0;(T(),D)[d+28>>>2>>>0]=p,(T(),D)[d+36>>>2>>>0]=-60*c.getTimezoneOffset(),p=new Date(c.getFullYear(),6,1).getTimezoneOffset();var m=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(p!=m&&c.getTimezoneOffset()==Math.min(m,p)),(T(),D)[d+32>>>2>>>0]=c}function qv(c){c>>>=0;var d=new Date((T(),D)[c+20>>>2>>>0]+1900,(T(),D)[c+16>>>2>>>0],(T(),D)[c+12>>>2>>>0],(T(),D)[c+8>>>2>>>0],(T(),D)[c+4>>>2>>>0],(T(),D)[c>>>2>>>0],0),p=(T(),D)[c+32>>>2>>>0],m=d.getTimezoneOffset(),y=new Date(d.getFullYear(),6,1).getTimezoneOffset(),x=new Date(d.getFullYear(),0,1).getTimezoneOffset(),A=Math.min(x,y);return 0>p?(T(),D)[c+32>>>2>>>0]=+(y!=x&&A==m):0>>2>>>0]=d.getDay(),p=(md(d.getFullYear())?gd:wd)[d.getMonth()]+d.getDate()-1|0,(T(),D)[c+28>>>2>>>0]=p,(T(),D)[c>>>2>>>0]=d.getSeconds(),(T(),D)[c+4>>>2>>>0]=d.getMinutes(),(T(),D)[c+8>>>2>>>0]=d.getHours(),(T(),D)[c+12>>>2>>>0]=d.getDate(),(T(),D)[c+16>>>2>>>0]=d.getMonth(),(T(),D)[c+20>>>2>>>0]=d.getYear(),c=d.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function vd(c,d,p,m,y,x,A){return s?te(16,1,c,d,p,m,y,x,A):-52}function yd(c,d,p,m,y,x){if(s)return te(17,1,c,d,p,m,y,x)}var $n={},Hv=()=>performance.timeOrigin+performance.now();function bd(c,d){if(s)return te(18,1,c,d);if($n[c]&&(clearTimeout($n[c].id),delete $n[c]),!d)return 0;var p=setTimeout(()=>{delete $n[c],ht(()=>Yd(c,performance.timeOrigin+performance.now()))},d);return $n[c]={id:p,Ce:d},0}function Qv(c,d,p,m){c>>>=0,d>>>=0,p>>>=0,m>>>=0;var y=new Date().getFullYear(),x=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset();var A=Math.max(x,y);(T(),N)[c>>>2>>>0]=60*A,(T(),D)[d>>>2>>>0]=+(x!=y),c=(d=L=>{var $=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor($/60)).padStart(2,"0")}${String($%60).padStart(2,"0")}`})(x),d=d(y),yDate.now();function Yv(c,d,p){return p>>>=0,0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),c=Math.round(1e6*c),(T(),ee)[p>>>3>>>0]=BigInt(c),0):28}var mo=[],Md=(c,d)=>{mo.length=0;for(var p;p=(T(),U)[c++>>>0];){var m=p!=105;d+=(m&=p!=112)&&d%8?4:0,mo.push(p==112?(T(),N)[d>>>2>>>0]:p==106?(T(),ee)[d>>>3>>>0]:p==105?(T(),D)[d>>>2>>>0]:(T(),K)[d>>>3>>>0]),d+=m?8:4}return mo};function Kv(c,d,p){return c>>>=0,d=Md(d>>>0,p>>>0),Fo[c](...d)}function Jv(c,d,p){return c>>>=0,d=Md(d>>>0,p>>>0),Fo[c](...d)}var Zv=()=>{};function ey(c,d){return F(Zr(c>>>0,d>>>0))}var ty=()=>{throw me+=1,"unwind"};function ry(){return 4294901760}var ny=()=>1,sy=()=>navigator.hardwareConcurrency;function ay(c){c>>>=0;var d=(T(),U).length;if(c<=d||4294901760=p;p*=2){var m=d*(1+.2/p);m=Math.min(m,c+100663296);e:{m=(Math.min(4294901760,65536*Math.ceil(Math.max(c,m)/65536))-hr.buffer.byteLength+65535)/65536|0;try{hr.grow(m),re();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1}var qt=c=>{var d=rr(c)+1,p=Bs(d);return tr(c,p,d),p},go=(c,d)=>{(T(),N)[c>>>2>>>0]=d;var p=(T(),N)[c>>>2>>>0];(T(),N)[c+4>>>2>>>0]=(d-p)/4294967296},Gn=c=>(T(),N)[c>>>2>>>0]+4294967296*(T(),D)[c+4>>>2>>>0],tt=[],oy=(c,d)=>{tt[c>>>0]=d},nr=[],Os=[],tn=(c,d)=>{Os[c]=new Promise(p=>d.finally(()=>p(c)))},J=c=>{if(c)return tt[c>>>0]},iy=(c,d)=>{for(c=(T(),N)[c>>>2>>>0];c;c=(T(),N)[c>>>2>>>0])d[(T(),D)[c+4>>>2>>>0]](c)},Ns=(c,d,p)=>{(T(),N)[c>>>2>>>0]=d,(T(),N)[c+4>>>2>>>0]=p},xd=c=>{var d=(T(),N)[c>>>2>>>0];return c=(T(),N)[c+4>>>2>>>0],Zr(d,c)},sr=c=>{var d=(T(),N)[c>>>2>>>0];return c=(T(),N)[c+4>>>2>>>0],d?Zr(d,c):c===0?"":void 0},ly=c=>{var d=sr(c+4),p=(p=(T(),N)[c+12>>>2>>>0])?J(p):"auto";if(c+=16){var m=J((T(),N)[c+4>>>2>>>0]),y=(T(),N)[c+16>>>2>>>0],x=(T(),N)[c+20>>>2>>>0];if(y){for(var A={},L=0;L>>3>>>0]}y=A}else y=void 0;c={module:m,constants:y,entryPoint:sr(c+8)}}else c=void 0;return{label:d,layout:p,compute:c}},Td=(c,d)=>{function p(m,y){m=c[m],(T(),N)[d+y>>>2>>>0]=m}p("maxTextureDimension1D",4),p("maxTextureDimension2D",8),p("maxTextureDimension3D",12),p("maxTextureArrayLayers",16),p("maxBindGroups",20),p("maxBindGroupsPlusVertexBuffers",24),p("maxBindingsPerBindGroup",28),p("maxDynamicUniformBuffersPerPipelineLayout",32),p("maxDynamicStorageBuffersPerPipelineLayout",36),p("maxSampledTexturesPerShaderStage",40),p("maxSamplersPerShaderStage",44),p("maxStorageBuffersPerShaderStage",48),p("maxStorageTexturesPerShaderStage",52),p("maxUniformBuffersPerShaderStage",56),p("minUniformBufferOffsetAlignment",80),p("minStorageBufferOffsetAlignment",84),go(d+64,c.maxUniformBufferBindingSize),go(d+72,c.maxStorageBufferBindingSize),p("maxVertexBuffers",88),go(d+96,c.maxBufferSize),p("maxVertexAttributes",104),p("maxVertexBufferArrayStride",108),p("maxInterStageShaderVariables",112),p("maxColorAttachments",116),p("maxColorAttachmentBytesPerSample",120),p("maxComputeWorkgroupStorageSize",124),p("maxComputeInvocationsPerWorkgroup",128),p("maxComputeWorkgroupSizeX",132),p("maxComputeWorkgroupSizeY",136),p("maxComputeWorkgroupSizeZ",140),p("maxComputeWorkgroupsPerDimension",144),c.Ae!==void 0&&p("maxImmediateSize",148)},cy=[,"validation","out-of-memory","internal"],uy=[,"compatibility","core"],kd={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"},dy=[,"low-power","high-performance"],hy=[,"occlusion","timestamp"],fy={undefined:1,unknown:1,destroyed:2};function _y(c,d,p,m,y,x){d=dt(d),p=dt(p),m>>>=0,y>>>=0,x>>>=0;var A=J(c>>>0);if(c={},x){var L=(T(),N)[x+12>>>2>>>0];if(L){var $=(T(),N)[x+16>>>2>>>0];c.requiredFeatures=Array.from((T(),N).subarray($>>>2>>>0,$+4*L>>>2>>>0),Q=>kd[Q])}var q=(T(),N)[x+20>>>2>>>0];if(q){let Q=function(Ae,Qe,Wn=!1){Qe=q+Qe,(Qe=(T(),N)[Qe>>>2>>>0])==4294967295||Wn&&Qe==0||(ve[Ae]=Qe)},fe=function(Ae,Qe){Qe=q+Qe;var Wn=(T(),N)[Qe>>>2>>>0],Lo=(T(),N)[Qe+4>>>2>>>0];Wn==4294967295&&Lo==4294967295||(ve[Ae]=Gn(Qe))};var ve={};Q("maxTextureDimension1D",4),Q("maxTextureDimension2D",8),Q("maxTextureDimension3D",12),Q("maxTextureArrayLayers",16),Q("maxBindGroups",20),Q("maxBindGroupsPlusVertexBuffers",24),Q("maxDynamicUniformBuffersPerPipelineLayout",32),Q("maxDynamicStorageBuffersPerPipelineLayout",36),Q("maxSampledTexturesPerShaderStage",40),Q("maxSamplersPerShaderStage",44),Q("maxStorageBuffersPerShaderStage",48),Q("maxStorageTexturesPerShaderStage",52),Q("maxUniformBuffersPerShaderStage",56),Q("minUniformBufferOffsetAlignment",80),Q("minStorageBufferOffsetAlignment",84),fe("maxUniformBufferBindingSize",64),fe("maxStorageBufferBindingSize",72),Q("maxVertexBuffers",88),fe("maxBufferSize",96),Q("maxVertexAttributes",104),Q("maxVertexBufferArrayStride",108),Q("maxInterStageShaderVariables",112),Q("maxColorAttachments",116),Q("maxColorAttachmentBytesPerSample",120),Q("maxComputeWorkgroupStorageSize",124),Q("maxComputeInvocationsPerWorkgroup",128),Q("maxComputeWorkgroupSizeX",132),Q("maxComputeWorkgroupSizeY",136),Q("maxComputeWorkgroupSizeZ",140),Q("maxComputeWorkgroupsPerDimension",144),Q("maxImmediateSize",148,!0),c.requiredLimits=ve}(L=(T(),N)[x+24>>>2>>>0])&&(L={label:sr(L+4)},c.defaultQueue=L),c.label=sr(x+4)}me+=1,tn(d,A.requestDevice(c).then(Q=>{--me,ht(()=>{tt[y>>>0]=Q.queue,tt[m>>>0]=Q,tn(p,Q.lost.then(fe=>{ht(()=>{Q.onuncapturederror=()=>{};var Ae=se(),Qe=qt(fe.message);Mo(p,fy[fe.reason],Qe),ne(Ae)})})),Q.onuncapturederror=fe=>{var Ae=5;fe.error instanceof GPUValidationError?Ae=2:fe.error instanceof GPUOutOfMemoryError?Ae=3:fe.error instanceof GPUInternalError&&(Ae=4);var Qe=se();fe=qt(fe.error.message),qd(m,Ae,fe),ne(Qe)},"adapterInfo"in Q||(Q.adapterInfo=A.info),ko(d,1,m,0)})},Q=>{--me,ht(()=>{var fe=se(),Ae=qt(Q.message);ko(d,3,m,Ae),p&&Mo(p,4,Ae),ne(fe)})}))}function py(c){var d=J(c>>>=0),p=nr[c];if(p){for(var m=0;m>>=0;var m=J(c>>>=0);p==4294967295&&(p=void 0);try{var y=m.getMappedRange(d>>>0,p)}catch{return 0}var x=So(16,y.byteLength);return(T(),U).set(new Uint8Array(y),x>>>0),nr[c].push(()=>It(x)),x}function gy(c,d,p){p>>>=0;var m=J(c>>>=0);p==4294967295&&(p=void 0);try{var y=m.getMappedRange(d>>>0,p)}catch{return 0}var x=So(16,y.byteLength);return(T(),U).fill(0,x,y.byteLength),nr[c].push(()=>{new Uint8Array(y).set((T(),U).subarray(x>>>0,x+y.byteLength>>>0)),It(x)}),x}function wy(c,d,p,m,y){c>>>=0,d=dt(d),p=dt(p),y>>>=0;var x=J(c);nr[c]=[],y==4294967295&&(y=void 0),me+=1,tn(d,x.mapAsync(p,m>>>0,y).then(()=>{--me,ht(()=>{xo(d,1,0)})},A=>{--me,ht(()=>{se();var L=qt(A.message);xo(d,A.name==="AbortError"?4:A.name==="OperationError"?3:0,L),delete nr[c]})}))}function vy(c){var d=J(c>>>=0),p=nr[c];if(p){for(var m=0;m>>0]}function by(c,d,p){c>>>=0,d>>>=0,p>>>=0;var m=!!(T(),N)[d+32>>>2>>>0];d={label:sr(d+4),usage:(T(),N)[d+16>>>2>>>0],size:Gn(d+24),mappedAtCreation:m},c=J(c);try{var y=c.createBuffer(d)}catch{return!1}return tt[p>>>0]=y,m&&(nr[p]=[]),!0}function My(c,d,p,m){c>>>=0,d=dt(d),m>>>=0,p=ly(p>>>0),c=J(c),me+=1,tn(d,c.createComputePipelineAsync(p).then(y=>{--me,ht(()=>{tt[m>>>0]=y,bo(d,1,m,0)})},y=>{--me,ht(()=>{var x=se(),A=qt(y.message);bo(d,y.reason==="validation"?3:y.reason==="internal"?4:0,m,A),ne(x)})}))}function xy(c,d,p){c>>>=0,d>>>=0,p>>>=0;var m=(T(),N)[d>>>2>>>0],y=(T(),D)[m+4>>>2>>>0];d={label:sr(d+4),code:""},y===2&&(d.code=xd(m+8)),c=J(c).createShaderModule(d),tt[p>>>0]=c}var Ty=c=>{(c=J(c)).onuncapturederror=null,c.destroy()};function ky(c,d){d=dt(d),c=J(c>>>0),me+=1,tn(d,c.popErrorScope().then(p=>{--me,ht(()=>{var m=5;p?p instanceof GPUValidationError?m=2:p instanceof GPUOutOfMemoryError?m=3:p instanceof GPUInternalError&&(m=4):m=1;var y=se(),x=p?qt(p.message):0;To(d,1,m,x),ne(y)})},p=>{--me,ht(()=>{var m=se(),y=qt(p.message);To(d,1,5,y),ne(m)})}))}function Ey(c,d,p,m){if(d=dt(d),m>>>=0,p>>>=0){var y={featureLevel:uy[(T(),D)[p+4>>>2>>>0]],powerPreference:dy[(T(),D)[p+8>>>2>>>0]],forceFallbackAdapter:!!(T(),N)[p+12>>>2>>>0]};(c=(T(),N)[p>>>2>>>0])!==0&&(T(),y.Fe=!!(T(),N)[c+8>>>2>>>0])}"gpu"in navigator?(me+=1,tn(d,navigator.gpu.requestAdapter(y).then(x=>{--me,ht(()=>{if(x)tt[m>>>0]=x,Vn(d,1,m,0);else{var A=se(),L=qt("WebGPU not available on this browser (requestAdapter returned null)");Vn(d,3,m,L),ne(A)}})},x=>{--me,ht(()=>{var A=se(),L=qt(x.message);Vn(d,4,m,L),ne(A)})}))):(y=se(),c=qt("WebGPU not available on this browser (navigator.gpu is not available)"),Vn(d,3,m,c),ne(y))}function Cy(c,d,p){return c>>>=0,d>>>=0,p>>>=0,_d(async()=>{var m=[];if(p){var y=(T(),D)[p>>>2>>>0];m.length=d+1,m[d]=new Promise(L=>setTimeout(L,y,0))}else m.length=d;for(var x=0;x{var m;if(!wo){var c,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(((m=globalThis.navigator)==null?void 0:m.language)??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in vo)vo[c]===void 0?delete d[c]:d[c]=vo[c];var p=[];for(c in d)p.push(`${c}=${d[c]}`);wo=p}return wo};function Cd(c,d){if(s)return te(19,1,c,d);c>>>=0,d>>>=0;var p,m=0,y=0;for(p of Ed()){var x=d+m;(T(),N)[c+y>>>2>>>0]=x,m+=tr(p,x,1/0)+1,y+=4}return 0}function Sd(c,d){if(s)return te(20,1,c,d);c>>>=0,d>>>=0;var p=Ed();for(var m of((T(),N)[c>>>2>>>0]=p.length,c=0,p))c+=rr(m)+1;return(T(),N)[d>>>2>>>0]=c,0}function Ad(c){return s?te(21,1,c):52}function Pd(c,d,p,m){return s?te(22,1,c,d,p,m):52}function Fd(c,d,p,m){return s?te(23,1,c,d,p,m):70}var Sy=[null,[],[]];function Ld(c,d,p,m){if(s)return te(24,1,c,d,p,m);d>>>=0,p>>>=0,m>>>=0;for(var y=0,x=0;x>>2>>>0],L=(T(),N)[d+4>>>2>>>0];d+=8;for(var $=0;$>>0],Q=Sy[q];ve===0||ve===10?((q===1?C:F)(Qu(Q)),Q.length=0):Q.push(ve)}y+=L}return(T(),N)[m>>>2>>>0]=y,0}function Ay(c){return c>>>0}function Py(c,d){return Td(J(c>>>0).limits,d>>>0),1}function Fy(c,d){return J(c>>>0).features.has(kd[d])}function Ly(c){return BigInt(J(c>>>0).size)}function Iy(c){return BigInt(J(c>>>0).usage)}function Oy(c,d){if(c>>>=0,d>>>=0){var p=sr(d+4);p={label:p,timestampWrites:d=(d=(T(),N)[d+12>>>2>>>0])!==0?{querySet:J((T(),N)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(T(),N)[d+8>>>2>>>0],endOfPassWriteIndex:(T(),N)[d+12>>>2>>>0]}:void 0}}return d=J(c),c=Gd(0),p=d.beginComputePass(p),tt[c>>>0]=p,c}function Ny(c,d,p,m,y,x){p=dt(p),y=dt(y),x=dt(x),J(c>>>0).copyBufferToBuffer(J(d>>>0),p,J(m>>>0),y,x)}function Dy(c){var d=J(c>>>0);return c=Rd(0),d=d.finish(),tt[c>>>0]=d,c}function By(c,d,p,m,y,x){x=dt(x),J(c>>>0).resolveQuerySet(J(d>>>0),p,m,J(y>>>0),x)}function zy(c,d,p,m){J(c>>>0).dispatchWorkgroups(d,p,m)}function Ry(c,d,p){p=dt(p),J(c>>>0).dispatchWorkgroupsIndirect(J(d>>>0),p)}function $y(c){J(c>>>0).end()}function Gy(c,d,p,m,y){m>>>=0,y>>>=0,c=J(c>>>0),p=J(p>>>0),m==0?c.setBindGroup(d,p):c.setBindGroup(d,p,(T(),N),y>>>2,m)}function Vy(c,d){J(c>>>0).setPipeline(J(d>>>0))}function Uy(c,d,p){J(c>>>0).Ee(J(d>>>0),p)}function Wy(c,d){var p=J(c>>>0);return c=zd(0),d=p.getBindGroupLayout(d),tt[c>>>0]=d,c}function jy(c,d){function p(y){var x=(T(),N)[y+8>>>2>>>0],A=(T(),N)[y+32>>>2>>>0],L=(T(),N)[y+36>>>2>>>0],$=0;return iy(y,{327681:q=>{$=(T(),N)[q+8>>>2>>>0]}}),x?((A=Gn(y+24))==-1&&(A=void 0),x={buffer:J(x),offset:Gn(y+16),size:A}):x=J(A||L||$),{binding:(T(),N)[y+4>>>2>>>0],resource:x}}c>>>=0,d={label:sr(4+(d>>>=0)),layout:J((T(),N)[d+12>>>2>>>0]),entries:(function(y,x){for(var A=[],L=0;L>>2>>>0],(T(),N)[d+20>>>2>>>0])},c=J(c);var m=Bd(0);return oy(m,c.createBindGroup(d)),m}function qy(c,d){var p;return c>>>=0,(d>>>=0)&&(p={label:sr(d+4)}),d=J(c),c=$d(0),p=d.createCommandEncoder(p),tt[c>>>0]=p,c}function Hy(c,d){c>>>=0,d>>>=0,d={type:hy[(T(),D)[d+12>>>2>>>0]],count:(T(),N)[d+16>>>2>>>0]};var p=J(c);return c=Vd(0),d=p.createQuerySet(d),tt[c>>>0]=d,c}function Qy(c,d){c=J(c>>>0).adapterInfo,d>>>=0,(T(),N)[d+52>>>2>>>0]=c.subgroupMinSize,(T(),N)[d+56>>>2>>>0]=c.subgroupMaxSize;var p=c.vendor+c.architecture+c.device+c.description,m=rr(p)+1,y=rn(m);return y&&tr(p,y,m),p=y,m=rr(c.vendor),Ns(d+4,p,m),p+=m,m=rr(c.architecture),Ns(d+12,p,m),p+=m,m=rr(c.device),Ns(d+20,p,m),Ns(d+28,p+m,rr(c.description)),(T(),D)[d+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(T(),D)[d+40>>>2>>>0]=c,(T(),N)[d+44>>>2>>>0]=0,(T(),N)[d+48>>>2>>>0]=0,1}var Xy={"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 Yy(c,d){d>>>=0;var p=J(c>>>0);c=rn(4*p.features.size);var m=0,y=0;for(let x of p.features)0<=(p=Xy[x])&&((T(),D)[c+m>>>2>>>0]=p,m+=4,y++);(T(),N)[d+4>>>2>>>0]=c,(T(),N)[d>>>2>>>0]=y}function Ky(c,d){return Td(J(c>>>0).limits,d>>>0),1}function Jy(c,d){J(c>>>0).pushErrorScope(cy[d])}function Zy(c,d,p){d>>>=0,p>>>=0,c=J(c>>>0),d=Array.from((T(),D).subarray(p>>>2>>>0,p+4*d>>>2>>>0),m=>J(m)),c.submit(d)}function eb(c,d,p,m,y){p=dt(p),m>>>=0,y>>>=0,c=J(c>>>0),d=J(d>>>0),m=(T(),U).subarray(m>>>0,m+y>>>0),c.writeBuffer(d,p,m,0,y)}s||(function(){for(var c=t.numThreads-1;c--;)Gu();at.push(async()=>{var d=(async function(){if(!s)return Promise.all(Ve.map($u))})();Je++,await d,--Je==0&&De&&(d=De,De=null,d())})})(),s||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),re()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>se(),t.stackRestore=c=>ne(c),t.stackAlloc=c=>Bs(c),t.setValue=function(c,d,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":(T(),R)[c>>>0]=d;break;case"i16":(T(),Z)[c>>>1>>>0]=d;break;case"i32":(T(),D)[c>>>2>>>0]=d;break;case"i64":(T(),ee)[c>>>3>>>0]=BigInt(d);break;case"float":(T(),ie)[c>>>2>>>0]=d;break;case"double":(T(),K)[c>>>3>>>0]=d;break;case"*":(T(),N)[c>>>2>>>0]=d;break;default:pe(`invalid type for setValue: ${p}`)}},t.getValue=function(c,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(T(),R)[c>>>0];case"i16":return(T(),Z)[c>>>1>>>0];case"i32":return(T(),D)[c>>>2>>>0];case"i64":return(T(),ee)[c>>>3>>>0];case"float":return(T(),ie)[c>>>2>>>0];case"double":return(T(),K)[c>>>3>>>0];case"*":return(T(),N)[c>>>2>>>0];default:pe(`invalid type for getValue: ${d}`)}},t.UTF8ToString=Zr,t.stringToUTF8=tr,t.lengthBytesUTF8=rr;var Id,Od,yo,Ds,It,rn,Nd,Dd,Bd,zd,Rd,$d,Gd,Vd,Ud,Wd,jd,bo,Mo,xo,To,Vn,ko,qd,Eo,Hd,Qd,Xd,Co,Yd,Kd,So,he,Un,Jd,ne,Bs,se,Zd,Ao,eh,th,rh,Po,nh,sh,ah,oh,ih,lh,ch,uh,dh,hh,fh,_h,ph,mh,gh,wh,vh,yh,bh,Mh,xh,Th,kh,Eh,Ch,Sh,Ah,Ph,Fh,Lh,Ih,Oh,Nh,Dh,Bh,zh,Rh,$h,Gh,ar,tb=[ke,Ze,Wu,Xu,Yu,Ku,Ju,Zu,ed,td,rd,nd,sd,ad,od,id,vd,yd,bd,Cd,Sd,Ad,Pd,Fd,Ld],Fo={923180:(c,d,p,m,y)=>{if(t===void 0||!t.Uc)return 1;if((c=Zr(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=t.Uc.get(c)))return 2;if(d=Number(d>>>0),p=Number(p>>>0),m=Number(m>>>0),d+p>c.byteLength)return 3;try{let x=c.subarray(d,d+p);switch(y){case 0:(T(),U).set(x,m>>>0);break;case 1:t.ad?t.ad(m,x):t.oe(m,x);break;default:return 4}return 0}catch{return 4}},924004:(c,d,p)=>{t.Sd(c,(T(),U).subarray(d>>>0,d+p>>>0))},924068:()=>t.me(),924110:c=>{t.jd(c)},924147:()=>typeof wasmOffsetConverter<"u"};function rb(c,d,p,m){var y=se();try{return uh(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function nb(c,d,p){var m=se();try{return ih(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;he(1,0)}}function sb(c,d,p){var m=se();try{rh(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;he(1,0)}}function ab(c,d){var p=se();try{return Po(c,d)}catch(m){if(ne(p),m!==m+0)throw m;he(1,0)}}function ob(c){var d=se();try{nh(c)}catch(p){if(ne(d),p!==p+0)throw p;he(1,0)}}function ib(c,d,p,m,y,x,A){var L=se();try{return oh(c,d,p,m,y,x,A)}catch($){if(ne(L),$!==$+0)throw $;he(1,0)}}function lb(c,d){var p=se();try{dh(c,d)}catch(m){if(ne(p),m!==m+0)throw m;he(1,0)}}function cb(c,d,p,m,y,x){var A=se();try{sh(c,d,p,m,y,x)}catch(L){if(ne(A),L!==L+0)throw L;he(1,0)}}function ub(c,d,p,m){var y=se();try{ch(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function db(c,d,p,m,y,x,A){var L=se();try{fh(c,d,p,m,y,x,A)}catch($){if(ne(L),$!==$+0)throw $;he(1,0)}}function hb(c,d,p,m,y,x,A){var L=se();try{_h(c,d,p,m,y,x,A)}catch($){if(ne(L),$!==$+0)throw $;he(1,0)}}function fb(c,d,p,m,y,x,A,L){var $=se();try{xh(c,d,p,m,y,x,A,L)}catch(q){if(ne($),q!==q+0)throw q;he(1,0)}}function _b(c,d,p,m,y,x,A,L,$,q,ve,Q){var fe=se();try{ph(c,d,p,m,y,x,A,L,$,q,ve,Q)}catch(Ae){if(ne(fe),Ae!==Ae+0)throw Ae;he(1,0)}}function pb(c,d,p,m,y){var x=se();try{return hh(c,d,p,m,y)}catch(A){if(ne(x),A!==A+0)throw A;he(1,0)}}function mb(c,d,p,m,y){var x=se();try{ah(c,d,p,m,y)}catch(A){if(ne(x),A!==A+0)throw A;he(1,0)}}function gb(c,d,p,m,y,x,A,L){var $=se();try{lh(c,d,p,m,y,x,A,L)}catch(q){if(ne($),q!==q+0)throw q;he(1,0)}}function wb(c){var d=se();try{return Th(c)}catch(p){if(ne(d),p!==p+0)throw p;he(1,0)}}function vb(c,d,p){var m=se();try{return kh(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;he(1,0)}}function yb(c,d){var p=se();try{return Bh(c,d)}catch(m){if(ne(p),m!==m+0)throw m;return he(1,0),0n}}function bb(c,d,p,m,y){var x=se();try{Eh(c,d,p,m,y)}catch(A){if(ne(x),A!==A+0)throw A;he(1,0)}}function Mb(c){var d=se();try{return mh(c)}catch(p){if(ne(d),p!==p+0)throw p;return he(1,0),0n}}function xb(c,d,p,m,y,x){var A=se();try{return bh(c,d,p,m,y,x)}catch(L){if(ne(A),L!==L+0)throw L;he(1,0)}}function Tb(c,d,p,m,y,x){var A=se();try{return Ch(c,d,p,m,y,x)}catch(L){if(ne(A),L!==L+0)throw L;he(1,0)}}function kb(c,d,p,m,y,x){var A=se();try{return Sh(c,d,p,m,y,x)}catch(L){if(ne(A),L!==L+0)throw L;he(1,0)}}function Eb(c,d,p,m,y,x,A,L){var $=se();try{return Mh(c,d,p,m,y,x,A,L)}catch(q){if(ne($),q!==q+0)throw q;he(1,0)}}function Cb(c,d,p,m,y){var x=se();try{return Ah(c,d,p,m,y)}catch(A){if(ne(x),A!==A+0)throw A;return he(1,0),0n}}function Sb(c,d,p,m){var y=se();try{return Ph(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function Ab(c,d,p,m){var y=se();try{return Fh(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function Pb(c,d,p,m,y,x,A,L,$,q,ve,Q){var fe=se();try{return Lh(c,d,p,m,y,x,A,L,$,q,ve,Q)}catch(Ae){if(ne(fe),Ae!==Ae+0)throw Ae;he(1,0)}}function Fb(c,d,p,m,y,x,A,L,$,q,ve){var Q=se();try{Ih(c,d,p,m,y,x,A,L,$,q,ve)}catch(fe){if(ne(Q),fe!==fe+0)throw fe;he(1,0)}}function Lb(c,d,p,m,y,x,A,L,$,q,ve,Q,fe,Ae,Qe,Wn){var Lo=se();try{Oh(c,d,p,m,y,x,A,L,$,q,ve,Q,fe,Ae,Qe,Wn)}catch(Io){if(ne(Lo),Io!==Io+0)throw Io;he(1,0)}}function Ib(c,d,p,m){var y=se();try{return Nh(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function Ob(c,d,p,m,y){var x=se();try{return Dh(c,d,p,m,y)}catch(A){if(ne(x),A!==A+0)throw A;he(1,0)}}function Nb(c,d,p){var m=se();try{return wh(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;return he(1,0),0n}}function Db(c,d,p){var m=se();try{return gh(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;he(1,0)}}function Bb(c,d,p){var m=se();try{return vh(c,d,p)}catch(y){if(ne(m),y!==y+0)throw y;he(1,0)}}function zb(c,d,p,m){var y=se();try{yh(c,d,p,m)}catch(x){if(ne(y),x!==x+0)throw x;he(1,0)}}function zs(){if(0{let d=new WeakMap,p,m,y=1;t.webgpuRegisterDevice=L=>{if(m!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var $=d.get(L);if(!$){let q=((ve,Q=0)=>{var fe=jd(Q);return Q=Wd(Q,fe),tt[fe>>>0]=ve.queue,tt[Q>>>0]=ve,Q})(L,$=Dd(0));$=[y++,$,q],d.set(L,$)}return p=L,m=$[0],$}p=void 0,m=0};let x=new Map;t.webgpuOnCreateSession=L=>{if(m!==void 0){var $=m;if(m=void 0,L){let q=yo($);x.set(L,q),$===0&&c(p??J(q))}p=void 0}},t.webgpuOnReleaseSession=L=>{x.delete(L)};let A=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(L,$,q)=>{if(q)return L[A]=[q,NaN],q;if(q=L[A])return q[1]++,q[0];if(($=x.get($))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return $=((ve,Q=0)=>(ve.mapState==="unmapped"||pe(),Q=Ud(Q),tt[Q>>>0]=ve,Q))(L,$),L[A]=[$,1],$},t.webgpuUnregisterBuffer=L=>{let $=L[A];if(!$)throw Error("Buffer is not registered");$[1]--,$[1]===0&&(Nd($[0]),delete L[A])},t.webgpuGetBuffer=L=>J(L),t.webgpuCreateDownloader=(L,$,q)=>{if((q=x.get(q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ve=J(q),Q=16*Math.ceil(Number($)/16);return async()=>{let fe=ve.createBuffer({size:Q,usage:9});try{let Ae=ve.createCommandEncoder();return Ae.copyBufferToBuffer(L,0,fe,0,Q),ve.queue.submit([Ae.finish()]),await fe.mapAsync(GPUMapMode.READ),fe.getMappedRange().slice(0,$)}finally{fe.destroy()}}},t.ad=(L,$)=>{var q=$.buffer;let ve=$.byteOffset,Q=$.byteLength;if($=16*Math.ceil(Number(Q)/16),L=J(L),!p){var fe=yo(m);p=J(fe)}let Ae=(fe=p.createBuffer({mappedAtCreation:!0,size:$,usage:6})).getMappedRange();new Uint8Array(Ae).set(new Uint8Array(q,ve,Q)),fe.unmap(),(q=p.createCommandEncoder()).copyBufferToBuffer(fe,0,L,0,$),p.queue.submit([q.finish()]),fe.destroy()}},t.webnnInit=c=>{let d=c[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=c.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=p=>d.onRunStart(p),t.webnnOnRunEnd=d.onRunEnd.bind(d),t.webnnOnReleaseSession=p=>{d.onReleaseSession(p)},t.webnnCreateMLTensorDownloader=(p,m)=>d.createMLTensorDownloader(p,m),t.webnnRegisterMLTensor=(p,m,y,x)=>d.registerMLTensor(p,m,y,x),t.webnnCreateMLContext=p=>d.createMLContext(p),t.webnnRegisterMLConstant=(p,m,y,x,A,L)=>d.registerMLConstant(p,m,y,x,A,t.Uc,L),t.webnnRegisterGraphInput=d.registerGraphInput.bind(d),t.webnnIsGraphInput=d.isGraphInput.bind(d),t.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),t.webnnIsGraphOutput=d.isGraphOutput.bind(d),t.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),t.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},z?t:new Promise((c,d)=>{w=c,v=d})}var V_,qh,o0=we(()=>{var e,t;V_=jh,qh=(t=(e=globalThis.self)==null?void 0:e.name)==null?void 0:t.startsWith("em-pthread"),qh&&jh()}),Ro,ji,Hh,yt,U_,$s,Qh,Xh,$o,Yh,Go,W_,Vo,j_,ul=we(()=>{cl(),Ro=typeof location>"u"?void 0:location.origin,ji=import.meta.url>"file:"&&import.meta.url<"file;",Hh=()=>{{if(ji){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,Ro).href}return import.meta.url}},yt=Hh(),U_=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},$s=(e,t)=>{try{let r=t??yt;return(r?new URL(e,r):new URL(e)).origin===Ro}catch{return!1}},Qh=(e,t)=>{let r=t??yt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Xh=(e,t)=>`${t??"./"}${e}`,$o=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Yh=async e=>(await import(e)).default,Go=(a0(),va(R_)).default,W_=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($s(yt))return[void 0,Go()];let e=await $o(yt);return[e,Go(e)]},Vo=(o0(),va(G_)).default,j_=async(e,t,r,n)=>{let s=Vo&&!(e||t);if(s)if(yt)s=$s(yt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,Vo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Qh(a,t),i=r&&o&&!$s(o,t),l=i?await $o(o):o??Xh(a,t);return[i?l:void 0,await Yh(l)]}}}),Uo,Gs,qn,Wo,Kh,Jh,Zh,dl,Se,Xr=we(()=>{ul(),Gs=!1,qn=!1,Wo=!1,Kh=()=>{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}},Jh=()=>{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}},Zh=()=>{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}},dl=async e=>{if(Gs)return Promise.resolve();if(qn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wo)throw new Error("previous call to 'initializeWebAssembly()' failed.");qn=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Zh())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Jh())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Kh();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,o=s==null?void 0:s.mjs,i=(o==null?void 0:o.href)??o,l=s==null?void 0:s.wasm,u=(l==null?void 0:l.href)??l,h=e.wasmBinary,[f,_]=await j_(i,a,r>1,!!h||!!u),g=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{g=!0,v()},t)})),w.push(new Promise((v,b)=>{let k={numThreads:r};if(h)k.wasmBinary=h,k.locateFile=E=>E;else if(u||a)k.locateFile=E=>u??a+E;else if(i&&i.indexOf("blob:")!==0)k.locateFile=E=>new URL(E,i).href;else if(f){let E=U_();E&&(k.locateFile=C=>E+C)}_(k).then(E=>{qn=!1,Gs=!0,Uo=E,v(),f&&URL.revokeObjectURL(f)},E=>{qn=!1,Wo=!0,b(E)})})),await Promise.race(w),g)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Se=()=>{if(Gs&&Uo)return Uo;throw new Error("WebAssembly is not initialized yet.")}}),bt,ba,Te,hl=we(()=>{Xr(),bt=(e,t)=>{let r=Se(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},ba=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let o=t?t+s:s;if(typeof a=="object")ba(a,o+".",r,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Te=e=>{let t=Se(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),o=t.getValue(s+n,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),q_,i0=we(()=>{Xr(),hl(),q_=e=>{let t=Se(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=bt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Te("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ba(e.extra,"",new WeakSet,(o,i)=>{let l=bt(o,n),u=bt(i,n);t._OrtAddRunConfigEntry(r,l,u)!==0&&Te(`Can't set a run config entry: ${o} - ${i}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),a}}}),ef,tf,rf,Vs,pr,nf,H_,l0=we(()=>{Xr(),hl(),ef=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}`)}},tf=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},rf=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)},Vs=(e,t,r,n)=>{let s=bt(t,n),a=bt(r,n);Se()._OrtAddSessionConfigEntry(e,s,a)!==0&&Te(`Can't set a session config entry: ${t} - ${r}.`)},pr=(e,t,r,n)=>{let s=bt(t,n),a=bt(r,n);e.push([s,a])},nf=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let f=s==null?void 0:s.deviceType;f&&Vs(e,"deviceType",f,r)}break;case"webgpu":{a="WebGPU";let f;if(typeof s!="string"){let g=s;if(g.device)if(typeof GPUDevice<"u"&&g.device instanceof GPUDevice)f=g.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&pr(o,"enableGraphCapture","1",r),typeof g.preferredLayout=="string"&&pr(o,"preferredLayout",g.preferredLayout,r),g.forceCpuNodeNames){let v=Array.isArray(g.forceCpuNodeNames)?g.forceCpuNodeNames:[g.forceCpuNodeNames];pr(o,"forceCpuNodeNames",v.join(`
+`),r)}g.validationMode&&pr(o,"validationMode",g.validationMode,r)}let _=Se().webgpuRegisterDevice(f);if(_){let[g,w,v]=_;pr(o,"deviceId",g.toString(),r),pr(o,"webgpuInstance",w.toString(),r),pr(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=bt(a,r),l=o.length,u=0,h=0;if(l>0){u=Se()._malloc(l*Se().PTR_SIZE),r.push(u),h=Se()._malloc(l*Se().PTR_SIZE),r.push(h);for(let f=0;f{let t=Se(),r=0,n=[],s=e||{};rf(s);try{let a=ef(s.graphOptimizationLevel??"all"),o=tf(s.executionMode??"sequential"),i=typeof s.logId=="string"?bt(s.logId,n):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let u=s.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let h=typeof s.optimizedModelFilePath=="string"?bt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,u,h),r===0&&Te("Can't create session options."),s.executionProviders&&await nf(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Vs(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[f,_]of Object.entries(s.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let g=bt(f,n);t._OrtAddFreeDimensionOverride(r,g,_)!==0&&Te(`Can't set a free dimension override: ${f} - ${_}.`)}return s.extra!==void 0&&ba(s.extra,"",new WeakSet,(f,_)=>{Vs(r,f,_,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Te("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Rr,ha,cn,fs,Ma,fl,_l,qi,yn=we(()=>{Rr=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}`)}},ha=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}`)}},cn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},fs=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}`)}},Ma=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}`)}},fl=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",_l=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",qi=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}`)}}}),pl,Q_=we(()=>{cl(),pl=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(i){if(i instanceof RangeError){let l=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;let u=l.byteLength;new Uint8Array(a,o,u).set(l),o+=u}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),X_,c0=we(()=>{yn(),X_=(e,t)=>new(fs(t))(e)}),sf,af,of,lf,Y_,cf,it,K_=we(()=>{yn(),sf=["V","I","W","E","F"],af=(e,t)=>{console.log(`[${sf[e]},${new Date().toISOString()}]${t}`)},Y_=(e,t)=>{of=e,lf=t},cf=(e,t)=>{let r=Ma(e),n=Ma(of);r>=n&&af(r,typeof t=="function"?t():t)},it=(...e)=>{lf&&cf(...e)}}),jo,Hi,qo,uf,Ho,df,Qo,Xo,Yo,hf,J_,u0=we(()=>{yn(),K_(),jo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Hi=(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 n=r/8;if(e.byteLength%n!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(fs(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i2147483647n||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'`)}},qo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},uf=1,Ho=()=>uf++,df=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((n,s)=>n*s)*r/8):0},Xo=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Qo(this.dataType,this.tensorShape)}destroy(){it("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=qo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},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,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!(a!=null&&a.input.dataTypes.includes(t))){if(o=df.get(t),!o||(a==null?void 0:a.input.dataTypes.includes(o)))throw new Error(`WebNN backend does not support data type: ${t}`);it("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==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),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Hi(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 it("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 n=(t=this.wrapper)!=null&&t.isDataConverted?qo(this.activeUpload,(r=this.wrapper)==null?void 0:r.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(n):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(n);return}else return n.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},hf=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,n,s){it("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){it("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,n){let s=this.getMLContext(e),a=Ho(),o=new Xo({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new Yo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[u,h]of this.freeTensors.entries())if(h.canReuseTensor(i,t,r)){it("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=e,f}it("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new 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)}},J_=(...e)=>new hf(...e)}),Z_={};ms(Z_,{WebNNBackend:()=>ep});var Hn,ff,ep,d0=we(()=>{yn(),Xr(),c0(),u0(),K_(),Hn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ff=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},ep=class{constructor(e){this.tensorManager=J_(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,Y_(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){it("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){it("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)it("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>ff(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){it("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=Hn.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){it("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=Hn.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!Se().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");it("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 X_(r,t)}}registerMLTensor(e,t,r,n){let s=Hn.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return it("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(t,t+r).buffer,h;switch(s.dataType){case"float32":h=new Float32Array(u);break;case"float16":h=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":h=new Int32Array(u);break;case"uint32":h=new Uint32Array(u);break;case"int64":if(o){let f=Hi(new Uint8Array(u),"int64");h=new Int32Array(f.buffer),s.dataType="int32"}else h=new BigInt64Array(u);break;case"uint64":h=new BigUint64Array(u);break;case"int8":h=new Int8Array(u);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return it("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,h)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=Hn.get(Rr(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!(s!=null&&s.input.dataTypes.includes(n)):!!(s!=null&&s.output.dataTypes.includes(n))}flush(){}}}),_f,ml,gl,mr,pf,Ko,xa,wl,vl,Jo,yl,bl,Ml,tp=we(()=>{Qr(),i0(),l0(),yn(),Xr(),hl(),Q_(),_f=(e,t)=>{Se()._OrtInit(e,t)!==0&&Te("Can't initialize onnxruntime.")},ml=async e=>{_f(e.wasm.numThreads,Ma(e.logLevel))},gl=async(e,t)=>{var n,s;(s=(n=Se()).asyncInit)==null||s.call(n);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(d0(),va(Z_)).WebNNBackend(e);Se().webnnInit([a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,i,l,u,h)=>a.ensureTensor(o,i,l,u,h),(o,i)=>{a.uploadTensor(o,i)},async(o,i)=>a.downloadTensor(o,i),(o,i)=>a.registerMLContext(o,i),!!e.trace])}},mr=new Map,pf=e=>{let t=Se(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&Te("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},Ko=(e,t)=>{let r=Se(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&Te("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));s=Number(r.getValue(o+a,"*"));let l=r.HEAP32[s/4];if(l===0)return[i,0];let u=r.HEAPU32[s/4+1],h=[];for(let f=0;f{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]},wl=async(e,t)=>{var f,_,g,w;let r,n,s=Se();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=xa(e);let a=0,o=0,i=0,l=[],u=[],h=[];try{if([o,l]=await H_(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let V=[];for(let R of t.externalData){let U=typeof R=="string"?R:R.path;V.push(pl(typeof R=="string"?R:R.data).then(Z=>{s.mountExternalData(U,Z)}))}await Promise.all(V)}for(let V of(t==null?void 0:t.executionProviders)??[])if((typeof V=="string"?V:V.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof V!="string"){let R=V,U=R==null?void 0:R.context,Z=R==null?void 0:R.gpuDevice,H=R==null?void 0:R.deviceType,D=R==null?void 0:R.powerPreference;U?s.currentContext=U:Z?s.currentContext=await s.webnnCreateMLContext(Z):s.currentContext=await s.webnnCreateMLContext({deviceType:H,powerPreference:D})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),(f=s.webgpuOnCreateSession)==null||f.call(s,a),a===0&&Te("Can't create a session."),(_=s.jsepOnCreateSession)==null||_.call(s),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[v,b]=pf(a),k=!!(t!=null&&t.enableGraphCapture),E=[],C=[],F=[],O=[],G=[];for(let V=0;VV==="gpu-buffer"||V==="ml-tensor"||V==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&Te("Can't create IO binding."),T={handle:i,outputPreferredLocations:G,outputPreferredLocationsEncoded:G.map(V=>V==="ml-tensor-cpu-output"?"ml-tensor":V).map(V=>qi(V))}),mr.set(a,[a,u,h,T,k,!1]),[a,E,C,F,O]}catch(v){throw u.forEach(b=>s._OrtFree(b)),h.forEach(b=>s._OrtFree(b)),i!==0&&s._OrtReleaseBinding(i)!==0&&Te("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&Te("Can't release session."),v}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&Te("Can't release session options."),l.forEach(v=>s._free(v)),(w=s.unmountExternalData)==null||w.call(s)}},vl=e=>{var l,u,h;let t=Se(),r=mr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&Te("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&Te("Can't release IO binding.")),(l=t.jsepOnReleaseSession)==null||l.call(t,e),(u=t.webnnOnReleaseSession)==null||u.call(t,e),(h=t.webgpuOnReleaseSession)==null||h.call(t,e),s.forEach(f=>t._OrtFree(f)),a.forEach(f=>t._OrtFree(f)),t._OrtReleaseSession(n)!==0&&Te("Can't release session."),mr.delete(e)},Jo=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Se(),l=i.PTR_SIZE,u=e[0],h=e[1],f=e[3],_=f,g,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let k=e[2].gpuBuffer;w=cn(Rr(u),h);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=E(k,n)}}else if(f==="ml-tensor"){let k=e[2].mlTensor;w=cn(Rr(u),h);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=E(n,k,Rr(u),h)}else{let k=e[2];if(Array.isArray(k)){w=l*k.length,g=i._malloc(w),r.push(g);for(let E=0;Ei.setValue(b+C*l,E,l===4?"i32":"i64"));let k=i._OrtCreateTensor(Rr(u),g,w,b,h.length,qi(_));k===0&&Te(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(k)}finally{i.stackRestore(v)}},yl=async(e,t,r,n,s,a)=>{var H,D,N,ie;let o=Se(),i=o.PTR_SIZE,l=mr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],h=l[1],f=l[2],_=l[3],g=l[4],w=l[5],v=t.length,b=n.length,k=0,E=[],C=[],F=[],O=[],G=[],T=o.stackSave(),V=o.stackAlloc(v*i),R=o.stackAlloc(v*i),U=o.stackAlloc(b*i),Z=o.stackAlloc(b*i);try{[k,E]=q_(a),Mr("wasm prepareInputOutputTensor");for(let S=0;Ste*ke,1);ue=ha(st);let me=_==null?void 0:_.outputPreferredLocations[n[S]];if(ue==="string"){if(me==="gpu-buffer"||me==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let te=[];for(let ke=0;ke0){let te=o.webgpuGetBuffer;if(!te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=te(Pe),Ze=cn(st,He);if(Ze===void 0||!fl(ue))throw new Error(`Unsupported data type: ${ue}`);pe=!0;{o.webgpuRegisterBuffer(ke,e,Pe);let Et=o.webgpuCreateDownloader(ke,Ze,e);ee.push([ue,De,{gpuBuffer:ke,download:async()=>{let Ve=await Et();return new(fs(ue))(Ve)},dispose:()=>{o._OrtReleaseTensor(z)!==0&&Te("Can't release tensor.")}},"gpu-buffer"])}}else if(me==="ml-tensor"&&He>0){let te=o.webnnEnsureTensor,ke=o.webnnIsGraphInputOutputTypeSupported;if(!te||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(st,He)===void 0||!_l(ue))throw new Error(`Unsupported data type: ${ue}`);if(!ke(e,ue,!1))throw new Error(`preferredLocation "ml-tensor" for ${ue} output is not supported by current WebNN Context.`);let Ze=await te(e,Pe,st,De,!1);pe=!0,ee.push([ue,De,{mlTensor:Ze,download:o.webnnCreateMLTensorDownloader(Pe,ue),dispose:()=>{o.webnnReleaseTensorId(Pe),o._OrtReleaseTensor(z)}},"ml-tensor"])}else if(me==="ml-tensor-cpu-output"&&He>0){let te=o.webnnCreateMLTensorDownloader(Pe,ue)(),ke=ee.length;pe=!0,I.push((async()=>{let Ze=[ke,await te];return o.webnnReleaseTensorId(Pe),o._OrtReleaseTensor(z),Ze})()),ee.push([ue,De,[],"cpu"])}else{let te=fs(ue),ke=new te(He);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(o.HEAPU8.subarray(Pe,Pe+ke.byteLength)),ee.push([ue,De,ke,"cpu"])}}finally{o.stackRestore(re),ue==="string"&&Pe&&o._free(Pe),pe||o._OrtReleaseTensor(z)}}_&&!g&&(o._OrtClearBoundOutputs(_.handle)!==0&&Te("Can't clear bound outputs."),mr.set(e,[u,h,f,_,g,!1]));for(let[S,z]of await Promise.all(I))ee[S][2]=z;return xr("wasm ProcessOutputTensor"),ee}finally{(ie=o.webnnOnRunEnd)==null||ie.call(o,u),o.stackRestore(T),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(K[2].gpuBuffer)}),s.forEach(K=>{K&&K[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(K[2].gpuBuffer)}),C.forEach(K=>o._OrtReleaseTensor(K)),F.forEach(K=>o._OrtReleaseTensor(K)),O.forEach(K=>o._free(K)),k!==0&&o._OrtReleaseRunOptions(k),E.forEach(K=>o._free(K))}},bl=e=>{let t=Se(),r=mr.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Te("Can't get an profile file name."),t._OrtFree(s)},Ml=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),gr,_t,nn,Qn,Xn,Us,Zo,Ws,Lr,Ir,mf,rp,np,sp,ap,op,ip,lp,cp=we(()=>{Qr(),tp(),Xr(),ul(),gr=()=>!!Be.wasm.proxy&&typeof document<"u",nn=!1,Qn=!1,Xn=!1,Ws=new Map,Lr=(e,t)=>{let r=Ws.get(e);r?r.push(t):Ws.set(e,[t])},Ir=()=>{if(nn||!Qn||Xn||!_t)throw new Error("worker not ready")},mf=e=>{switch(e.data.type){case"init-wasm":nn=!1,e.data.err?(Xn=!0,Zo[1](e.data.err)):(Qn=!0,Zo[0]()),Us&&(URL.revokeObjectURL(Us),Us=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ws.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},rp=async()=>{if(!Qn){if(nn)throw new Error("multiple calls to 'initWasm()' detected.");if(Xn)throw new Error("previous call to 'initWasm()' failed.");if(nn=!0,gr())return new Promise((e,t)=>{_t==null||_t.terminate(),W_().then(([r,n])=>{try{_t=n,_t.onerror=a=>t(a),_t.onmessage=mf,Zo=[e,t];let s={type:"init-wasm",in:Be};!s.in.wasm.wasmPaths&&(r||ji)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-COni_aV6.wasm",import.meta.url).href}),_t.postMessage(s),Us=r}catch(s){t(s)}},t)});try{await dl(Be.wasm),await ml(Be),Qn=!0}catch(e){throw Xn=!0,e}finally{nn=!1}}},np=async e=>{if(gr())return Ir(),new Promise((t,r)=>{Lr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:Be}};_t.postMessage(n)});await gl(Be,e)},sp=async e=>gr()?(Ir(),new Promise((t,r)=>{Lr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};_t.postMessage(n,[e.buffer])})):xa(e),ap=async(e,t)=>{if(gr()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ir(),new Promise((r,n)=>{Lr("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),_t.postMessage(s,a)})}else return wl(e,t)},op=async e=>{if(gr())return Ir(),new Promise((t,r)=>{Lr("release",[t,r]);let n={type:"release",in:e};_t.postMessage(n)});vl(e)},ip=async(e,t,r,n,s,a)=>{if(gr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ir(),new Promise((o,i)=>{Lr("run",[o,i]);let l=r,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};_t.postMessage(u,Ml(l))})}else return yl(e,t,r,n,s,a)},lp=async e=>{if(gr())return Ir(),new Promise((t,r)=>{Lr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};_t.postMessage(n)});bl(e)}}),ei,gf,up,h0=we(()=>{Qr(),cp(),yn(),cl(),Q_(),ei=(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()}`)}},gf=e=>{switch(e[3]){case"cpu":return new Ot(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!fl(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Ot.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!_l(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Ot.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},up=class{async fetchModelAndCopyToWasmMemory(e){return sp(await pl(e))}async loadModel(e,t){qr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ap(r,t),Hr()}async dispose(){return op(this.sessionId)}async run(e,t,r){qr();let n=[],s=[];Object.entries(e).forEach(f=>{let _=f[0],g=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);n.push(g),s.push(w)});let a=[],o=[];Object.entries(t).forEach(f=>{let _=f[0],g=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(g),o.push(w)});let i=n.map((f,_)=>ei(f,()=>`input "${this.inputNames[s[_]]}"`)),l=a.map((f,_)=>f?ei(f,()=>`output "${this.outputNames[o[_]]}"`):null),u=await ip(this.sessionId,s,i,o,l,r),h={};for(let f=0;fXi,initializeFlags:()=>Qi,wasmBackend:()=>hp});var Qi,Xi,hp,f0=we(()=>{Qr(),cp(),h0(),Qi=()=>{(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"?Wb("node:os").cpus().length:navigator.hardwareConcurrency;Be.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Xi=class{async init(e){Qi(),await rp(),await np(e)}async createInferenceSessionHandler(e,t){let r=new up;return await r.loadModel(e,t),r}},hp=new Xi});Qr();Qr();Qr();var _0="1.25.0-dev.20260303-e7e64dc112",p0=z_;{let e=(f0(),va(dp)).wasmBackend;$r("webgpu",e,5),$r("webnn",e,5),$r("cpu",e,10),$r("wasm",e,10)}Object.defineProperty(Be.versions,"web",{value:_0,enumerable:!0});const m0=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return ll},get TRACE(){return ya},get TRACE_EVENT_BEGIN(){return Mr},get TRACE_EVENT_END(){return xr},get TRACE_FUNC_BEGIN(){return qr},get TRACE_FUNC_END(){return Hr},get Tensor(){return Ot},default:p0,get env(){return Be},get registerBackend(){return $r}},Symbol.toStringTag,{value:"Module"})),g0=(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 n=r.getContext("2d");if(n!=null){let s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=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,u;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?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));const h=a*s;let f=0,_=h,g=h*2,w=-1;o==="RGBA"?(f=0,_=h,g=h*2,w=h*3):o==="RGB"?(f=0,_=h,g=h*2):o==="RBG"&&(f=0,g=h,_=h*2);for(let v=0;v{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let s,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm;let u,h;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?h=[0,0,0,0]:typeof l.bias=="number"?h=[l.bias,l.bias,l.bias,l.bias]:(h=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(h[3]=l.bias[3]));const f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let g=0,w=1,v=2,b=3,k=0,E=f,C=f*2,F=-1;i==="RGBA"?(k=0,E=f,C=f*2,F=f*3):i==="RGB"?(k=0,E=f,C=f*2):i==="RBG"&&(k=0,C=f,E=f*2),n=r.createImageData(s,a);for(let O=0;O{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:n}=t,s=t.norm??{mean:255,bias:0};let a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=r*n,h=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let f=4,_=0,g=1,w=2,v=3,b=0,k=u,E=u*2,C=-1;i==="RGB"&&(f=3,_=0,g=1,w=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?(b=0,E=u,k=u*2):l==="BGR"&&(E=0,k=u,b=u*2);for(let O=0;O{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";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")},u=h=>typeof HTMLCanvasElement<"u"&&h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas?h.getContext("2d"):null;if(r){const h=l();h.width=e.width,h.height=e.height;const f=u(h);if(f!=null){let _=e.height,g=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,g=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=g}else i.tensorFormat="RGBA",i.height=_,i.width=g;f.drawImage(e,0,0),o=f.getImageData(0,0,g,_).data}else throw new Error("Can not access image data")}else if(n){let h,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(h=t.resizedHeight,f=t.resizedWidth):(h=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=h,i.width=f,t!==void 0){const _=l();_.width=f,_.height=h;const g=u(_);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,f,h).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const h=l();h.width=e.width,h.height=e.height;const f=u(h);if(f!=null){const _=e.height,g=e.width;return f.drawImage(e,0,0,g,_),o=f.getImageData(0,0,g,_).data,i.height=_,i.width=g,ti(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((h,f)=>{const _=l(),g=u(_);if(!e||!g)return f();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,g.drawImage(w,0,0,_.width,_.height);const v=g.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,h(ti(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ti(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},y0=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new Pt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},b0=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Pt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},M0=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Pt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},x0=(e,t,r)=>new Pt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),hn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),fa=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let wf=!1;const T0=()=>{if(!wf){wf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(hn.set("int64",BigInt64Array),fa.set(BigInt64Array,"int64")),t&&(hn.set("uint64",BigUint64Array),fa.set(BigUint64Array,"uint64")),n?(hn.set("float16",r),fa.set(r,"float16")):hn.set("float16",Uint16Array)}},k0=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Pt(e.type,e.data,t);case"cpu-pinned":return new Pt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Pt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Pt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Pt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Pt=class{constructor(t,r,n){T0();let s,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=hn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof t=="string")if(s=t,l=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const u=hn.get(t);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&u===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${u.name} as data.`);t==="uint64"||t==="int64"?i=u.from(r,BigInt):i=u.from(r)}else if(r instanceof u)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&&u!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${u}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof t[0];if(u==="string")s="string",i=t;else if(u==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{const u=fa.get(t.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=u,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=k0(a);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=a,this.size=o}static async fromImage(t,r){return v0(t,r)}static fromTexture(t,r){return y0(t,r)}static fromGpuBuffer(t,r){return b0(t,r)}static fromMLTensor(t,r){return M0(t,r)}static fromPinnedBuffer(t,r,n){return x0(t,r,n)}toDataURL(t){return g0(this,t)}toImageData(t){return w0(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 E0(this,t)}};const C0=Pt;var or={},S0=Object.defineProperty,bn=(e,t)=>{for(var r in t)S0(e,r,{get:t[r],enumerable:!0})},xt={},Yt={},A0={},P0="4.0.0-next.6",xl=typeof self<"u",pn=!mp(xt),fp=!mp(Yt),Ta=xl&&"caches"in self,F0=typeof globalThis.Deno<"u",Na=F0&&Ta&&!pn,_p=typeof process<"u",g_,pp=_p&&((g_=process==null?void 0:process.release)==null?void 0:g_.name)==="node"&&!Na,Tl=typeof window<"u"&&typeof window.document<"u",w_,kl=xl&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((w_=self.constructor)==null?void 0:w_.name),L0=Tl||kl||Na,I0=pp||typeof navigator<"u"&&"gpu"in navigator,O0=typeof navigator<"u"&&"ml"in navigator,N0=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",D0=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",B0=typeof ServiceWorkerGlobalScope<"u"&&xl&&self instanceof ServiceWorkerGlobalScope,z0=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&n},R0=z0(),_e=Object.freeze({IS_BROWSER_ENV:Tl,IS_WEBWORKER_ENV:kl,IS_WEB_ENV:L0,IS_SERVICE_WORKER_ENV:B0,IS_DENO_WEB_RUNTIME:Na,IS_WEB_CACHE_AVAILABLE:Ta,IS_WEBGPU_AVAILABLE:I0,IS_WEBNN_AVAILABLE:O0,IS_SAFARI:R0,IS_PROCESS_AVAILABLE:_p,IS_NODE_ENV:pp,IS_FS_AVAILABLE:pn,IS_PATH_AVAILABLE:fp,IS_CRYPTO_AVAILABLE:N0,IS_CHROME_AVAILABLE:D0}),El=pn&&fp,ka="./";if(El){const e=Object(import.meta).url;e?ka=Yt.dirname(Yt.dirname(A0.fileURLToPath(e))):typeof __dirname<"u"&&(ka=Yt.dirname(__dirname))}var $0=El?Yt.join(ka,"/.cache/"):null,vf="/models/",G0=El?Yt.join(ka,vf):vf,V0=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Nt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),yf=Nt.WARNING,xe={version:P0,backends:{onnx:{}},get logLevel(){return yf},set logLevel(e){var t,r;yf=e,(r=(t=xe.backends.onnx)==null?void 0:t.setLogLevel)==null||r.call(t,e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Tl||kl||Na),localModelPath:G0,useFS:pn,useBrowserCache:Ta,useFSCache:pn,cacheDir:$0,useCustomCache:!1,customCache:null,useWasmCache:Ta||pn,cacheKey:"transformers-cache",fetch:V0};function mp(e){return Object.keys(e).length===0}function fn(e,t){e&&e(t)}function U0(e){return Number.isInteger(e)||typeof e=="bigint"}function bf(e){return e==null||e===-1}function Mf(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Dt(...e){return Array.prototype.concat.apply([],e)}function Ea(e,t){return Math.abs((e+t)%(2*t)-t)}function mt(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function W0(e,t){let r=0;for(const n of e)n===t&&++r;return r}var ge={error(...e){xe.logLevel<=Nt.ERROR&&console.error(...e)},warn(...e){xe.logLevel<=Nt.WARNING&&console.warn(...e)},info(...e){xe.logLevel<=Nt.INFO&&console.log(...e)},debug(...e){xe.logLevel<=Nt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},j0=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let n=t;for(let s=0;sn&&t.push(e.slice(n,s)),t.push(o),s+=o.length,n=s):++s}return n{const e=[...Array.from({length:94},(s,a)=>a+33),...Array.from({length:12},(s,a)=>a+161),...Array.from({length:82},(s,a)=>a+174)],t=e.slice();let r=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+r),r+=1);const n=t.map(s=>String.fromCharCode(s));return Object.fromEntries(e.map((s,a)=>[s,n[a]]))})(),Q0=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),X0=Q0(gp),Tf=".,!?…。,、।۔،",Y0=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|[${Tf}])]+`,` ?[^\\s${Tf}]+`]]),Ca="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Cl=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"),Da=(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[n,s]of Y0)r=r.replaceAll(n,s);try{return new RegExp(r,"gu")}catch(n){if(!(n instanceof SyntaxError)||!n.message.toLowerCase().includes("invalid property name"))throw n;let s=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return s=!0,`${i}{Script=${l}}`}});if(!s)throw n;try{return new RegExp(a,"gu")}catch{throw n}}}else if(e.String!==void 0){const r=K0(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},K0=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),J0=(e,t,r)=>{const n=[];let s=0;for(;se>=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,eM=e=>Number.isInteger(e)||typeof e=="bigint",tM=e=>{let t=0;for(const r of e)++t;return t},rM=e=>wp(e.toLowerCase()),Bt=(...e)=>Array.prototype.concat.apply([],e),Sl=e=>new Map(Object.entries(e)),nM=(e,t)=>{const r=[];let n=0;for(const s of e.matchAll(t)){const a=s[0];n0&&r.push(a),n=s.index+a.length}return ne.replace(new RegExp("\\p{M}","gu"),""),kf=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},sM=e=>e.match(/\S+/g)||[],aM=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},gs=aM,oM=class extends gs{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},dr=oM,iM=class extends dr{tokenize_chinese_chars(e){const t=[];for(let r=0;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},uM=cM,dM=class extends dr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>vp(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},hM=dM,fM=class extends dr{normalize(e){const t=Da(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},_M=fM,pM=class extends dr{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Ba=pM,mM=class extends Ba{constructor(){super(...arguments),this.form="NFC"}},gM=mM,wM=class extends Ba{constructor(){super(...arguments),this.form="NFD"}},vM=wM,yM=class extends Ba{constructor(){super(...arguments),this.form="NFKC"}},bM=yM,MM=class extends Ba{constructor(){super(...arguments),this.form="NFKD"}},xM=MM,TM=class extends dr{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}},kM=TM,EM=class extends dr{normalize(e){return wp(e)}},CM=EM,SM=class extends dr{normalize(e){return e.toLowerCase()}},AM=SM,PM=class extends dr{normalize(e){return e=this.config.prepend+e,e}},FM=PM;function LM(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new lM(e);case"Precompiled":return new uM(e);case"Sequence":return new hM(e);case"Replace":return new _M(e);case"NFC":return new gM(e);case"NFD":return new vM(e);case"NFKC":return new bM(e);case"NFKD":return new xM(e);case"Strip":return new kM(e);case"StripAccents":return new CM(e);case"Lowercase":return new AM(e);case"Prepend":return new FM(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var vp=LM,IM=class extends gs{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)}},Rt=IM,OM=class extends Rt{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=gp,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(n=>Array.from(this.text_encoder.encode(n),s=>this.byte_encoder[s]).join(""))}},NM=OM,DM=class extends Rt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},BM=DM,zM=class extends Rt{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 n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},RM=zM,$M=class extends Rt{constructor(e){super(),this.config=e,this.pattern=Da(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):nM(e,this.pattern)}},GM=$M,VM=class extends Rt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Ca}]+|[${Ca}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},UM=VM,WM=class extends Rt{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)||[]}},jM=WM,qM=class extends Rt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ca}]+|[${Ca}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},HM=qM,QM=class extends Rt{constructor(e){super(),this.config=e,this.pattern=Da(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},XM=QM,YM=class extends Rt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>yp(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},KM=YM,JM=class extends Rt{pre_tokenize_text(e){return sM(e)}},ZM=JM,ex=class extends Rt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;rthis.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0;const o=[];for(;a0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},Ef=sx,Cf=class bp{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new bp(!1,new Map)}},ax=class{constructor(){this.root=Cf.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let n=t.children.get(r);n===void 0&&(n=Cf.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},ox=ax,ri=class Mp{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new Mp(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},ix=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 n=new ri(this.bos_token_id??0,0,0,0,0),s=new ri(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(e,t,r,n){const s=this.nodes.length,a=new ri(n,s,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 u of this.end_nodes[t]){const h=u.backtrace_score+o.score;(l===null||h>i)&&(l=u.clone(),i=h)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}const r=[],s=this.begin_nodes[e][0].prev;if(s===null)return[];let a=s.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},lx=ix;function cx(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=cx(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new ox,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let n=0;for(;nr>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size0&&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.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},_x=fx,px=class extends za{constructor(e){super(e),this.tokens_to_ids=Sl(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,n]of this.tokens_to_ids)this.vocab[n]=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,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new _x(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 n=[];if(r.length>1){const s=new hx((i,l)=>i.score`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},Af=px,mx=class extends za{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=Sl(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[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(e){return e}},gx=mx;function wx(e,t){switch(e.type){case"WordPiece":return new Ef(e);case"Unigram":return new Sf(e,t.eos_token);case"BPE":return new Af(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 Af(e):new Ef(e):new gx(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 vx=wx,yx=class extends gs{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ws=yx,bx=class extends ws{post_process(e,t=null,r=!0){const n=t===null?this.config.single:this.config.pair;let s=[],a=[];for(const o of n)"SpecialToken"in o?r&&(s.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(s=Bt(s,e),a=Bt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=Bt(s,t),a=Bt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},Mx=bx,xx=class extends ws{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},Tx=xx,kx=class extends ws{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Bt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=[],a=r?[this.sep[0]]:[];e=Bt(e,s,t,a),n=Bt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},Ex=kx,Cx=class extends ws{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Bt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Bt(e,s,t,a),n=Bt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},Sx=Cx,Ax=class extends ws{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>xp(t))}post_process(e,t=null,r=!0){let n={tokens:e,tokens_pair:t};for(const s of this.processors)n=s.post_process(n.tokens,n.tokens_pair,r);return n}},Px=Ax;function Fx(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new Mx(e);case"ByteLevel":return new Tx(e);case"BertProcessing":return new Ex(e);case"RobertaProcessing":return new Sx(e);case"Sequence":return new Px(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var xp=Fx,Lx=class extends gs{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=Lx,Ix=class extends $t{constructor(e){super(e),this.byte_decoder=X0,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(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const n of e)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},Ox=Ix,Nx=class extends $t{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=Cl(t)),t})}},Dx=Nx,Bx=class extends $t{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;rt.replaceAll(this.suffix,r===e.length-1?"":" "))}},$x=Rx,Gx=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 s=1;ss!==this.pad_token).join("");return this.cleanup&&(n=Cl(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Vx=Gx,Ux=class extends $t{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Tp(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},Wx=Ux,jx=class extends $t{decode_chain(e){const t=Da(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},qx=jx,Hx=class extends $t{decode_chain(e){return[e.join("")]}},Qx=Hx,Xx=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 s=0;s")){const a=parseInt(n.slice(3,5),16);isNaN(a)||(s=a)}if(s!==null)r.push(s);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(n)}}if(r.length>0){const n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},Jx=Kx;function Zx(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Ox(e);case"WordPiece":return new Dx(e);case"Metaspace":return new zx(e);case"BPEDecoder":return new $x(e);case"CTC":return new Vx(e);case"Sequence":return new Wx(e);case"Replace":return new qx(e);case"Fuse":return new Qx(e);case"Strip":return new Yx(e);case"ByteFallback":return new Jx(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Tp=Zx,e1=class{constructor(e,t){const r=kf(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=kf(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=vp(this.tokenizer.normalizer),this.pre_tokenizer=yp(this.tokenizer.pre_tokenizer),this.model=vx(this.tokenizer.model,this.config),this.post_processor=xp(this.tokenizer.post_processor),this.decoder=Tp(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const s=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new H0(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 s.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new xf(s),this.splitter_normalized=new xf(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=s.map(l=>{var u;return((u=this.added_tokens_map.get(l))==null?void 0:u.id)??this.model.tokens_to_ids.get(l)??this.model.unk_token_id}),i={ids:o,tokens:s,attention_mask:new Array(o.length).fill(1)};return n&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!eM(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(s=>this.model.vocab[Number(s)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=Cl(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,n)=>{const s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),s.rstrip&&n{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=rM(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const s=this.splitter_normalized.split(r);return s.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(s[o-1]=s[o-1].trimEnd()),i.rstrip&&o{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:n}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const n=this.encode_text(e),s=this.encode_text(t||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Bt(n??[],s??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){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=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],n1=new Map([["n",`
+`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function s1(e,t={}){return e.endsWith(`
+`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function a1(e,t={}){var u,h;const r=[],n=s1(e,t);let s=0,a=0;const o=f=>{let _="";for(;f(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const g=n[s++],w=n1.get(g);if(w===void 0)throw new SyntaxError(`Unexpected escaped character: ${g}`);_+=w;continue}if(_+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return _},i=()=>{const f=r.at(-1);f&&f.type===B.Text&&(f.value=f.value.trimEnd(),f.value===""&&r.pop())},l=()=>{for(;s0){r.push(new St(g,B.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const g=n[s]==="-";g&&++s;let w="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");w+=n[s++]}const v=w.endsWith("-");v&&(w=w.slice(0,-1)),g&&i(),r.push(new St(w,B.Comment)),s+=2,v&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new St("{%",B.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new St("{{",B.OpenExpression)),a=0,s+=3;continue}if(o(Ff),n.slice(s,s+3)==="-%}"){r.push(new St("%}",B.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new St("}}",B.CloseExpression)),s+=3,l();continue}const _=n[s];if(_==="-"||_==="+"){const g=(h=r.at(-1))==null?void 0:h.type;if(g===B.Text||g===void 0)throw new SyntaxError(`Unexpected character: ${_}`);switch(g){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++s;const w=o(Yn);r.push(new St(`${_}${w}`,w.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(const[g,w]of r1){if(g==="}}"&&a>0)continue;if(n.slice(s,s+g.length)===g){r.push(new St(g,w)),w===B.OpenExpression?a=0:w===B.OpenCurlyBracket?++a:w===B.CloseCurlyBracket&&--a,s+=g.length;continue e}}if(_==="'"||_==='"'){++s;const g=o(w=>w!==_);r.push(new St(g,B.StringLiteral)),++s;continue}if(Yn(_)){let g=o(Yn);if(n[s]==="."&&Yn(n[s+1])){++s;const w=o(Yn);g=`${g}.${w}`}r.push(new St(g,B.NumericLiteral));continue}if(Pf(_)){const g=o(Pf);r.push(new St(g,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${_}`)}return r}var Gt=class{constructor(){M(this,"type","Statement")}},o1=class extends Gt{constructor(t){super();M(this,"type","Program");this.body=t}},i1=class extends Gt{constructor(t,r,n){super();M(this,"type","If");this.test=t,this.body=r,this.alternate=n}},l1=class extends Gt{constructor(t,r,n,s){super();M(this,"type","For");this.loopvar=t,this.iterable=r,this.body=n,this.defaultBlock=s}},c1=class extends Gt{constructor(){super(...arguments);M(this,"type","Break")}},u1=class extends Gt{constructor(){super(...arguments);M(this,"type","Continue")}},d1=class extends Gt{constructor(t,r,n){super();M(this,"type","Set");this.assignee=t,this.value=r,this.body=n}},h1=class extends Gt{constructor(t,r,n){super();M(this,"type","Macro");this.name=t,this.args=r,this.body=n}},f1=class extends Gt{constructor(t){super();M(this,"type","Comment");this.value=t}},Tt=class extends Gt{constructor(){super(...arguments);M(this,"type","Expression")}},_1=class extends Tt{constructor(t,r,n){super();M(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=n}},Lf=class extends Tt{constructor(t,r){super();M(this,"type","CallExpression");this.callee=t,this.args=r}},sn=class extends Tt{constructor(t){super();M(this,"type","Identifier");this.value=t}},Mn=class extends Tt{constructor(t){super();M(this,"type","Literal");this.value=t}},p1=class extends Mn{constructor(){super(...arguments);M(this,"type","IntegerLiteral")}},m1=class extends Mn{constructor(){super(...arguments);M(this,"type","FloatLiteral")}},If=class extends Mn{constructor(){super(...arguments);M(this,"type","StringLiteral")}},g1=class extends Mn{constructor(){super(...arguments);M(this,"type","ArrayLiteral")}},Of=class extends Mn{constructor(){super(...arguments);M(this,"type","TupleLiteral")}},w1=class extends Mn{constructor(){super(...arguments);M(this,"type","ObjectLiteral")}},Kn=class extends Tt{constructor(t,r,n){super();M(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=n}},v1=class extends Tt{constructor(t,r){super();M(this,"type","FilterExpression");this.operand=t,this.filter=r}},y1=class extends Gt{constructor(t,r){super();M(this,"type","FilterStatement");this.filter=t,this.body=r}},b1=class extends Tt{constructor(t,r){super();M(this,"type","SelectExpression");this.lhs=t,this.test=r}},M1=class extends Tt{constructor(t,r,n){super();M(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=n}},x1=class extends Tt{constructor(t,r){super();M(this,"type","UnaryExpression");this.operator=t,this.argument=r}},T1=class extends Tt{constructor(t=void 0,r=void 0,n=void 0){super();M(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=n}},k1=class extends Tt{constructor(t,r){super();M(this,"type","KeywordArgumentExpression");this.key=t,this.value=r}},E1=class extends Tt{constructor(t){super();M(this,"type","SpreadExpression");this.argument=t}},C1=class extends Gt{constructor(t,r,n){super();M(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=n}},S1=class extends Tt{constructor(t,r,n){super();M(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=n}};function A1(e){const t=new o1([]);let r=0;function n(I,S){const z=e[r++];if(!z||z.type!==I)throw new Error(`Parser Error: ${S}. ${z.type} !== ${I}.`);return z}function s(I){if(!l(I))throw new SyntaxError(`Expected ${I}`);++r}function a(){switch(e[r].type){case B.Comment:return new f1(e[r++].value);case B.Text:return u();case B.OpenStatement:return h();case B.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...I){return r+I.length<=e.length&&I.every((S,z)=>S===e[r+z].type)}function i(...I){var S,z,re;return((S=e[r])==null?void 0:S.type)===B.OpenStatement&&((z=e[r+1])==null?void 0:z.type)===B.Identifier&&I.includes((re=e[r+1])==null?void 0:re.value)}function l(...I){return r+I.length<=e.length&&I.every((S,z)=>e[r+z].type==="Identifier"&&S===e[r+z].value)}function u(){return new If(n(B.Text,"Expected text token").value)}function h(){if(n(B.OpenStatement,"Expected opening statement token"),e[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const I=e[r].value;let S;switch(I){case"set":++r,S=_();break;case"if":++r,S=g(),n(B.OpenStatement,"Expected {% token"),s("endif"),n(B.CloseStatement,"Expected %} token");break;case"macro":++r,S=w(),n(B.OpenStatement,"Expected {% token"),s("endmacro"),n(B.CloseStatement,"Expected %} token");break;case"for":++r,S=b(),n(B.OpenStatement,"Expected {% token"),s("endfor"),n(B.CloseStatement,"Expected %} token");break;case"call":{++r;let z=null;o(B.OpenParen)&&(z=U());const re=ee();if(re.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const X=U();n(B.CloseStatement,"Expected closing statement token");const pe=[];for(;!i("endcall");)pe.push(a());n(B.OpenStatement,"Expected '{%'"),s("endcall"),n(B.CloseStatement,"Expected closing statement token");const ue=new Lf(re,X);S=new C1(ue,z,pe);break}case"break":++r,n(B.CloseStatement,"Expected closing statement token"),S=new c1;break;case"continue":++r,n(B.CloseStatement,"Expected closing statement token"),S=new u1;break;case"filter":{++r;let z=ee();z instanceof sn&&o(B.OpenParen)&&(z=R(z)),n(B.CloseStatement,"Expected closing statement token");const re=[];for(;!i("endfilter");)re.push(a());n(B.OpenStatement,"Expected '{%'"),s("endfilter"),n(B.CloseStatement,"Expected '%}'"),S=new y1(z,re);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return S}function f(){n(B.OpenExpression,"Expected opening expression token");const I=k();return n(B.CloseExpression,"Expected closing expression token"),I}function _(){const I=v();let S=null;const z=[];if(o(B.Equals))++r,S=v();else{for(n(B.CloseStatement,"Expected %} token");!i("endset");)z.push(a());n(B.OpenStatement,"Expected {% token"),s("endset")}return n(B.CloseStatement,"Expected closing statement token"),new d1(I,S,z)}function g(){const I=k();n(B.CloseStatement,"Expected closing statement token");const S=[],z=[];for(;!i("elif","else","endif");)S.push(a());if(i("elif")){++r,++r;const re=g();z.push(re)}else if(i("else"))for(++r,++r,n(B.CloseStatement,"Expected closing statement token");!i("endif");)z.push(a());return new i1(I,S,z)}function w(){const I=ee();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const S=U();n(B.CloseStatement,"Expected closing statement token");const z=[];for(;!i("endmacro");)z.push(a());return new h1(I,S,z)}function v(I=!1){const S=I?ee:k,z=[S()],re=o(B.Comma);for(;re&&(++r,z.push(S()),!!o(B.Comma)););return re?new Of(z):z[0]}function b(){const I=v(!0);if(!(I instanceof sn||I instanceof Of))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const S=k();n(B.CloseStatement,"Expected closing statement token");const z=[];for(;!i("endfor","else");)z.push(a());const re=[];if(i("else"))for(++r,++r,n(B.CloseStatement,"Expected closing statement token");!i("endfor");)re.push(a());return new l1(I,S,z,re)}function k(){return E()}function E(){const I=C();if(l("if")){++r;const S=C();if(l("else")){++r;const z=E();return new S1(S,I,z)}else return new b1(I,S)}return I}function C(){let I=F();for(;l("or");){const S=e[r];++r;const z=F();I=new Kn(S,I,z)}return I}function F(){let I=O();for(;l("and");){const S=e[r];++r;const z=O();I=new Kn(S,I,z)}return I}function O(){let I;for(;l("not");){const S=e[r];++r;const z=O();I=new x1(S,z)}return I??G()}function G(){let I=T();for(;;){let S;if(l("not","in"))S=new St("not in",B.Identifier),r+=2;else if(l("in"))S=e[r++];else if(o(B.ComparisonBinaryOperator))S=e[r++];else break;const z=T();I=new Kn(S,I,z)}return I}function T(){let I=N();for(;o(B.AdditiveBinaryOperator);){const S=e[r];++r;const z=N();I=new Kn(S,I,z)}return I}function V(){const I=D(ee());return o(B.OpenParen)?R(I):I}function R(I){let S=new Lf(I,U());return S=D(S),o(B.OpenParen)&&(S=R(S)),S}function U(){n(B.OpenParen,"Expected opening parenthesis for arguments list");const I=Z();return n(B.CloseParen,"Expected closing parenthesis for arguments list"),I}function Z(){const I=[];for(;!o(B.CloseParen);){let S;if(e[r].type===B.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const z=k();S=new E1(z)}else if(S=k(),o(B.Equals)){if(++r,!(S instanceof sn))throw new SyntaxError("Expected identifier for keyword argument");const z=k();S=new k1(S,z)}I.push(S),o(B.Comma)&&++r}return I}function H(){const I=[];let S=!1;for(;!o(B.CloseSquareBracket);)o(B.Colon)?(I.push(void 0),++r,S=!0):(I.push(k()),o(B.Colon)&&(++r,S=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(S){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new T1(...I)}return I[0]}function D(I){for(;o(B.Dot)||o(B.OpenSquareBracket);){const S=e[r];++r;let z;const re=S.type===B.OpenSquareBracket;if(re)z=H(),n(B.CloseSquareBracket,"Expected closing square bracket");else if(z=ee(),z.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new _1(I,z,re)}return I}function N(){let I=ie();for(;o(B.MultiplicativeBinaryOperator);){const S=e[r++],z=ie();I=new Kn(S,I,z)}return I}function ie(){let I=K();for(;l("is");){++r;const S=l("not");S&&++r;const z=ee();if(!(z instanceof sn))throw new SyntaxError("Expected identifier for the test");I=new M1(I,S,z)}return I}function K(){let I=V();for(;o(B.Pipe);){++r;let S=ee();if(!(S instanceof sn))throw new SyntaxError("Expected identifier for the filter");o(B.OpenParen)&&(S=R(S)),I=new v1(I,S)}return I}function ee(){const I=e[r++];switch(I.type){case B.NumericLiteral:{const S=I.value;return S.includes(".")?new m1(Number(S)):new p1(Number(S))}case B.StringLiteral:{let S=I.value;for(;o(B.StringLiteral);)S+=e[r++].value;return new If(S)}case B.Identifier:return new sn(I.value);case B.OpenParen:{const S=v();return n(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),S}case B.OpenSquareBracket:{const S=[];for(;!o(B.CloseSquareBracket);)S.push(k()),o(B.Comma)&&++r;return++r,new g1(S)}case B.OpenCurlyBracket:{const S=new Map;for(;!o(B.CloseCurlyBracket);){const z=k();n(B.Colon,"Expected colon between key and value in object literal");const re=k();S.set(z,re),o(B.Comma)&&++r}return++r,new w1(S)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r0)for(let s=e;st;s+=r)n.push(s);return n}function Nf(e,t,r,n=1){const s=Math.sign(n);s>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;s*ot.toUpperCase())}function L1(e){return I1(new Date,e)}function I1(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),s=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return s(e.getMonth()+1);case"%d":return s(e.getDate());case"%b":return n.format(e);case"%B":return r.format(e);case"%H":return s(e.getHours());case"%M":return s(e.getMinutes());case"%%":return"%";default:return a}})}function O1(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N1(e,t,r,n){if(n===0)return e;let s=n==null||n<0?1/0:n;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(O1(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var Df=class extends Error{},Bf=class extends Error{},Jt=class{constructor(e=void 0){M(this,"type","RuntimeValue");M(this,"value");M(this,"builtins",new Map);this.value=e}__bool__(){return new ae(!!this.value)}toString(){return String(this.value)}},ce=class extends Jt{constructor(){super(...arguments);M(this,"type","IntegerValue")}},Ge=class extends Jt{constructor(){super(...arguments);M(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Y=class extends Jt{constructor(){super(...arguments);M(this,"type","StringValue");M(this,"builtins",new Map([["upper",new Ie(()=>new Y(this.value.toUpperCase()))],["lower",new Ie(()=>new Y(this.value.toLowerCase()))],["strip",new Ie(()=>new Y(this.value.trim()))],["title",new Ie(()=>new Y(F1(this.value)))],["capitalize",new Ie(()=>new Y(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ce(this.value.length)],["rstrip",new Ie(()=>new Y(this.value.trimEnd()))],["lstrip",new Ie(()=>new Y(this.value.trimStart()))],["startswith",new Ie(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");const r=t[0];if(r instanceof Y)return new ae(this.value.startsWith(r.value));if(r instanceof ye){for(const n of r.value){if(!(n instanceof Y))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(n.value))return new ae(!0)}return new ae(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ie(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");const r=t[0];if(r instanceof Y)return new ae(this.value.endsWith(r.value));if(r instanceof ye){for(const n of r.value){if(!(n instanceof Y))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(n.value))return new ae(!0)}return new ae(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ie(t=>{const r=t[0]??new ze;if(!(r instanceof Y||r instanceof ze))throw new Error("sep argument must be a string or null");const n=t[1]??new ce(-1);if(!(n instanceof ce))throw new Error("maxsplit argument must be a number");let s=[];if(r instanceof ze){const a=this.value.trimStart();for(const{0:o,index:i}of a.matchAll(/\S+/g)){if(n.value!==-1&&s.length>=n.value&&i!==void 0){s.push(o+a.slice(i+o.length));break}s.push(o)}}else{if(r.value==="")throw new Error("empty separator");s=this.value.split(r.value),n.value!==-1&&s.length>n.value&&s.push(s.splice(n.value).join(r.value))}return new ye(s.map(a=>new Y(a)))})],["replace",new Ie(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");const r=t[0],n=t[1];if(!(r instanceof Y&&n instanceof Y))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new ze:s=t[2]:s=new ze,!(s instanceof ce||s instanceof ze))throw new Error("replace() count argument must be a number or null");return new Y(N1(this.value,r.value,n.value,s.value))})]]))}},ae=class extends Jt{constructor(){super(...arguments);M(this,"type","BooleanValue")}},D1=/[\x7f-\uffff]/g;function zf(e){return e.replace(D1,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Ur(e,t={},r=0,n=!0){const{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,u;switch(o?[l,u]=o:s?(l=",",u=": "):(l=", ",u=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let h=JSON.stringify(e.value);return a&&(h=zf(h)),h}case"ArrayValue":case"ObjectValue":{const h=s?" ".repeat(s):"",f=`
+`+h.repeat(r),_=f+h;if(e.type==="ArrayValue"){const g=e.value.map(w=>Ur(w,t,r+1,n));return s?`[${_}${g.join(`${l}${_}`)}${f}]`:`[${g.join(l)}]`}else{let g=Array.from(e.value.entries());i&&(g=g.sort(([v],[b])=>v.localeCompare(b)));const w=g.map(([v,b])=>{let k=JSON.stringify(v);a&&(k=zf(k));const E=`${k}${u}${Ur(b,t,r+1,n)}`;return s?`${_}${E}`:E});return s?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var ot=class extends Jt{constructor(){super(...arguments);M(this,"type","ObjectValue");M(this,"builtins",new Map([["get",new Ie(([t,r])=>{if(!(t instanceof Y))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new ze})],["items",new Ie(()=>this.items())],["keys",new Ie(()=>this.keys())],["values",new Ie(()=>this.values())],["dictsort",new Ie(t=>{let r=new Map;const n=t.filter(l=>l instanceof cs?(r=l.value,!1):!0),s=n.at(0)??r.get("case_sensitive")??new ae(!1);if(!(s instanceof ae))throw new Error("case_sensitive must be a boolean");const a=n.at(1)??r.get("by")??new Y("key");if(!(a instanceof Y))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=n.at(2)??r.get("reverse")??new ae(!1);if(!(o instanceof ae))throw new Error("reverse must be a boolean");const i=Array.from(this.value.entries()).map(([l,u])=>new ye([new Y(l),u])).sort((l,u)=>{const h=a.value==="key"?0:1,f=l.value[h],_=u.value[h],g=Yi(f,_,s.value);return o.value?-g:g});return new ye(i)})]]))}__bool__(){return new ae(this.value.size>0)}items(){return new ye(Array.from(this.value.entries()).map(([t,r])=>new ye([new Y(t),r])))}keys(){return new ye(Array.from(this.value.keys()).map(t=>new Y(t)))}values(){return new ye(Array.from(this.value.values()))}toString(){return Ur(this,{},0,!1)}},cs=class extends ot{constructor(){super(...arguments);M(this,"type","KeywordArgumentsValue")}},ye=class extends Jt{constructor(){super(...arguments);M(this,"type","ArrayValue");M(this,"builtins",new Map([["length",new ce(this.value.length)]]))}__bool__(){return new ae(this.value.length>0)}toString(){return Ur(this,{},0,!1)}},Rf=class extends ye{constructor(){super(...arguments);M(this,"type","TupleValue")}},Ie=class extends Jt{constructor(){super(...arguments);M(this,"type","FunctionValue")}},ze=class extends Jt{constructor(){super(...arguments);M(this,"type","NullValue")}},Le=class extends Jt{constructor(){super(...arguments);M(this,"type","UndefinedValue")}},Dr=class{constructor(e){M(this,"variables",new Map([["namespace",new Ie(e=>{if(e.length===0)return new ot(new Map);if(e.length!==1||!(e[0]instanceof ot))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));M(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Ie],["odd",e=>{if(!(e instanceof ce))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof ce))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 ce||e instanceof Ge],["integer",e=>e instanceof ce],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e.type==="ObjectValue"],["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,_a(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 Le}catch{return new Le}}};function B1(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",P1),e.set("strftime_now",L1),e.set("True",!0),e.set("False",!1),e.set("None",null)}function $f(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof ot)n=n.value.get(s)??new Le;else if(n instanceof ye){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&aa instanceof ce||a instanceof Ge||a instanceof ae,s=a=>a instanceof ae?a.value?1:0:a.value;if(n(e)&&n(t)){const a=s(e),o=s(t);return ao?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()),ao?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var z1=class{constructor(e){M(this,"global");this.global=e??new Dr}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 n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ae(r.value==n.value);case"!=":return new ae(r.value!=n.value)}if(r instanceof Le||n instanceof Le){if(n instanceof Le&&["in","not in"].includes(e.operator.value))return new ae(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof ze||n instanceof ze)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Y(r.value.toString()+n.value.toString());if((r instanceof ce||r instanceof Ge)&&(n instanceof ce||n instanceof Ge)){const s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof Ge||n instanceof Ge?new Ge(o):new ce(o)}case"/":return new Ge(s/a);case"%":{const o=s%a;return r instanceof Ge||n instanceof Ge?new Ge(o):new ce(o)}case"<":return new ae(s":return new ae(s>a);case">=":return new ae(s>=a);case"<=":return new ae(s<=a)}}else if(r instanceof ye&&n instanceof ye)switch(e.operator.value){case"+":return new ye(r.value.concat(n.value))}else if(n instanceof ye){const s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ae(s);case"not in":return new ae(!s)}}}if(r instanceof Y||n instanceof Y)switch(e.operator.value){case"+":return new Y(r.value.toString()+n.value.toString())}if(r instanceof Y&&n instanceof Y)switch(e.operator.value){case"in":return new ae(n.value.includes(r.value));case"not in":return new ae(!n.value.includes(r.value))}if(r instanceof Y&&n instanceof ot)switch(e.operator.value){case"in":return new ae(n.value.has(r.value));case"not in":return new ae(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(e,t){const r=[],n=new Map;for(const s of e)if(s.type==="SpreadExpression"){const a=s,o=this.evaluate(a.argument,t);if(!(o instanceof ye))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}else if(s.type==="KeywordArgumentExpression"){const a=s;n.set(a.key.value,this.evaluate(a.value,t))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,t))}return[r,n]}applyFilter(e,t,r){if(t.type==="Identifier"){const n=t;if(n.value==="tojson")return new Y(Ur(e,{}));if(e instanceof ye)switch(n.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new ce(e.value.length);case"reverse":return new ye(e.value.slice().reverse());case"sort":return new ye(e.value.slice().sort((s,a)=>Yi(s,a,!1)));case"join":return new Y(e.value.map(s=>s.value).join(""));case"string":return new Y(Ur(e,{},0,!1));case"unique":{const s=new Set,a=[];for(const o of e.value)s.has(o.value)||(s.add(o.value),a.push(o));return new ye(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof Y)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const s=e.builtins.get(n.value);if(s instanceof Ie)return s.value([],r);if(s instanceof ce)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new Y(e.value.trim());case"indent":return new Y(e.value.split(`
+`).map((s,a)=>a===0||s.length===0?s:" "+s).join(`
+`));case"join":case"string":return e;case"int":{const s=parseInt(e.value,10);return new ce(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new Ge(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof ce||e instanceof Ge)switch(n.value){case"abs":return e instanceof ce?new ce(Math.abs(e.value)):new Ge(Math.abs(e.value));case"int":return new ce(Math.floor(e.value));case"float":return new Ge(e.value);default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof ot)switch(n.value){case"items":return new ye(Array.from(e.value.entries()).map(([s,a])=>new ye([new Y(s),a])));case"length":return new ce(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof Ie?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof ae)switch(n.value){case"bool":return new ae(e.value);case"int":return new ce(e.value?1:0);case"float":return new Ge(e.value?1:0);case"string":return new Y(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const n=t;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value;if(s==="tojson"){const[,a]=this.evaluateArguments(n.args,r),o=a.get("indent")??new ze;if(!(o instanceof ce||o instanceof ze))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new ae(!1);if(!(i instanceof ae))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new ae(!1);if(!(l instanceof ae))throw new Error("If set, sort_keys must be a boolean");const u=a.get("separators")??new ze;let h=null;if(u instanceof ye||u instanceof Rf){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");const[f,_]=u.value;if(!(f instanceof Y)||!(_ instanceof Y))throw new Error("separators must be a tuple of two strings");h=[f.value,_.value]}else if(!(u instanceof ze))throw new Error("If set, separators must be a tuple of two strings");return new Y(Ur(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:h}))}else if(s==="join"){let a;if(e instanceof Y)a=Array.from(e.value);else if(e instanceof ye)a=e.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(n.args,r),l=o.at(0)??i.get("separator")??new Y("");if(!(l instanceof Y))throw new Error("separator must be a string");return new Y(a.join(l.value))}else if(s==="int"||s==="float"){const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("default")??(s==="int"?new ce(0):new Ge(0));if(e instanceof Y){const l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new ce(l):new Ge(l)}else{if(e instanceof ce||e instanceof Ge)return e;if(e instanceof ae)return s==="int"?new ce(e.value?1:0):new Ge(e.value?1:0);throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}}else if(s==="default"){const[a,o]=this.evaluateArguments(n.args,r),i=a[0]??new Y(""),l=a[1]??o.get("boolean")??new ae(!1);if(!(l instanceof ae))throw new Error("`default` filter flag must be a boolean");return e instanceof Le||l.value&&!e.__bool__().value?i:e}if(e instanceof ye){switch(s){case"sort":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new ae(!1);if(!(i instanceof ae))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new ae(!1);if(!(l instanceof ae))throw new Error("case_sensitive must be a boolean");const u=a.at(2)??o.get("attribute")??new ze;if(!(u instanceof Y||u instanceof ce||u instanceof ze))throw new Error("attribute must be a string, integer, or null");const h=f=>{if(u instanceof ze)return f;const _=u instanceof ce?String(u.value):u.value;return $f(f,_)};return new ye(e.value.slice().sort((f,_)=>{const g=h(f),w=h(_),v=Yi(g,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(f=>!(f instanceof ot)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[o,i,l]=n.args.map(f=>this.evaluate(f,r));let u;if(i){const f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;const h=e.value.filter(f=>{const _=f.value.get(o.value),g=_?u(_,l):!1;return a?g:!g});return new ye(h)}case"map":{const[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof Y))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(u=>{if(!(u instanceof ot))throw new Error("items in map must be an object");const h=$f(u,o.value);return h instanceof Le?i??new Le:h});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof Y){switch(s){case"indent":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new ce(4);if(!(i instanceof ce))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new ae(!1),u=a.at(2)??o.get("blank")??new ae(!1),h=e.value.split(`
+`),f=" ".repeat(i.value),_=h.map((g,w)=>!l.value&&w===0||!u.value&&g.length===0?g:f+g);return new Y(_.join(`
+`))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Ie))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new cs(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof ot){const a=e.builtins.get(s);if(a&&a instanceof Ie){const[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new cs(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${s}`)}else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw new Error(`Unknown test: ${e.test.value}`);const s=n(r);return new ae(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Le}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ae(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const n of e){const s=this.evaluate(n,t);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(r+=s.toString())}return new Y(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,n]=this.evaluateArguments(e.args,t);n.size>0&&r.push(new cs(n));const s=this.evaluate(e.callee,t);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof ye||e instanceof Y))throw new Error("Slice object must be an array or string");const n=this.evaluate(t.start,r),s=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(n instanceof ce||n instanceof Le))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ce||s instanceof Le))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof ce||a instanceof Le))throw new Error("Slice step must be numeric or undefined");return e instanceof ye?new ye(Nf(e.value,n.value,s.value,a.value)):new Y(Nf(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let n;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);n=this.evaluate(e.property,t)}else n=new Y(e.property.value);let s;if(r instanceof ot){if(!(n instanceof Y))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof ye||r instanceof Y)if(n instanceof ce)s=r.value.at(n.value),r instanceof Y&&(s=new Y(r.value.at(n.value)));else if(n instanceof Y)s=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Y))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Jt?s:new Le}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const n=e.assignee.value;t.setVariable(n,r)}else if(e.assignee.type==="TupleLiteral"){const n=e.assignee;if(!(r instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const s=r.value;if(s.length!==n.value.length)throw new Error(`Too ${n.value.length>s.length?"few":"many"} items to unpack in set`);for(let a=0;ag.setVariable(e.loopvar.value,f);else if(e.loopvar.type==="TupleLiteral"){const g=e.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);const w=f;if(g.value.length!==w.value.length)throw new Error(`Too ${g.value.length>w.value.length?"few":"many"} items to unpack`);_=v=>{for(let b=0;b0?a[u-1]:new Le],["nextitem",u{var o;const s=new Dr(n);r=r.slice();let a;((o=r.at(-1))==null?void 0:o.type)==="KeywordArgumentsValue"&&(a=r.pop());for(let i=0;i{const u=new Dr(l);if(e.callerArgs)for(let h=0;hthis.evaluate(r,t)));case"TupleLiteral":return new Rf(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[n,s]of e.value){const a=this.evaluate(n,t);if(!(a instanceof Y))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new ot(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 ze;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function _a(e){switch(typeof e){case"number":return Number.isInteger(e)?new ce(e):new Ge(e);case"string":return new Y(e);case"boolean":return new ae(e);case"undefined":return new Le;case"object":return e===null?new ze:Array.isArray(e)?new ye(e.map(_a)):new ot(new Map(Object.entries(e).map(([t,r])=>[t,_a(r)])));case"function":return new Ie((t,r)=>{const n=e(...t.map(s=>s.value))??null;return _a(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Ue=`
+`,R1="{%- ",$1=" -%}";function G1(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 V1(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return zt(e.body,0,r).replace(/\n$/,"")}function nt(...e){return R1+e.join(" ")+$1}function zt(e,t,r){return e.map(n=>U1(n,t,r)).join(Ue)}function U1(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return zt(e.body,t,r);case"If":return W1(e,t,r);case"For":return j1(e,t,r);case"Set":return q1(e,t,r);case"Macro":return H1(e,t,r);case"Break":return n+nt("break");case"Continue":return n+nt("continue");case"CallStatement":return Q1(e,t,r);case"FilterStatement":return X1(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+be(e)+" -}}"}}function W1(e,t,r){const n=r.repeat(t),s=[];let a=e;for(;a&&(s.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=n+nt("if",be(s[0].test))+Ue+zt(s[0].body,t+1,r);for(let i=1;i0&&(o+=Ue+n+nt("else")+Ue+zt(a.alternate,t+1,r)),o+=Ue+n+nt("endif"),o}function j1(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;s=`${be(o.lhs)} if ${be(o.test)}`}else s=be(e.iterable);let a=n+nt("for",be(e.loopvar),"in",s)+Ue+zt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Ue+n+nt("else")+Ue+zt(e.defaultBlock,t+1,r)),a+=Ue+n+nt("endfor"),a}function q1(e,t,r){const n=r.repeat(t),s=be(e.assignee),a=e.value?be(e.value):"",o=n+nt("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Ue+zt(e.body,t+1,r)+Ue+n+nt("endset")}function H1(e,t,r){const n=r.repeat(t),s=e.args.map(be).join(", ");return n+nt("macro",`${e.name.value}(${s})`)+Ue+zt(e.body,t+1,r)+Ue+n+nt("endmacro")}function Q1(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(be).join(", ")})`:"",a=be(e.call);let o=n+nt(`call${s}`,a)+Ue;return o+=zt(e.body,t+1,r)+Ue,o+=n+nt("endcall"),o}function X1(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:be(e.filter);let a=n+nt("filter",s)+Ue;return a+=zt(e.body,t+1,r)+Ue,a+=n+nt("endfilter"),a}function be(e,t=-1){switch(e.type){case"SpreadExpression":return`*${be(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,n=G1(r),s=be(r.left,n),a=be(r.right,n+1),o=`${s} ${r.operator.value} ${a}`;return n`${be(n)}: ${be(s)}`).join(", ")}}`;case"SliceExpression":{const r=e,n=r.start?be(r.start):"",s=r.stop?be(r.stop):"",a=r.step?`:${be(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${be(r.value)}`}case"Ternary":{const r=e,n=`${be(r.trueExpr)} if ${be(r.condition,0)} else ${be(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}var Y1=class{constructor(e){M(this,"parsed");const t=a1(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=A1(t)}render(e){const t=new Dr;if(B1(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new z1(t).run(this.parsed).value}format(e){return V1(this.parsed,(e==null?void 0:e.indent)||" ")}},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")}},K1={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"},Sa=class kp{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=xt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=xt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=xt.createReadStream(t);this.body=new ReadableStream({start(s){n.on("data",a=>s.enqueue(a)),n.on("end",()=>s.close()),n.on("error",a=>s.error(a))},cancel(){n.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",K1[t]??"application/octet-stream")}clone(){let t=new kp(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 xt.promises.readFile(this.filePath)).buffer}async blob(){const t=await xt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await xt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Al=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(_e.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,n=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))n.push(o&4294967295);n.length||n.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let s=1,a=0;for(let o=Math.max(624,n.length);o>0;--o,++s,++a)s>=624&&(t[0]=t[623],s=1),a>=n.length&&(a=0),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1664525))+n[a]+a>>>0;for(let o=623;o>0;--o,++s)s>=624&&(t[0]=t[623],s=1),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1566083941))-s>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const n=this.random()*2*Math.PI,s=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*s,this._gauss_next=Math.sin(n)*s}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let n=this._int32()>>>32-r;for(;n>t;)n=this._int32()>>>32-r;const s=e[t];e[t]=e[n],e[n]=s}}choices(e,t){return e[Ep(this._random_fn,t)]}};function Ep(e,t){let r=0;for(let s=0;sEp(Pl.random,e),Z1=new Al,Cp=class{constructor(e){this.path=e}async match(e){let t=Yt.join(this.path,e),r=new Sa(t);if(r.exists)return r}async put(e,t,r=void 0){const n=Yt.join(this.path,e),s=_e.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Z1._int32().toString(36),o=n+`.tmp.${s}.${a}`;try{const i=t.headers.get("Content-Length"),l=parseInt(i??"0");let u=0;await xt.promises.mkdir(Yt.dirname(n),{recursive:!0});const h=xt.createWriteStream(o),f=t.body.getReader();for(;;){const{done:_,value:g}=await f.read();if(_)break;await new Promise((v,b)=>{h.write(g,k=>{if(k){b(k);return}v()})}),u+=g.length;const w=l?u/l*100:0;r==null||r({progress:w,loaded:u,total:l})}await new Promise((_,g)=>{h.close(w=>w?g(w):_())}),await xt.promises.rename(o,n)}catch(i){try{await xt.promises.unlink(o)}catch{}throw i}}async delete(e){let t=Yt.join(this.path,e);try{return await xt.promises.unlink(t),!0}catch{return!1}}},eT={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"},Gf=100,tT=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function js(...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 xn(e,t=null,r=null){let n;try{n=new URL(e)}catch{return!1}return!(t&&!t.includes(n.protocol)||r&&!r.includes(n.hostname))}function rT(e){return!(!tT.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function nT(e,t,r){if(!r)return null;const n=eT[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function sT(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&ge.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),o=0;const i=e.body.getReader();async function l(){const{done:u,value:h}=await i.read();if(u)return;const f=o+h.length;if(f>s){s=f;const g=new Uint8Array(s);g.set(a),a=g}a.set(h,o),o=f;const _=o/s*100;return t({progress:_,loaded:o,total:s}),l()}return await l(),a}function Vf(e){return xn(e,["blob:"])}function Uf(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}async function Fl(e=null){let t=null;if(xe.useCustomCache){if(!xe.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!xe.customCache.match||!xe.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=xe.customCache}if(!t&&xe.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(xe.cacheKey)}catch(r){ge.warn("An error occurred while opening the browser cache:",r)}}if(!t&&xe.useFSCache){if(!_e.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new Cp(e??xe.cacheDir)}return t}async function aT(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}async function oT(e){if(!xn(e,["http:","https:"]))return null;const t=Ap(e);return t.set("Range","bytes=0-0"),xe.fetch(e,{method:"GET",headers:t,cache:"no-store"})}async function Sp(e,t,r={}){var u;const n=await Fl(r==null?void 0:r.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=Pp(e,t,r,n),l=await Fp(n,s,o);if(l!==void 0&&typeof l!="string"){const h=l.headers.get("content-length"),f=l.headers.get("content-type");return{exists:!0,size:h?parseInt(h,10):void 0,contentType:f||void 0,fromCache:!0}}if(xe.allowLocalModels&&!xn(s,["http:","https:"]))try{const f=await Aa(s);if(typeof f!="string"&&f.status!==404){const _=f.headers.get("content-length"),g=f.headers.get("content-type");return{exists:!0,size:_?parseInt(_,10):void 0,contentType:g||void 0,fromCache:!1}}}catch{}if(xe.allowRemoteModels&&!r.local_files_only&&i)try{const h=await oT(a);if(h&&h.status>=200&&h.status<300){let f;const _=h.headers.get("content-type");if(h.status===206){const g=h.headers.get("content-range");if(g){const w=g.match(/bytes \d+-\d+\/(\d+)/);w&&(f=parseInt(w[1],10))}}else if(h.status===200)try{await((u=h.body)==null?void 0:u.cancel())}catch{}if(f===void 0){const g=h.headers.get("content-length");f=g?parseInt(g,10):void 0}return{exists:!0,size:f,contentType:_||void 0,fromCache:!1}}}catch(h){ge.warn(`Unable to fetch file metadata for "${a}": ${h}`)}return{exists:!1,fromCache:!1}}async function Aa(e){return xe.useFS&&!xn(e,["http:","https:","blob:"])?new Sa(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):xe.fetch(e,{headers:Ap(e)})}function Ap(e){var n;const t=typeof process<"u"&&((n=process==null?void 0:process.release)==null?void 0:n.name)==="node",r=new Headers;if(t){const s=!!(or!=null&&or.TESTING_REMOTELY),a=xe.version;if(r.set("User-Agent",`transformers.js/${a}; is_ci/${s};`),xn(e,["http:","https:"],["huggingface.co","hf.co"])){const i=(or==null?void 0:or.HF_TOKEN)??(or==null?void 0:or.HF_ACCESS_TOKEN);i&&r.set("Authorization",`Bearer ${i}`)}}return r}function Pp(e,t,r={},n=null){const s=r.revision??"main",a=js(e,t),o=rT(e),i=o?js(xe.localModelPath,a):a,l=js(xe.remoteHost,xe.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),u=n instanceof Cp?s==="main"?a:js(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:o}}async function Fp(e,t,r){if(e)return await aT(e,t,r)}async function iT(e,t,r,n,s,a,o={}){if(await r.match(n)===void 0)if(a)typeof s!="string"&&await r.put(n,new Response(a,{headers:s.headers})).catch(i=>{ge.warn(`Unable to add response to browser cache: ${i}.`)});else{const i=o.progress_callback?l=>fn(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function lT(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:h}=Pp(e,t,n,a);let f,_=!1,g;g=await Fp(a,i,u);const w=g!==void 0;if(!w){if(xe.allowLocalModels)if(xn(o,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!xe.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{g=await Aa(i),f=i}catch(E){ge.warn(`Unable to load from local path "${i}": "${E}"`)}if(g===void 0||typeof g!="string"&&g.status===404){if(n.local_files_only||!xe.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!h)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(g=await Aa(l),g.status!==200)return nT(g.status,l,r);f=u}_=a&&typeof Response<"u"&&g instanceof Response&&g.status===200}fn(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(_e.IS_NODE_ENV&&s)){let k;if(typeof g!="string")if(!n.progress_callback)k=new Uint8Array(await g.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))k=new Uint8Array(await g.arrayBuffer()),fn(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:k.length,total:k.length});else{let E;const C=g.headers.get("content-length");if(C)E=parseInt(C,10);else try{const F=await Sp(e,t,n);F.size&&(E=F.size)}catch{}k=await sT(g,F=>{fn(n.progress_callback,{status:"progress",name:e,file:t,...F})},E)}v=k}if(_&&f&&typeof g!="string"&&await iT(e,t,a,f,g,v,n),fn(n.progress_callback,{status:"done",name:e,file:t}),v){if(!_e.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(g instanceof Sa)return g.filePath;const b=await(a==null?void 0:a.match(f));if(b instanceof Sa)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}async function Pa(e,t,r=!0,n={},s=!1){if(!xe.allowLocalModels){if(n.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!xe.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}fn(n.progress_callback,{status:"initiate",name:e,file:t});const a=await Fl(n==null?void 0:n.cache_dir);return await lT(e,t,r,n,s,a)}async function Lp(e,t,r=!0,n={}){const s=await Pa(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function Er(e,t,r=!0,n={}){const s=await Lp(e,t,r,n);return s===null?{}:JSON.parse(s)}function cT(e,[t,r,n],[s,a],o="bilinear",i=!1){const l=a/n,u=s/r,h=new e.constructor(s*a*t),f=r*n,_=s*a;for(let g=0;g=0;--i)s[i]=l,n[i]=t[r[i]],l*=n[i];const a=r.map((i,l)=>s[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i=0;--u)l+=h%t[u]*a[u],h=Math.floor(h/t[u]);o[l]=e[i]}return[o,n]}function Tn(e){const t=We(e)[0],r=e.map(a=>Math.exp(a-t)),n=r.reduce((a,o)=>a+o,0);return r.map(a=>a/n)}function dT(e){const t=We(e)[0];let r=0;for(let a=0;aa-t-n)}function Ki(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;nt&&(t=e[n],r=n);return[t,r]}function Ip(e){return e>0&&(e&e-1)===0}var Op=class{constructor(e){if(this.size=e|0,this.size<=1||!Ip(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;rr;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let n=0;n>>1],r[n+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r>=2;a>=2;a>>=2){o=n/a<<1;const f=o>>>2;for(i=0;i>>1,a>>>1)}else for(i=0,l=0;i>>1,a>>>1,r)}const h=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const _=o>>>1,g=_>>>1,w=g>>>1;for(i=0;i>>1;for(let _=2;_>1;++u){const h=(u+1-e)**2/2,f=Math.sqrt(i**2+l**2)**h,_=h*Math.atan2(l,i),g=2*u;s[g]=f*Math.cos(_),s[g+1]=f*Math.sin(_),a[g]=s[g],a[g+1]=-s[g+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new Op(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const n=this._buffer1,s=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(r)for(let h=0;h>1,g=t[_];n[h]=g*l[h],n[f]=g*l[f]}else for(let h=0;h=e.length&&(l=2*(e.length-1)-l),n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function qs(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function pT(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function mT(e){const t=e.length,r=e[0].length,n=[t+1,r+1],s=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));s[0][0]=0;const a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let h=1;h0||i>0;)switch(l.push(o-1),u.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(),u.reverse(),[l,u]}var gT=(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>10;let _=l&1023;if(f===31)u=h|2139095040|_<<13;else if(f===0)if(_===0)u=h;else{let g=113;for(;(_&1024)===0;)_<<=1,--g;_&=-1025,u=h|g<<23|_<<13}else u=h|f+112<<23|_<<13;o[0]=u,e[l]=i[0]}}const r=t.length,n=e,s=new Float32Array(r);for(let a=0;awT});var wT={};async function Dp(e){const t=e.split("/").pop();let r;try{if(r=await Fl(),r){const s=await r.match(e);if(s)return s}}catch(s){ge.warn(`Failed to load ${t} from cache:`,s)}const n=await xe.fetch(e);if(!n.ok)throw new Error(`Failed to fetch ${t}: ${n.status} ${n.statusText}`);if(r)try{await r.put(e,n.clone())}catch(s){ge.warn(`Failed to cache ${t}:`,s)}return n}async function vT(e){const t=await Dp(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ge.warn("Failed to read WASM binary:",r),null}}async function yT(e){if(_e.IS_SERVICE_WORKER_ENV||_e.IS_CHROME_AVAILABLE)return e;const t=await Dp(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return ge.warn("Failed to read WASM factory:",r),null}}var bT=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 Bp(e){return e<=Nt.DEBUG?0:e<=Nt.INFO?2:e<=Nt.WARNING||e<=Nt.ERROR?3:4}var MT={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},At=[],Ji,Tr,Wf=Symbol.for("onnxruntime");if(Wf in globalThis)Tr=globalThis[Wf];else if(_e.IS_NODE_ENV){switch(Tr=Np,process.platform){case"win32":At.push("dml");break;case"linux":process.arch==="x64"&&At.push("cuda");break;case"darwin":At.push("coreml");break}At.push("webgpu"),At.push("cpu"),Ji=["cpu"]}else Tr=m0,_e.IS_WEBNN_AVAILABLE&&At.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),_e.IS_WEBGPU_AVAILABLE&&At.push("webgpu"),At.push("wasm"),Ji=["wasm"];var xT=Tr.InferenceSession;function TT(e=null){if(!e)return Ji;switch(e){case"auto":return At;case"gpu":return At.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(At.includes(e))return[bT[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${At.join(", ")}.`)}var jf=Promise.resolve(),an=null;async function kT(){var t,r,n,s,a;if(an)return an;if(!(xe.useWasmCache&&typeof((t=Fe==null?void 0:Fe.wasm)==null?void 0:t.wasmPaths)=="object"&&((n=(r=Fe==null?void 0:Fe.wasm)==null?void 0:r.wasmPaths)==null?void 0:n.wasm)&&((a=(s=Fe==null?void 0:Fe.wasm)==null?void 0:s.wasmPaths)==null?void 0:a.mjs))){if(_e.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return an=Promise.resolve(),an}return an=(async()=>{const o=Fe.wasm.wasmPaths;let i=!1;await Promise.all([o.wasm&&!Vf(o.wasm)?(async()=>{try{const l=await vT(Uf(o.wasm));l&&(Fe.wasm.wasmBinary=l,i=!0)}catch(l){ge.warn("Failed to pre-load WASM binary:",l)}})():Promise.resolve(),o.mjs&&!Vf(o.mjs)?(async()=>{try{const l=await yT(Uf(o.mjs));l&&(Fe.wasm.wasmPaths.mjs=l)}catch(l){ge.warn("Failed to pre-load WASM factory:",l)}})():Promise.resolve()]),i||(Fe.wasm.wasmPaths.mjs=o.mjs)})(),an}async function zp(e,t,r){await kT();const n=Bp(xe.logLevel??Nt.WARNING),s=()=>xT.create(e,{logSeverityLevel:n,...t}),a=await(_e.IS_WEB_ENV?jf=jf.then(s):s());return a.config=r,a}var qf=Promise.resolve();async function Rp(e,t){const r=()=>e.run(t);return _e.IS_WEB_ENV?qf=qf.then(r):r()}function $p(e){return e instanceof Tr.Tensor}var Fe=Tr==null?void 0:Tr.env;function Ll(){var e;return(e=Fe==null?void 0:Fe.wasm)==null?void 0:e.proxy}var v_;if(Fe){let e=function(t){const r=Bp(t);Fe.logLevel=MT[r]};if(Fe.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&((v_=Fe.versions)!=null&&v_.web)&&!Fe.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Fe.versions.web}/dist/`;Fe.wasm.wasmPaths=_e.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`}}Fe.wasm.proxy=!1}Fe.webgpu&&(Fe.webgpu.powerPreference="high-performance"),e(xe.logLevel??Nt.WARNING),xe.backends.onnx={...Fe,setLogLevel:e}}var wr=async(e,t,r)=>{const n=await zp(new Uint8Array(e),t);return(async s=>{const a=Ll(),o=Object.fromEntries(Object.entries(s).map(([l,u])=>[l,(a?u.clone():u).ort_tensor])),i=await Rp(n,o);return Array.isArray(r)?r.map(l=>new j(i[l])):new j(i[r])})},hi,mn=(hi=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=wr([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=wr([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=wr([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=wr([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=wr([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=wr([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=wr([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=wr([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}},M(hi,"session_options",{}),hi),ET=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"}),ni=_e.IS_NODE_ENV?"cpu":"wasm";function CT(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 (${ni}).`),ni):ni}var ST=(function(){let e;return async function(){if(e===void 0)if(!_e.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),lt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Hf=lt.fp32,Qf=Object.freeze({[ET.wasm]:lt.q8}),Xf=Object.freeze({[lt.fp32]:"",[lt.fp16]:"_fp16",[lt.int8]:"_int8",[lt.uint8]:"_uint8",[lt.q8]:"_quantized",[lt.q4]:"_q4",[lt.q4f16]:"_q4f16",[lt.bnb4]:"_bnb4"});function AT(e,t,r,{configDtype:n=null,warn:s}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===lt.auto){if(n){const l=typeof n=="string"?n:n==null?void 0:n[t];if(l&&l!==lt.auto&<.hasOwnProperty(l))return l}i=Qf[r]??Hf}else a&<.hasOwnProperty(a)?i=a:i=Qf[r]??Hf;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var Fa=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}),j=class $e{constructor(...t){M(this,"ort_tensor");return $p(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new C0(t[0],t[1],t[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let s=Number(n);if(Number.isInteger(s))return r._getitem(s)}return r[n]},set:(r,n,s)=>r[n]=s})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const n=r.reduce((s,a)=>s*a);for(let s=0;s0){const s=n.reduce((a,o)=>a*o);return this._subarray(t,s,n)}else return new $e(this.type,[this.data[t]],n)}indexOf(t){const r=this.data;for(let n=0;ng)throw new Error(`Invalid slice: ${f}`);const w=[Math.max(_,0),Math.min(g,this.dims[h])];n.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}const s=n.map(([h,f])=>f-h),a=s.reduce((h,f)=>h*f),o=this.data,i=new o.constructor(a),l=this.stride();let u=!0;for(let h=1;h=0;--_){const w=s[_];f+=(g%w+n[_][0])*l[_],g=Math.floor(g/w)}i[h]=o[f]}return new $e(this.type,i,r)}permute(...t){return FT(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,n=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const s=this.data,a=(u,h)=>u+h**t;if(r===null){const u=s.reduce(a,0)**(1/t);return new $e(this.type,[u],[])}const[o,i,l]=ds(a,this,r,n);if(t!==1)for(let u=0;u=0;--l){const f=this.dims[l];if(l!==r){const _=u%f;i+=_*h,h*=this.dims[l]}u=Math.floor(u/f)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return si(this.dims)}squeeze(t=null){return new $e(this.type,this.data,Yf(this.dims,t))}squeeze_(t=null){return this.dims=Yf(this.dims,t),this}unsqueeze(t){return new $e(this.type,this.data,Kf(this.dims,t))}unsqueeze_(t){return this.dims=Kf(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;si!==r?a*o:a,1);t[r]=n.length/s}return new $e(this.type,n,t)}neg_(){const t=this.data;for(let r=0;rt?1:0;return new $e("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;sMath.min(o,i),this,t,r,1/0);return new $e(n,s,a)}max(t=null,r=!1){if(t===null){const o=We(this.data)[0];return new $e(this.type,[o],[])}const[n,s,a]=ds((o,i)=>Math.max(o,i),this,t,r,-1/0);return new $e(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Ki(this.data)[1];return new $e("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=We(this.data)[1];return new $e("int64",[BigInt(n)],[])}repeat(...t){if(t.lengthh===1)){if(t.length===this.dims.length)return this.clone();const h=t.length-this.dims.length,f=Array(h).fill(1).concat(this.dims);return new $e(this.type,this.data.slice(),f)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((h,f)=>h*t[f]),a=s.reduce((h,f)=>h*f,1),o=this.data,i=new o.constructor(a),l=si(n),u=si(s);for(let h=0;hBigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new $e(t,gT(this.data),this.dims);return new $e(t,Fa[t].from(this.data,r),this.dims)}};function PT(e,t){const r=e.length,n=t.reduce((a,o)=>a*o);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let a=t.length-1;a>=0;a--)s=s.reduce((o,i)=>{let l=o[o.length-1];return l.lengthnew j("int64",e,[e.length]);async function Up(e,t,r,n,s){return await(await mn.slice)({x:e,s:Hs(t),e:Hs(r),a:Hs(n),t:Hs(new Array(n.length).fill(1))})}function Yf(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,n)=>r!==1||!t.includes(n))),e}function Kf(e,t){return t=Xt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Xt(e,t,r=null,n=!0){if(e<-t||e>=t){if(n)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Re(e,t=0){t=Xt(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const n=r.reduce((o,i)=>o*i,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;s.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i=0;--_){const v=u[_];let b=g%v;_===t&&(b+=o),f+=b*w,w*=r[_],g=Math.floor(g/v)}s[f]=l[h]}o+=u[t]}}return new j(a,s,r)}function kn(e,t=0){return Re(e.map(r=>r.unsqueeze(t)),t)}function ds(e,t,r,n=!1,s=null){const a=t.data,o=t.dims;r=Xt(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);s!==null&&l.fill(s);for(let u=0;u=0;--f){const w=o[f];if(f!==r){const v=_%w;h+=v*g,g*=i[f]}_=Math.floor(_/w)}l[h]=e(l[h],a[u],u,h)}return n||i.splice(r,1),[t.type,l,i]}function IT(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const g=s.reduce((k,E)=>k+E,0)/s.length,w=Math.sqrt(s.reduce((k,E)=>k+(E-g)**2,0)/(s.length-r)),v=new j(e.type,[g],[]);return[new j(e.type,[w],[]),v]}t=Xt(t,a.length);const o=Il(e,t,n),i=o.data,[l,u,h]=ds((_,g,w,v)=>_+(g-i[v])**2,e,t,n);for(let _=0;_u+h,0);return new j(e.type,[l/s.length],[])}t=Xt(t,n.length);const[a,o,i]=ds((l,u)=>l+u,e,t,r);if(n[t]!==1)for(let l=0;l=0;--r)t[r]=n,n*=e[r];return t}function Ol(e,t,r,n){const s=e.reduce((a,o)=>a*o,1);return new j(r,new n(s).fill(t),e)}function ct(e,t){let r,n;if(typeof t=="number")r="float32",n=Float32Array;else if(typeof t=="bigint")r="int64",n=BigInt64Array;else if(typeof t=="boolean")r="bool",n=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Ol(e,t,r,n)}function Zi(e,t){return ct(e.dims,t)}function Ft(e){return Ol(e,1n,"int64",BigInt64Array)}function Wp(e){return Ft(e.dims)}function jp(e){return Ol(e,0n,"int64",BigInt64Array)}function qp(e){return jp(e.dims)}function OT(e){const t=e.reduce((r,n)=>r*n,1);return new j("float32",Float32Array.from({length:t},()=>Pl.gauss()),e)}async function NT(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await Sp(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Hp(e,t){const r=await NT(e);return await Promise.all(r.map(n=>Er(e,n,!0,t)))}function Qp(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 DT=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function BT(e,t,r,n){for(const s of Object.keys(e)){const a=t-e[s].length,o=r(s),i=new Array(a).fill(o);e[s]=n==="right"?Dt(e[s],i):Dt(i,e[s])}}function zT(e,t){for(const r of Object.keys(e))e[r].length=t}function Or(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const n=e[r];if(n)if(typeof n=="object"){if(n.__type==="AddedToken")return n.content;throw Error(`Unknown token: ${n}`)}else return n}return null}function RT(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();M(this,"return_token_type_ids",!1);M(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new t1(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Or(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Or(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Or(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Or(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Or(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Or(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 s=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');s[a]=o}this.chat_template=s}this._compiled_template_cache=new Map;const n=RT(this._tokenizer);this.all_special_ids=n.map(s=>s.id),this.all_special_tokens=n.map(s=>s.content)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){const i=await Hp(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,{text_pair:r=null,add_special_tokens:n=!0,padding:s=!1,truncation:a=null,max_length:o=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){const u=Array.isArray(t);let h;if(u){if(t.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(t.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=t.map((_,g)=>this._encode_plus(_,{text_pair:r[g],add_special_tokens:n,return_token_type_ids:l}))}else h=t.map(_=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:l}))}else{if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:l})]}if(o===null?o=this.model_max_length:a===null&&(s===!0?(ge.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),o=this.model_max_length):s===!1&&(ge.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),a=!0)),s===!0&&(o=Math.min(We(h.map(_=>_.input_ids.length))[0],o??1/0)),o=Math.min(o,this.model_max_length??1/0),s||a)for(let _=0;_o?a&&zT(h[_],o):s&&BT(h[_],o,g=>g==="input_ids"?this.pad_token_id:0,this.padding_side));const f={};if(i){if(!(s&&a)&&h.some(g=>{var w;for(const v of Object.keys(g))if(g[v].length!==((w=h[0][v])==null?void 0:w.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 _=[h.length,h[0].input_ids.length];for(const g of Object.keys(h[0]))f[g]=new j("int64",BigInt64Array.from(h.flatMap(w=>w[g]).map(BigInt)),_)}else{for(const _ of Object.keys(h[0]))f[_]=h.map(g=>g[_]);if(!u)for(const _ of Object.keys(f))f[_]=f[_][0]}return f}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){const{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s??this.return_token_type_ids});return{input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:n})}encode(t,{text_pair:r=null,add_special_tokens:n=!0,return_token_type_ids:s=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:n,return_token_type_ids:s}).ids}batch_decode(t,r={}){return t instanceof j&&(t=t.tolist()),t.map(n=>this.decode(n,r))}decode(t,r={}){if(t instanceof j&&(t=Qp(t)),!Array.isArray(t)||t.length===0||!U0(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const n=this.chat_template;if(t!==null&&Object.hasOwn(n,t))t=n[t];else if(t===null)if(r!==null&&"tool_use"in n)t=n.tool_use;else if("default"in n)t=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}else if(t===null)if(this.chat_template)t=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return t}apply_chat_template(t,{tools:r=null,documents:n=null,chat_template:s=null,add_generation_prompt:a=!1,tokenize:o=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:h=!0,return_dict:f=!0,tokenizer_kwargs:_={},...g}={}){if(s=this.get_chat_template({chat_template:s,tools:r}),typeof s!="string")throw Error(`chat_template must be a string, but got ${typeof s}`);let w=this._compiled_template_cache.get(s);w===void 0&&(w=new Y1(s),this._compiled_template_cache.set(s,w));const v=Object.create(null);for(const k of DT){const E=Or(this.config,k);E&&(v[k]=E)}const b=w.render({messages:t,add_generation_prompt:a,tools:r,documents:n,...v,...g});if(o){const k=this._call(b,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:h,..._});return f?k:k.input_ids}return b}};function Nl(e,t,r,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const s=n.src_lang,a=n.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(s!==void 0){if(!e.language_codes.includes(s))throw new Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(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(s);break}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var Xp={};bn(Xp,{AlbertTokenizer:()=>$T,AutoTokenizer:()=>Oe,BartTokenizer:()=>GT,BertTokenizer:()=>VT,BlenderbotSmallTokenizer:()=>UT,BlenderbotTokenizer:()=>WT,BloomTokenizer:()=>jT,CLIPTokenizer:()=>HT,CamembertTokenizer:()=>qT,CodeGenTokenizer:()=>XT,CodeLlamaTokenizer:()=>QT,CohereTokenizer:()=>YT,ConvBertTokenizer:()=>KT,DebertaTokenizer:()=>ZT,DebertaV2Tokenizer:()=>JT,DistilBertTokenizer:()=>ek,ElectraTokenizer:()=>tk,EsmTokenizer:()=>rk,FalconTokenizer:()=>nk,GPT2Tokenizer:()=>ok,GPTNeoXTokenizer:()=>ak,GemmaTokenizer:()=>sk,HerbertTokenizer:()=>ik,LlamaTokenizer:()=>lk,M2M100Tokenizer:()=>ck,MBart50Tokenizer:()=>dk,MBartTokenizer:()=>Yp,MPNetTokenizer:()=>_k,MarianTokenizer:()=>uk,MgpstrTokenizer:()=>hk,MobileBertTokenizer:()=>fk,NllbTokenizer:()=>pk,NougatTokenizer:()=>mk,PreTrainedTokenizer:()=>le,Qwen2Tokenizer:()=>gk,RoFormerTokenizer:()=>vk,RobertaTokenizer:()=>wk,SiglipTokenizer:()=>yk,SpeechT5Tokenizer:()=>bk,SqueezeBertTokenizer:()=>Mk,T5Tokenizer:()=>xk,TokenizersBackend:()=>le,VitsTokenizer:()=>kk,Wav2Vec2CTCTokenizer:()=>Ek,WhisperTokenizer:()=>Pk,XLMRobertaTokenizer:()=>Fk,XLMTokenizer:()=>Lk});var $T=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},GT=class extends le{},VT=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},UT=class extends le{},WT=class extends le{},jT=class extends le{},qT=class extends le{},HT=class extends le{},QT=class extends le{},XT=class extends le{},YT=class extends le{},KT=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},JT=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},ZT=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},ek=class extends le{},tk=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},rk=class extends le{},nk=class extends le{},sk=class extends le{},ak=class extends le{},ok=class extends le{},ik=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},lk=class extends le{constructor(){super(...arguments);M(this,"padding_side","left")}},ck=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 Nl(this,e,t,r)}},uk=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)),ge.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[n,s]=r;return this.supported_language_codes.includes(n)||ge.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Dt([n],super._encode_text(s))}}},Yp=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 Nl(this,e,t,r)}},dk=class extends Yp{},hk=class extends le{},fk=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},_k=class extends le{},pk=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 Nl(this,e,t,r)}},mk=class extends le{},gk=class extends le{},wk=class extends le{},vk=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},yk=class extends le{},bk=class extends le{},Mk=class extends le{constructor(){super(...arguments);M(this,"return_token_type_ids",!0)}},xk=class extends le{},Tk=class extends $t{decode_chain(e){let t="";for(let r=1;r[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 Sk(e){e=e.toLowerCase();let t=Ck.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),pa.has(e))t=e;else{const s=e.length===2?pa.keys():pa.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var Ak="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Jf=new RegExp(`^[${Ak}]+$`,"gu"),Pk=class extends le{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null;const o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let u=i(),h=0;const f=this.timestamp_begin,g=f+1500;let w=[],v=[],b=!1,k=null;const E=new Set(this.all_special_ids);for(const O of e){const G=O.tokens,T=o?O.token_timestamps:null;let V=null,R=f;if("stride"in O){const[H,D,N]=O.stride;if(h-=D,k=H-N,D&&(R=D/n+f),N)for(let ie=G.length-1;ie>=0;--ie){const K=Number(G[ie]);if(K>=f){if(V!==null&&(K-f)*n=f&&D<=g){const N=(D-f)*n+h,ie=qs(N,2);if(V!==null&&D>=V)b=!0;else if(b||w.length>0&&D0?(w.push(U),o&&v.push(Z)):w.every(H=>H.length===0)&&(u=i(),w=[],U=[],v=[],Z=[])}if(w.length>0){if(s&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[O,G]=this.findLongestCommonSequence(w,v),T=this.decode(O);u.text=T,o&&(u.words=this.collateWordTimestamps(O,G,a)),l.push(u)}let C=Object.create(null);const F=l.map(O=>O.text).join("");if(t||r){for(let O=0;O0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;lD===R[N]&&i[F+N]<=t[l][T+N]).length:U=G.filter((D,N)=>D===R[N]).length;const Z=C/1e4,H=U/C+Z;U>1&&H>h&&(h=H,f=[F,O,T,V])}const[g,w,v,b]=f,k=Math.floor((w+g)/2),E=Math.floor((b+v)/2);s.push(...r.slice(0,k)),r=u.slice(E),n=r.length,a&&(o.push(...i.slice(0,k)),i=t[l].slice(E))}return s.push(...r),a?(o.push(...i),[s,o]):[s,[]]}collateWordTimestamps(e,t,r){const[n,s,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i=n){const o=((a-n)*r).toFixed(2);s.push(`<|${o}|>`),s.push([])}else s[s.length-1].push(a);return s=s.map(a=>typeof a=="string"?a:super.decode(a,t)),s.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",n=[],s=[],a=[];let o=[],i=[],l=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),g=l.trim(),w=Jf.test(g);if(f||_||w||s.length===0)s.push(l),a.push(u),o.push(h);else{const v=s.length-1;s[v]+=l,a[v].push(...u),o[v].push(...h)}}return[s,a,o]}mergePunctuations(e,t,r,n,s){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(r);let l=a.length-2,u=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[u]=a[l]+a[u],o[u]=Dt(o[l],o[u]),i[u]=Dt(i[l],i[u]),a[l]="",o[l]=[],i[l]=[]):u=l,--l;for(l=0,u=1;uh),o.filter(h=>h.length>0),i.filter(h=>h.length>0)]}},Fk=class extends le{},Lk=class extends le{constructor(t,r){super(t,r);M(this,"return_token_type_ids",!0);ge.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Oe=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){var h;const[o,i]=await Hp(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=((h=i.tokenizer_class)==null?void 0:h.replace(/Fast$/,""))??"PreTrainedTokenizer";let u=Xp[l];return u||(ge.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),u=le),new u(o,i)}},Dl="https://github.com/huggingface/transformers.js/issues/new/choose",Bl="preprocessor_config.json",Jp=Bl,Ik="processor_config.json",Ok="chat_template.jinja",Zn,Ne=(Zn=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,n,s]=await Promise.all([this.uses_processor_config?Er(e,Ik,!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?Lp(e,Ok,!0,t):null]);return new this(r,n,s)}},M(Zn,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),M(Zn,"uses_processor_config",!1),M(Zn,"uses_chat_template_file",!1),Zn),Nk={};bn(Nk,{ChatterboxProcessor:()=>iE,Florence2Processor:()=>e2,Gemma3nProcessor:()=>t2,GroundingDinoProcessor:()=>n2,Idefics3Processor:()=>n_,JinaCLIPProcessor:()=>l2,LlavaProcessor:()=>c2,MgpstrProcessor:()=>u2,MoonshineProcessor:()=>d2,OwlViTProcessor:()=>h2,PaliGemmaProcessor:()=>_2,Phi3VProcessor:()=>m2,PixtralProcessor:()=>g2,Processor:()=>Ne,PyAnnoteProcessor:()=>w2,Qwen2VLProcessor:()=>km,Qwen2_5_VLProcessor:()=>Em,Qwen3VLProcessor:()=>v2,Sam2Processor:()=>Sm,Sam2VideoProcessor:()=>y2,SamProcessor:()=>Cm,SmolVLMProcessor:()=>n_,SpeechT5Processor:()=>b2,UltravoxProcessor:()=>M2,VLChatProcessor:()=>i2,VoxtralProcessor:()=>E2,VoxtralRealtimeProcessor:()=>Pm,Wav2Vec2Processor:()=>P2,Wav2Vec2ProcessorWithLM:()=>F2,WhisperProcessor:()=>L2});var ft=class extends Vt{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await Er(e,Bl,!0,t);return new this(r)}};function kt(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 Zp={};bn(Zp,{ASTFeatureExtractor:()=>Hk,ChatterboxFeatureExtractor:()=>Qk,ClapFeatureExtractor:()=>Xk,DacFeatureExtractor:()=>nm,EncodecFeatureExtractor:()=>rm,FeatureExtractor:()=>ft,Gemma3nAudioFeatureExtractor:()=>Yk,MoonshineFeatureExtractor:()=>Kk,ParakeetFeatureExtractor:()=>Zk,PyAnnoteFeatureExtractor:()=>sm,SeamlessM4TFeatureExtractor:()=>eE,SnacFeatureExtractor:()=>tE,SpeechT5FeatureExtractor:()=>rE,VoxtralRealtimeFeatureExtractor:()=>aE,Wav2Vec2FeatureExtractor:()=>nE,WeSpeakerFeatureExtractor:()=>sE,WhisperFeatureExtractor:()=>oE});var Dk=()=>{},Bk=Dk;async function zk(e,t){if(_e.IS_BROWSER_ENV){if(_e.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(r)}else if(_e.IS_FS_AVAILABLE)t.stream(),xt.createWriteStream(e),await Bk();else throw new Error("Unable to save because filesystem is disabled in this environment.")}function em(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,n=2*Math.PI/(e-1),s=new Float64Array(e);for(let a=0;a2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,n=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*n:3*e/200};function ai(e,t="htk"){const r=$k[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}var Gk={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,n=Math.log(6.4)/27)=>e>=r?t*Math.exp(n*(e-r)):200*e/3};function Vk(e,t="htk"){const r=Gk[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}function Uk(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),n=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;onew Array(e.length));for(let o=0;oe+n*a)}function ur(e,t,r,n,s,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>n)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${n}`);const l=ai(r,o),u=ai(n,o),h=e_(l,u,t+2);let f=Vk(h,o),_;if(i){const w=s/((e-1)*2);_=ai(Float64Array.from({length:e},(v,b)=>b*w),o),f=h}else _=e_(0,Math.floor(s/2),e);const g=Uk(_,f);if(a!==null&&a==="slaney")for(let w=0;ws)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(T!==r)throw new Error(`Length of the window (${T}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&f!==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(!h)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o)switch(i){case"reflect":{const S=Math.floor((s-1)/2)+1;e=Wk(e,S,S);break}case"constant":{const S=Math.floor(s/2),z=new e.constructor(e.length+2*S);z.set(e,S),e=z;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let V=Math.floor(1+Math.floor((e.length-r)/n));E!==null&&VV?F&&(Z=C):Z=U=C);const H=new fT(s),D=new Float64Array(s),N=new Float64Array(H.outputBufferSize),ie=new Float32Array(R*Z);for(let S=0;S=1;--X)D[X]-=u*D[X-1];D[0]*=1-u}for(let X=0;XMath.pow(i,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),n===null)return o;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);return o}var Hk=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=ur(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Sr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Cr(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){kt(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,n=t.data;for(let s=0;s0)if(r==="rand_trunc"){const o=Math.floor(Pl.random()*(a+1));e=e.subarray(o,o+t),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let o=new Float64Array(t);if(o.set(e),n==="repeat")for(let i=e.length;it&&(e=e.slice(0,t)),n&&e.length%s!==0){const i=s-e.length%s,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}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}}},Kk=class extends ft{async _call(e){kt(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},Jk=1e-5,Zk=class extends ft{constructor(e){var n;super(e),(n=this.config).mel_filters??(n.mel_filters=ur(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=Sr(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 n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await Cr(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){kt(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),n=t.data;n.fill(0,r*t.dims[1]);const[s,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let h=0;h1?r-1:1;for(let h=0;h({id:i,start:l*r,end:u*r,confidence:h/(u-l)})))}return n}},eE=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=ur(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Sr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Cr(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:s=!0}={}){kt(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[g,w]=a.dims,v=a.data;for(let b=0;b0){const k=new Float32Array(w*(g+b));k.set(v),k.fill(this.config.padding_value,v.length);const E=g+b;a=new j(a.type,k,[E,w]),s&&(o=new j("int64",new BigInt64Array(E),[1,E]),o.data.fill(1n,0,g))}}const[i,l]=a.dims,u=this.config.stride;if(i%u!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${u}).`);const f=a.view(1,Math.floor(i/u),l*u),_={input_features:f};if(s){const g=f.dims[1],w=new BigInt64Array(g);if(o){const v=o.data;for(let b=1,k=0;bs+a,0)/e.length,n=e.reduce((s,a)=>s+(a-r)**2,0)/e.length;return e.map(s=>(s-r)/Math.sqrt(n+1e-7))}async _call(e){kt(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 j("float32",t,r),attention_mask:new j("int64",new BigInt64Array(t.length).fill(1n),r)}}},sE=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=ur(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Sr(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),Cr(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){kt(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,n=t.data,[s,a,o]=t.dims;for(let i=0;in?(e.length>this.config.n_samples&&ge.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},Zt=class{static async from_pretrained(e,t={}){const r=await Er(e,Bl,!0,t),n=r.feature_extractor_type,s=Zp[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Dl}.`);return new s(r)}},Ks,iE=(Ks=class extends Ne{async _call(e,t=null){const r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},M(Ks,"tokenizer_class",Oe),M(Ks,"feature_extractor_class",Zt),Ks),el={},Br,am,vr;if(_e.IS_WEB_ENV)Br=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},vr=self.createImageBitmap,am=self.ImageData;else if(el)vr=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new _s(new Uint8ClampedArray(n),s.width,s.height,s.channels);return r!==void 0&&r!==s.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var lE={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},cE=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),_s=class Qt{constructor(t,r,n,s){this.data=t,this.width=r,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(t){if(t instanceof Qt)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(!_e.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new Qt(n,t.width,t.height,4)}static async fromURL(t){const r=await Aa(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const n=await r.blob();return this.fromBlob(n)}static async fromBlob(t){if(_e.IS_WEB_ENV){const r=await vr(t),n=Br(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=el(await t.arrayBuffer());return await vr(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 Qt(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,n=0;r=0?l=n:h=-n,s>=0?u=s:f=-s,i.drawImage(o,l,u,t,r,h,f,t,r),new Qt(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(n>=0&&s>=0)a=a.extract({left:Math.floor(n),top:Math.floor(s),width:t,height:r});else if(n<=0&&s<=0){const o=Math.floor(-s),i=Math.floor(-n);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;s<0?(o[0]=Math.floor(-s),o[1]=r-this.height-o[0]):i=Math.floor(s);let l=[0,0],u=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):u=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:t,height:r})}return await vr(a)}}async toBlob(t="image/png",r=1){if(!_e.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 j("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(!_e.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Br(t.width,t.height),n=new am(t.data,t.width,t.height);return r.getContext("2d").putImageData(n,0,0),r}split(){const{data:t,width:r,height:n,channels:s}=this,a=t.constructor,o=t.length/s,i=Array.from({length:s},()=>new a(o));for(let l=0;lnew Qt(l,r,n,1))}_update(t,r,n,s=null){return this.data=t,this.width=r,this.height=n,s!==null&&(this.channels=s),this}clone(){return new Qt(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(_e.IS_WEB_ENV){if(_e.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=cE.get(r)??"image/png",s=await this.toBlob(n);return zk(t,s)}else if(_e.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(_e.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return el(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};_s.read.bind(_s);function t_(e,t,r=0,n=null){const s=e/t;let a=pT(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),at&&k.push(C)}else{let C=We(b.data)[1];if(C===l-1||(E=Tn(b.data),E[C]O*f[(G+1)%2])),_.boxes.push(F),_.classes.push(C),_.scores.push(E[C])}}u.push(_)}return u}function im(e,t=null){const r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let a=0;af[k]&&(f[k]=b[k],_[k]=v)}const g=new Array(i.dims[0]);for(let v=0;v<_.length;++v){const b=_[v];g[b]=b}const w=g.filter(v=>v!==void 0);s.push({segmentation:h,labels:w})}return s}function uE(e,t,r,n){const s=[],a=[],o=[];for(let i=0;ir&&(s.push(u),a.push(_),o.push(h))}return[s,a,o]}function dE(e,t,r,n=.5,s=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let h=0;h=n&&++i;let u=o>0&&i>0;return u&&(u=o/i>s),[u,a]}function hE(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,u=new j("int32",new Int32Array(i*l),[i,l]),h=[];if(o!==null)for(let v=0;v_[E]&&(f[E]=v,_[E]=k[E])}let g=0;const w=u.data;for(let v=0;vs?l=Math.floor(s*i/n):s>n&&(i=Math.floor(n*l/s)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),n=Ki(r.data)[0],a=We(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,u=0,h=0;const f=r.data;for(let _=0;_this.preprocess(s)));return{pixel_values:kn(r.map(s=>s.pixel_values),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await Er(e,Jp,!0,t);return new this(r)}},um={};bn(um,{BeitFeatureExtractor:()=>fE,BitImageProcessor:()=>_E,CLIPFeatureExtractor:()=>mE,CLIPImageProcessor:()=>dm,ChineseCLIPFeatureExtractor:()=>pE,ConvNextFeatureExtractor:()=>gE,ConvNextImageProcessor:()=>hm,DINOv3ViTImageProcessor:()=>yE,DPTFeatureExtractor:()=>ME,DPTImageProcessor:()=>pm,DeiTFeatureExtractor:()=>wE,DeiTImageProcessor:()=>fm,DetrFeatureExtractor:()=>vE,DetrImageProcessor:()=>_m,DonutFeatureExtractor:()=>bE,DonutImageProcessor:()=>zl,EfficientNetImageProcessor:()=>xE,GLPNFeatureExtractor:()=>TE,GroundingDinoImageProcessor:()=>kE,Idefics3ImageProcessor:()=>r_,ImageFeatureExtractor:()=>de,ImageProcessor:()=>de,JinaCLIPImageProcessor:()=>CE,LlavaOnevisionImageProcessor:()=>SE,Mask2FormerImageProcessor:()=>PE,MaskFormerFeatureExtractor:()=>AE,MaskFormerImageProcessor:()=>Rl,MobileNetV1FeatureExtractor:()=>FE,MobileNetV1ImageProcessor:()=>mm,MobileNetV2FeatureExtractor:()=>LE,MobileNetV2ImageProcessor:()=>gm,MobileNetV3FeatureExtractor:()=>IE,MobileNetV3ImageProcessor:()=>wm,MobileNetV4FeatureExtractor:()=>OE,MobileNetV4ImageProcessor:()=>vm,MobileViTFeatureExtractor:()=>NE,MobileViTImageProcessor:()=>ym,NougatImageProcessor:()=>DE,OwlViTFeatureExtractor:()=>BE,OwlViTImageProcessor:()=>$l,Owlv2ImageProcessor:()=>zE,Phi3VImageProcessor:()=>$E,PixtralImageProcessor:()=>GE,PvtImageProcessor:()=>VE,Qwen2VLImageProcessor:()=>WE,RTDetrImageProcessor:()=>jE,Sam2ImageProcessor:()=>ci,Sam3ImageProcessor:()=>ci,SamImageProcessor:()=>ci,SapiensFeatureExtractor:()=>qE,SapiensImageProcessor:()=>bm,SegformerFeatureExtractor:()=>HE,SegformerImageProcessor:()=>Mm,SiglipImageProcessor:()=>QE,SmolVLMImageProcessor:()=>r_,Swin2SRImageProcessor:()=>XE,VLMImageProcessor:()=>EE,ViTFeatureExtractor:()=>YE,ViTImageProcessor:()=>xm,VitMatteImageProcessor:()=>KE,VitPoseImageProcessor:()=>JE,YolosFeatureExtractor:()=>ZE,YolosImageProcessor:()=>Tm});var fE=class extends de{},_E=class extends de{},pE=class extends de{},dm=class extends de{},mE=class extends dm{},hm=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 n=Math.floor(t/this.crop_pct),[s,a]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(s,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},gE=class extends hm{},fm=class extends de{},wE=class extends fm{},_m=class extends de{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=ct(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return Ra(...e)}post_process_panoptic_segmentation(...e){return lm(...e)}post_process_instance_segmentation(...e){return cm(...e)}},vE=class extends _m{},yE=class extends de{},zl=class extends de{pad_image(e,t,r,n={}){const[s,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 u=i.map((h,f)=>-h/l[f]);return super.pad_image(e,t,r,{center:!0,constant_values:u,...n})}},bE=class extends zl{},pm=class extends de{},ME=class extends pm{},xE=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))}},TE=class extends de{},kE=class extends de{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=Ft([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},r_=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,n]=e.dims.slice(-2);const s=n/r;return n>=r?(n=Math.ceil(n/t)*t,r=Math.floor(n/s),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,n=Math.floor(r*s),n=Math.ceil(n/t)*t),{height:r,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let s=[],a=[],o=[];const i=[],l=[];for(const b of n){let k=await Promise.all(b.map(F=>this.preprocess(F)));i.push(...k.map(F=>F.original_size)),l.push(...k.map(F=>F.reshaped_input_size)),k.forEach(F=>F.pixel_values.unsqueeze_(0));const{longest_edge:E}=this.max_image_size;let C;if(t??this.do_image_splitting){let F=new Array(k.length),O=new Array(k.length);C=await Promise.all(k.map(async(G,T)=>{const V=this.get_resize_for_vision_encoder(G.pixel_values,E),R=await Wr(G.pixel_values,{size:[V.height,V.width]}),{frames:U,num_splits_h:Z,num_splits_w:H}=await this.split_image(R,this.max_image_size);return F[T]=Z,O[T]=H,Re(U,0)})),a.push(F),o.push(O)}else{const F=[E,E];C=await Promise.all(k.map(O=>Wr(O.pixel_values,{size:F}))),a.push(new Array(k.length).fill(0)),o.push(new Array(k.length).fill(0))}s.push(Re(C,0))}const u=s.length,[h,f,_,g]=s[0].dims;let w,v;if(u===1)w=s[0].unsqueeze_(0),v=ct([u,h,_,g],!0);else{const b=Math.max(...s.map(C=>C.dims.at(0)));v=ct([u,b,_,g],!0);const k=v.data,E=b*_*g;for(let C=0;Cr||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);const u=Math.ceil(a/i),h=Math.ceil(o/l);for(let g=0;gt*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},CE=class extends de{constructor(e){const{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,o=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},i=n==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:s,do_normalize:!0})}},SE=class extends de{},Rl=class extends de{post_process_panoptic_segmentation(...e){return lm(...e)}post_process_instance_segmentation(...e){return cm(...e)}},AE=class extends Rl{},PE=class extends Rl{},mm=class extends de{},FE=class extends mm{},gm=class extends de{},LE=class extends gm{},wm=class extends de{},IE=class extends wm{},vm=class extends de{},OE=class extends vm{},ym=class extends de{},NE=class extends ym{},DE=class extends zl{},$l=class extends de{post_process_object_detection(...e){return Ra(...e)}},BE=class extends $l{},zE=class extends $l{},vt=336,RE=[2,3],{ceil:ii,floor:on,sqrt:li}=Math,$E=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 on((on(t/vt)*on(e/vt)+1)*r+1+(on(t/vt)+1)*li(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[n,s]=e.size;let a=n/s,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,n={}){const[s,a]=t,o=vt*ii(s/vt),i=vt*ii(a/vt),l=[1,1,1].map((u,h)=>(u-this.image_mean[h])/this.image_std[h]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??(t=this.config.num_crops),t<4||li(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,n=await Promise.all(e.map(f=>this.preprocess(f))),s=n.map(f=>f.original_size),a=n.map(f=>f.reshaped_input_size),o=[];for(const{pixel_values:f}of n){f.unsqueeze_(0);const[_,g]=f.dims.slice(-2),w=await Wr(f,{size:[vt,vt],mode:"bicubic"});if(t>0){const v=[],b=li(t),k=on(g/b),E=on(_/b);for(let F=0;Ff.map(_=>vt*ii(_/vt))),u=new j("int64",l.flat(),[r,2]),h=l.map(([f,_])=>this.calc_num_image_tokens_from_image_size(_,f));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:h}}},GE=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[n,s]=e.size,a=Math.max(n,s)/r;let o=n,i=s;a>1&&(o=Math.floor(n/a),i=Math.floor(s/a));const{patch_size:l,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");const h=l*u,f=Math.floor((o-1)/h)+1,_=Math.floor((i-1)/h)+1;return[f*h,_*h]}},VE=class extends de{};function UE(e,t,r=28,n=3136,s=784*1280){if(e200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let a=Math.round(e/r)*r,o=Math.round(t/r)*r;if(a*o>s){const i=Math.sqrt(e*t/s);a=Math.floor(e/i/r)*r,o=Math.floor(t/i/r)*r}else if(a*oa),0));const u=a.dims[0]/o,h=a.dims[1],f=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),g=a.view(u,o,h,Math.floor(f/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(u*f*_,h*o*l*l),w=new j("int64",[u,f,_],[1,3]);return{pixel_values:g,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},jE=class extends de{post_process_object_detection(...e){return Ra(...e)}},ci=class extends de{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=Mf(e);if(s.length===3)n||(s=[1,...s]),e=[e];else if(s.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:n=null}={}){const s=await super._call(e);if(t&&(s.input_points=this.reshape_input_points(t,s.original_sizes,s.reshaped_input_sizes)),r){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(r,s.input_points)}return n&&(s.input_boxes=this.reshape_input_points(n,s.original_sizes,s.reshaped_input_sizes,!0)),s}async post_process_masks(e,t,r,{mask_threshold:n=0,binarize:s=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;ln&&(g[w]=1);f=new j("bool",g,f.dims)}o.push(f)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:s=32,crop_n_points_downscale_factor:a=1}={}){}},bm=class extends de{post_process_semantic_segmentation(...e){return im(...e)}},qE=class extends bm{},Mm=class extends de{post_process_semantic_segmentation(...e){return im(...e)}},HE=class extends Mm{},QE=class extends de{},XE=class extends de{pad_image(e,t,r,n={}){const[s,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}},xm=class extends de{},YE=class extends xm{},KE=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))),n=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:kn(r.map((a,o)=>Re([a.pixel_values,n[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},JE=class extends de{post_process_pose_estimation(e,t,{threshold:r=null}={}){const n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let u=0;u/gm,bboxes:/([^<]+)?/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[n,s]of this.task_prompts_with_input)if(r.includes(n)){t.push(s.replaceAll("{input}",r).replaceAll(n,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const n=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("","").replaceAll("","");let s;switch(n){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=n==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[u,h,...f]of o)i.push(h?h.trim():i.at(-1)??""),l.push(f.map((_,g)=>(Number(_)+.5)/this.size_per_bin*r[g%2]));s={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:s}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=await this.image_processor(e,r),s=t?this.tokenizer(this.construct_prompts(t),r):{};return{...n,...s}}},M(Js,"tokenizer_class",Oe),M(Js,"image_processor_class",wt),Js),Nr,t2=(Nr=class extends Ne{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:n,boa_token:s,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:u,eoi_token:h}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const f=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
+
+${s}${f}${o}
+
+`,this.image_token_id=i,this.boi_token=l,this.image_token=u;const _=u.repeat(this.image_seq_length);this.full_image_sequence=`
+
+${l}${_}${h}
+
+`}async _call(e,t=null,r=null,n={}){typeof e=="string"&&(e=[e]);let s;r&&(s=await this.feature_extractor(r,n),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,n),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...s}}},M(Nr,"image_processor_class",wt),M(Nr,"feature_extractor_class",Zt),M(Nr,"tokenizer_class",Oe),M(Nr,"uses_processor_config",!0),M(Nr,"uses_chat_template_file",!0),Nr);function r2(e,t){const n=e.dims.at(-1)-1,s=e.tolist();s.fill(!1,0,1),s.fill(!1,n);const a=t.tolist();return s.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var Zs,n2=(Zs=class extends Ne{async _call(e,t,r={}){const n=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:n=.25,target_sizes:s=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(s!==null&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),u=a.sigmoid(),h=u.max(-1).tolist(),f=o.tolist().map(g=>g.map(w=>om(w))),_=[];for(let g=0;gC.map((F,O)=>F*w[(O+1)%2])));const v=h[g],b=[],k=[],E=[];for(let C=0;C`+s.repeat(e);o+=`
+`}return o+=`
+${n}${a}`+s.repeat(e)+`${n}`,o}function a2(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function o2(e,t,r,n,s,a){return e===0&&t===0?a2(r,n,s,a):s2(r,e,t,n,s,a)}var es,n_=(es=class extends Ne{constructor(){super(...arguments);M(this,"fake_image_token","");M(this,"image_token","");M(this,"global_img_token","")}async _call(t,r=null,n={}){n.return_row_col_info??(n.return_row_col_info=!0);let s;r&&(s=await this.image_processor(r,n)),Array.isArray(t)||(t=[t]);const a=s.rows??[new Array(t.length).fill(0)],o=s.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],u=[];for(let f=0;fo2(E,w[C],i,this.fake_image_token,this.image_token,this.global_img_token)),b=_.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let k=b[0];for(let E=0;Ev.images).flatMap(v=>v.images).map(v=>_s.read(v)));const n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>n.encode(v,{add_special_tokens:!1}),o=s.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,u,h]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let f=a(o[0]),_=new Array(f.length).fill(!1);for(let v=1;v0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},M(ts,"image_processor_class",wt),M(ts,"tokenizer_class",Oe),M(ts,"uses_processor_config",!0),ts),ea,l2=(ea=class extends Ne{async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=e?this.tokenizer(e,r):{},s=t?await this.image_processor(t,r):{};return{...n,...s}}},M(ea,"tokenizer_class",Oe),M(ea,"image_processor_class",wt),ea),rs,c2=(rs=class extends Ne{async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:u}=this.config,h=Math.floor(a/l)*Math.floor(o/l)+u;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let f=0;f0?w.reduce((b,k)=>b*k,1):0;l.push(g),i.push(v)}return[s(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[n,s]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),u=[],h=[];for(let f=0;f";function f2(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
+`}var ns,_2=(ns=class extends Ne{async _call(e,t=null,r={}){t||(ge.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 n=this.tokenizer.bos_token,s=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(ln))?a=t.map(l=>{const u=l.replaceAll(ln,ln.repeat(s)),h=u.lastIndexOf(ln),f=h===-1?0:h+ln.length;return u.slice(0,f)+n+u.slice(f)+`
+`}):(ge.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(l=>f2(l,n,s,ln,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},M(ns,"tokenizer_class",Oe),M(ns,"image_processor_class",wt),M(ns,"uses_processor_config",!1),ns),a_="<|image|>",p2=/<\|image_\d+\|>/g,sa,m2=(sa=class extends Ne{async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:s});const{num_img_tokens:i}=o,l=e.map((h,f)=>h.split(p2).join(a_.repeat(i[f])));a=this.tokenizer(l,{padding:r,truncation:n});const u=this.tokenizer._tokenizer.token_to_id(a_);a.input_ids.map_(h=>h==u?-h:h)}else a=this.tokenizer(e);return{...a,...o}}},M(sa,"image_processor_class",wt),M(sa,"tokenizer_class",Oe),sa),ss,g2=(ss=class extends Ne{async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:u,patch_size:h,spatial_merge_size:f}=this.config,_=h*f,g=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v{for(;u.includes("<|image_pad|>");){const h=Number(l[i++].reduce((f,_)=>f*_,1n));u=u.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(h/o)))}return u.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}},M(aa,"image_processor_class",wt),M(aa,"tokenizer_class",Oe),aa),Em=class extends km{},v2=class extends Em{},_i,Cm=(_i=class extends Ne{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)}},M(_i,"image_processor_class",wt),_i),Sm=class extends Cm{},y2=class extends Sm{},oa,b2=(oa=class extends Ne{async _call(e){return await this.feature_extractor(e)}},M(oa,"tokenizer_class",Oe),M(oa,"feature_extractor_class",Zt),oa),as,M2=(as=class extends Ne{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};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);n.audio_token_len=[l],n.audio_values=o;const u=this.config.audio_placeholder;if(!e.includes(u))throw new Error(`The input text does not contain the image token ${u}.`);e=e.replaceAll(u,u.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},M(as,"tokenizer_class",Oe),M(as,"feature_extractor_class",Zt),M(as,"uses_processor_config",!0),as),Qs="[AUDIO]",x2="[BEGIN_AUDIO]",T2=375;function k2(e,t){const r=[];for(let n=0;nk2(g,i)),u=l.map(g=>g.length),h=l.flat(),f=(await Promise.all(h.map(g=>this.feature_extractor(g,r)))).map(g=>g.input_features);n.audio_values=f.length>1?Re(f,0):f[0];let _=a[0];for(let g=0;g1)throw new Error("Batched audio inputs are not supported yet.");t=t[0]}const n=this._pad_audio_streaming(t),a=(await this.feature_extractor(n)).input_features,o=1+o_+Am,i=new BigInt64Array(o),l=new BigInt64Array(o);i[0]=BigInt(C2),l[0]=1n;for(let u=1;u0){if(u>Gf)throw new Error(`The number of external data chunks (${u}) exceeds the maximum allowed value (${Gf}).`);const h=B2(o,u);for(const f of h){const _=`${n.subfolder??""}/${f}`;l.push(new Promise(async(g,w)=>{const v=await Pa(e,_,!0,n,i);g(v instanceof Uint8Array?{path:f,data:v}:f)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async h=>{if(typeof h.data=="string"){const f=await Pa(e,h.data,!0,n);return{...h,data:f}}return h}));return Promise.all(l)}async function $2(e,t,r,n=!1){var C;let s=((C=r.config)==null?void 0:C["transformers.js_config"])??{};const a=CT(r.device??s.device,t,{warn:F=>ge.info(F)}),o=TT(a),i=s.device_config??{};i.hasOwnProperty(a)&&(s={...s,...i[a]});const l=AT(r.dtype??s.dtype,t,a,{configDtype:s.dtype,warn:F=>ge.info(F)});if(Xf.hasOwnProperty(l)){if(a==="webgpu"&&!_e.IS_NODE_ENV&&l===lt.fp16&&!await ST())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(lt).join(", ")}`);const u=s.kv_cache_dtype,h=u?typeof u=="string"?u:u[l]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);const f=Xf[l],_={...r.session_options};_.executionProviders??(_.executionProviders=o);const g=s.free_dimension_overrides;g?_.freeDimensionOverrides??(_.freeDimensionOverrides=g):a.startsWith("webnn")&&!_.freeDimensionOverrides&&ge.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"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const w=z2(e,t,r,f),v=r.use_external_data_format??s.use_external_data_format,b=await R2(e,t,f,r,v,_);if(b.length>0&&!_e.IS_NODE_ENV&&(_.externalData=b),n&&a==="webgpu"&&u!==!1){const F=Gl(r.config,{prefix:"present"});if(Object.keys(F).length>0&&!Ll()){const O={};for(const G in F)O[G]="gpu-buffer";_.preferredOutputLocation=O}}return{buffer_or_path:await w,session_options:_,session_config:{dtype:l,kv_cache_dtype:h,device:a}}}async function pt(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const{buffer_or_path:a,session_options:o,session_config:i}=await $2(e,t[s],r,s===n),l=await zp(a,o,i);return[s,l]})))}function Lm(e){for(let t in e)$p(e[t])?e[t]=new j(e[t]):typeof e[t]=="object"&&Lm(e[t]);return e}async function Me(e,t){const r=G2(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return _e.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await Rp(e,n);return Lm(s)}catch(n){const s=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 ge.error(`An error occurred during model execution: "${n}".`),ge.error("Inputs given to model:",s),n}}function G2(e,t){const r=Object.create(null),n=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof j)){n.push(o);continue}r[o]=Ll()?i.clone():i}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ge.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var je=class{},oe=class extends je{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},qe=class extends je{constructor({logits:e}){super(),this.logits=e}},Ye=class extends je{constructor({logits:e}){super(),this.logits=e}},ut=class extends je{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Yr=class extends je{constructor({logits:e}){super(),this.logits=e}},V2=class extends je{constructor({alphas:e}){super(),this.alphas=e}},Ut=class extends Vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},U2=class extends Vt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},rl=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 n of this.processors)r=n(e,r);return r}[Symbol.iterator](){return this.processors.values()}},W2=class extends Ut{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r=1&&s[s.length-1]>=this.timestamp_begin,o=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a&&(o?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const h=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(h+1).fill(-1/0)}const i=dT(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((h,f)=>h+f)),u=We(i.subarray(0,this.timestamp_begin))[0];l>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},Q2=class extends Ut{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let s=0;s1 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,n=t.slice([0,r],null),s=t.slice([r,t.dims[0]],null);for(let a=0;at.length>=this.max_length)}},nC=class extends Vl{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const n=r.at(-1);return this.eos_token_id.some(s=>n==s)})}},$a=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),n=e.data;if(t===-1)n=n.slice(-r);else{let s=t*r;n=n.slice(s,s+r)}return n}randomSelect(e){return J1(e)}static getSampler(e){if(e.do_sample)return new aC(e);if(e.num_beams>1)return new oC(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 sC(e)}},sC=class extends $a{async sample(e){const t=We(e.data)[1];return[[BigInt(t),0]]}},aC=class extends $a{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,n]=await Vp(e,t),s=Tn(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},oC=class extends $a{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,n]=await Vp(e,t),s=Tn(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},us=null;function iC(e){us=e}function ps(e){for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);return Object.values(e)[0].dims.at(-2)}function nl(e){if(e instanceof j)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 j("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new j("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function Dm(e){return new j("bool",[e],[1])}var W={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},i_={[W.DecoderOnly]:{can_generate:!0,forward:Kt,prepare_inputs:La},[W.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Kt,prepare_inputs:La},[W.Seq2Seq]:{can_generate:!0,forward:Xs,prepare_inputs:Ia},[W.Vision2Seq]:{can_generate:!0,forward:Xs,prepare_inputs:Ia},[W.Musicgen]:{can_generate:!0,forward:Xs},[W.EncoderDecoder]:{can_generate:!1,forward:Xs},[W.ImageTextToText]:{can_generate:!0,forward:uC,prepare_inputs:Ys},[W.AudioTextToText]:{can_generate:!0,forward:cC,prepare_inputs:Ys},[W.Phi3V]:{can_generate:!0,prepare_inputs:Ys},[W.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ys},[W.MultiModality]:{can_generate:!0},[W.AutoEncoder]:{can_generate:!1,forward:lC},[W.Chatterbox]:{can_generate:!0,forward:kr},default:{can_generate:!1,forward:kr}},wn=new Map,Ul=new Map,gn=new Map,P=class extends Vt{constructor(t,r,n){super();M(this,"main_input_name","input_ids");M(this,"forward_params",["input_ids","attention_mask"]);M(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=n;const s=gn.get(this.constructor),a=wn.get(s),o=i_[a]??i_.default;this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const t=[];for(const n of Object.values(this.sessions))t.push((r=n.release)==null?void 0:r.call(n));return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:u=null,dtype:h=null,use_external_data_format:f=null,session_options:_={}}={}){const g={progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:u,dtype:h,use_external_data_format:f,session_options:_},w=gn.get(this),v=wn.get(w);n=g.config=await Fm.from_pretrained(t,g);let b;if(v===W.DecoderOnly)b=await Promise.all([pt(t,{model:g.model_file_name??"model"},g,"model"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.Seq2Seq||v===W.Vision2Seq)b=await Promise.all([pt(t,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},g,"decoder_model_merged"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.MaskGeneration)b=await Promise.all([pt(t,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},g)]);else if(v===W.EncoderDecoder)b=await Promise.all([pt(t,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},g,"decoder_model_merged")]);else if(v===W.ImageTextToText){const k={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};n.is_encoder_decoder&&(k.model="encoder_model"),b=await Promise.all([pt(t,k,g,"decoder_model_merged"),ir(t,{generation_config:"generation_config.json"},g)])}else if(v===W.AudioTextToText){const k={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};b=await Promise.all([pt(t,k,g,"decoder_model_merged"),ir(t,{generation_config:"generation_config.json"},g)])}else if(v===W.ImageAudioTextToText){const k={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};b=await Promise.all([pt(t,k,g),ir(t,{generation_config:"generation_config.json"},g)])}else if(v===W.Musicgen)b=await Promise.all([pt(t,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},g,"decoder_model_merged"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.MultiModality)b=await Promise.all([pt(t,{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"},g,"model"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.Phi3V)b=await Promise.all([pt(t,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},g,"model"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.Chatterbox)b=await Promise.all([pt(t,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},g,"model"),ir(t,{generation_config:"generation_config.json"},g)]);else if(v===W.AutoEncoder)b=await Promise.all([pt(t,{encoder_model:"encoder_model",decoder_model:"decoder_model"},g)]);else if(v===W.Supertonic)b=await Promise.all([pt(t,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},g)]);else{if(v===void 0){const k=w??(n==null?void 0:n.model_type);k!=="custom"&&ge.warn(`Model type for '${k}' not found, assuming encoder-only architecture. Please report this at ${Dl}.`)}b=await Promise.all([pt(t,{model:g.model_file_name??"model"},g)])}return new this(n,...b)}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,n=null){const s=new rl;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&s.push(new X2(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&s.push(new Q2(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&s.push(new J2(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&s.push(new Y2(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&s.push(new K2(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&s.push(new W2(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&s.push(new j2(t.max_length,t.forced_eos_token_id)),t.suppress_tokens!==null&&s.push(new q2(t.suppress_tokens)),t.begin_suppress_tokens!==null){const a=r>1||t.forced_bos_token_id===null?r:r+1;s.push(new Im(t.begin_suppress_tokens,a))}return t.guidance_scale!==null&&t.guidance_scale>1&&s.push(new Z2(t.guidance_scale)),t.temperature===0&&t.do_sample&&(ge.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),t.do_sample=!1),t.do_sample&&t.temperature!==null&&t.temperature!==1&&s.push(new eC(t.temperature)),n!==null&&s.extend(n),s}_prepare_generation_config(t,r,n=Om){const s={...this.config};for(const o of["decoder","generator","text_config"])o in s&&Object.assign(s,s[o]);const a=new n(s);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,mt(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){const n=new tC;return t.max_length!==null&&n.push(new rC(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&n.push(new nC(t.eos_token_id)),r&&n.extend(r),n}_validate_model_class(){if(!this.can_generate){const t=[us.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,us.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,us.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,us.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=gn.get(this.constructor),n=new Set,s=this.config.model_type;for(const o of t){const i=o==null?void 0:o.get(s);i&&n.add(i)}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(a+=` Please use the following class instead: ${[...n].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:n,is_encoder_decoder:s}){return n.past_key_values=this.getPastKeyValues(r,n.past_key_values),n.input_ids=new j("int64",t.flat(),[t.length,1]),s||(n.attention_mask=Re([n.attention_mask,Ft([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:n}){const s=mt(n,this.forward_params),a=this.main_input_name;if(a in s){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[a]=t;return{inputs_tensor:s[a],model_inputs:s,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:n,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:o,pixel_values:i,attention_mask:l,...u}=r,h=await this._prepare_inputs_embeds(r);r={...u,...mt(h,["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await kr(this,r);if(s.guidance_scale!==null&&s.guidance_scale>1)a=Re([a,Zi(a,0)],0),"attention_mask"in r&&(r.attention_mask=Re([r.attention_mask,qp(r.attention_mask)],0));else if(r.decoder_input_ids){const o=nl(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=Re(Array.from({length:o},()=>a),0)}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:n,decoder_start_token_id:s,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=n;if(!(i instanceof j)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(s??(s=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==t)throw new Error(`\`decoder_start_token_id\` expcted to have length ${t} but got ${s.length}`);i=s}else i=Array.from({length:t},()=>[s]);i=nl(i)}return n.decoder_attention_mask=Wp(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:n=null,stopping_criteria:s=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:u}=this._prepare_model_inputs({inputs:t,model_kwargs:o});const h=this.config.is_encoder_decoder;h&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:u,generation_config:r})));let f;h?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[u].dims.at(0),model_input_name:u,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[u];let _=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);const g=this._get_logits_processor(r,_,n),w=this._get_stopping_criteria(r,s),v=l[u].dims.at(0),b=$a.getSampler(r),k=new Array(v).fill(0),E=f.tolist();a&&a.put(E);let C,F={},O={};for(;;){if(l=this.prepare_inputs_for_generation(E,l,r),C=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){const H=this.getAttentions(C);for(const D in H)D in F||(F[D]=[]),F[D].push(H[D])}else this._return_dict_in_generate_keys&&Object.assign(O,mt(C,this._return_dict_in_generate_keys));const V=C.logits.slice(null,-1,null).to("float32"),R=g(E,V),U=[];for(let H=0;HH))break;l=this._update_model_kwargs_for_generation({generated_input_ids:U,outputs:C,model_inputs:l,is_encoder_decoder:h})}a&&a.end();const G=this.getPastKeyValues(C,l.past_key_values,!0),T=new j("int64",E.flat(),[E.length,E[0].length]);if(r.return_dict_in_generate)return{sequences:T,past_key_values:G,...F,...O};for(const V of Object.values(C))V.location==="gpu-buffer"&&V.dispose();return T}getPastKeyValues(t,r,n=!1){const s=Object.create(null);for(const a in t)if(a.startsWith("present")){const o=a.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=a.includes("encoder");if(i&&r?s[o]=r[o]:s[o]=t[a],r&&(!i||n)){const l=r[o];l.location==="gpu-buffer"&&l.dispose()}}return s}getAttentions(t){const r={};for(const n of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in t)s.startsWith(n)&&(n in r||(r[n]=[]),r[n].push(t[s]));return r}addPastKeyValues(t,r){var n,s,a;if(r)Object.assign(t,r);else{const o=this.sessions.decoder_model_merged??this.sessions.model,i=((s=(n=t[this.main_input_name]??t.attention_mask)==null?void 0:n.dims)==null?void 0:s[0])??1,l=((a=o==null?void 0:o.config)==null?void 0:a.kv_cache_dtype)??"float32",u=l==="float16"?Fa.float16:Fa.float32,h=Gl(this.config,{batch_size:i});for(const f in h){const _=h[f].reduce((g,w)=>g*w,1);t[f]=new j(l,new u(_),h[f])}}}async encode_image({pixel_values:t}){return(await Me(this.sessions.vision_encoder,{pixel_values:t})).image_features}async encode_text({input_ids:t}){return(await Me(this.sessions.embed_tokens,{input_ids:t})).inputs_embeds}async encode_audio({audio_values:t}){return(await Me(this.sessions.audio_encoder,{audio_values:t})).audio_features}};async function Xs(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,...a}=t;if(!r){const o=mt(t,e.sessions.model.inputNames);r=(await kr(e,o)).last_hidden_state}return a.input_ids=s,a.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=t.attention_mask),await Kt(e,a,!0)}async function kr(e,t){const r=e.sessions.model,n=mt(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=qp(n.input_ids)}if(r.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const s=n.pixel_values.dims;n.pixel_mask=Ft([s[0],s[2],s[3]])}return await Me(r,n)}async function lC(e,t){const r=await e.encode(t);return await e.decode(r)}async function Kt(e,t,r=!1){const n=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:s,...a}=t;if(n.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=Dm(!!s)),n.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=dC(a,s,i)}e.addPastKeyValues(a,s);const o=mt(a,n.inputNames);return await Me(n,o)}async function Bm(e,{encode_function:t,merge_function:r,modality_input_name:n,modality_output_name:s,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:h=null,logits_processor:f=null,..._}){const g=_[n];if(!l){if(l=await e.encode_text({input_ids:a,..._}),g&&a.dims[1]!==1){const v=await t({[n]:g,..._});({inputs_embeds:l,attention_mask:o}=r({[s]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(u&&g&&a.dims[1]===1){const v=a.dims[1],b=ps(u);o=Re([Ft([a.dims[0],b]),o.slice(null,[o.dims[1]-v,o.dims[1]])],1)}}if(!i&&["qwen2_vl","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text"].includes(e.config.model_type)){const{image_grid_thw:v,video_grid_thw:b}=_;[i]=e.get_rope_index(a,v,b,o)}return await Kt(e,{inputs_embeds:l,past_key_values:u,attention_mask:o,position_ids:i,generation_config:h,logits_processor:f},!0)}async function cC(e,t){return await Bm(e,{...t,modality_input_name:"audio_values",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 uC(e,t){return await Bm(e,{...t,modality_input_name:"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 zm(e,t=0){const[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;oa.dims[1]||s[s.at(-1)])),{...r,decoder_input_ids:nl(t)}}function Ys(e,...t){return e.config.is_encoder_decoder?Ia(e,...t):La(e,...t)}function Rm({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(u=>u.reduce((h,f,_)=>(f==e&&h.push(_),h),[])),o=a.reduce((u,h)=>u+h.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 u=0;u{const s=await Er(e,t[n],!1,r);return[n,s]})))}var Wl={};bn(Wl,{ASTForAudioClassification:()=>xC,ASTModel:()=>MC,ASTPreTrainedModel:()=>Ql,AfmoeForCausalLM:()=>vC,AfmoeModel:()=>wC,AfmoePreTrainedModel:()=>ql,AlbertForMaskedLM:()=>pC,AlbertForQuestionAnswering:()=>_C,AlbertForSequenceClassification:()=>fC,AlbertModel:()=>hC,AlbertPreTrainedModel:()=>ys,ApertusForCausalLM:()=>gC,ApertusModel:()=>mC,ApertusPreTrainedModel:()=>jl,ArceeForCausalLM:()=>bC,ArceeModel:()=>yC,ArceePreTrainedModel:()=>Hl,BartForConditionalGeneration:()=>kC,BartForSequenceClassification:()=>EC,BartModel:()=>TC,BartPretrainedModel:()=>Ga,BeitForImageClassification:()=>SC,BeitModel:()=>CC,BeitPreTrainedModel:()=>Xl,BertForMaskedLM:()=>PC,BertForQuestionAnswering:()=>IC,BertForSequenceClassification:()=>FC,BertForTokenClassification:()=>LC,BertModel:()=>AC,BertPreTrainedModel:()=>En,BlenderbotForConditionalGeneration:()=>NC,BlenderbotModel:()=>OC,BlenderbotPreTrainedModel:()=>Yl,BlenderbotSmallForConditionalGeneration:()=>BC,BlenderbotSmallModel:()=>DC,BlenderbotSmallPreTrainedModel:()=>Kl,BloomForCausalLM:()=>RC,BloomModel:()=>zC,BloomPreTrainedModel:()=>Jl,CLIPModel:()=>QC,CLIPPreTrainedModel:()=>Kr,CLIPSegForImageSegmentation:()=>ZC,CLIPSegModel:()=>JC,CLIPSegPreTrainedModel:()=>Zl,CLIPTextModel:()=>XC,CLIPTextModelWithProjection:()=>qm,CLIPVisionModel:()=>YC,CLIPVisionModelWithProjection:()=>KC,CamembertForMaskedLM:()=>GC,CamembertForQuestionAnswering:()=>WC,CamembertForSequenceClassification:()=>VC,CamembertForTokenClassification:()=>UC,CamembertModel:()=>$C,CamembertPreTrainedModel:()=>Cn,ChatterboxModel:()=>Vm,ChatterboxPreTrainedModel:()=>Gm,ChineseCLIPModel:()=>qC,ChineseCLIPPreTrainedModel:()=>Um,ClapAudioModelWithProjection:()=>jm,ClapModel:()=>HC,ClapPreTrainedModel:()=>Va,ClapTextModelWithProjection:()=>Wm,CodeGenForCausalLM:()=>tS,CodeGenModel:()=>eS,CodeGenPreTrainedModel:()=>ec,Cohere2ForCausalLM:()=>aS,Cohere2Model:()=>sS,Cohere2PreTrainedModel:()=>rc,CohereForCausalLM:()=>nS,CohereModel:()=>rS,CoherePreTrainedModel:()=>tc,ConvBertForMaskedLM:()=>iS,ConvBertForQuestionAnswering:()=>uS,ConvBertForSequenceClassification:()=>lS,ConvBertForTokenClassification:()=>cS,ConvBertModel:()=>oS,ConvBertPreTrainedModel:()=>Sn,ConvNextForImageClassification:()=>hS,ConvNextModel:()=>dS,ConvNextPreTrainedModel:()=>nc,ConvNextV2ForImageClassification:()=>_S,ConvNextV2Model:()=>fS,ConvNextV2PreTrainedModel:()=>sc,DFineForObjectDetection:()=>wS,DFineModel:()=>gS,DFinePreTrainedModel:()=>oc,DINOv3ConvNextModel:()=>VS,DINOv3ConvNextPreTrainedModel:()=>tg,DINOv3ViTModel:()=>US,DINOv3ViTPreTrainedModel:()=>rg,DPTForDepthEstimation:()=>KS,DPTModel:()=>YS,DPTPreTrainedModel:()=>dc,DacDecoderModel:()=>Ym,DacDecoderOutput:()=>Qm,DacEncoderModel:()=>Xm,DacEncoderOutput:()=>Hm,DacModel:()=>vS,DacPreTrainedModel:()=>Ua,DebertaForMaskedLM:()=>bS,DebertaForQuestionAnswering:()=>TS,DebertaForSequenceClassification:()=>MS,DebertaForTokenClassification:()=>xS,DebertaModel:()=>yS,DebertaPreTrainedModel:()=>An,DebertaV2ForMaskedLM:()=>ES,DebertaV2ForQuestionAnswering:()=>AS,DebertaV2ForSequenceClassification:()=>CS,DebertaV2ForTokenClassification:()=>SS,DebertaV2Model:()=>kS,DebertaV2PreTrainedModel:()=>Pn,DecisionTransformerModel:()=>PS,DecisionTransformerPreTrainedModel:()=>Km,DeiTForImageClassification:()=>LS,DeiTModel:()=>FS,DeiTPreTrainedModel:()=>ic,DepthAnythingForDepthEstimation:()=>IS,DepthAnythingPreTrainedModel:()=>Jm,DepthProForDepthEstimation:()=>OS,DepthProPreTrainedModel:()=>Zm,DetrForObjectDetection:()=>DS,DetrForSegmentation:()=>BS,DetrModel:()=>NS,DetrObjectDetectionOutput:()=>lc,DetrPreTrainedModel:()=>Wa,DetrSegmentationOutput:()=>eg,Dinov2ForImageClassification:()=>RS,Dinov2Model:()=>zS,Dinov2PreTrainedModel:()=>cc,Dinov2WithRegistersForImageClassification:()=>GS,Dinov2WithRegistersModel:()=>$S,Dinov2WithRegistersPreTrainedModel:()=>uc,DistilBertForMaskedLM:()=>QS,DistilBertForQuestionAnswering:()=>HS,DistilBertForSequenceClassification:()=>jS,DistilBertForTokenClassification:()=>qS,DistilBertModel:()=>WS,DistilBertPreTrainedModel:()=>Fn,DonutSwinModel:()=>XS,DonutSwinPreTrainedModel:()=>ng,EdgeTamModel:()=>UL,EfficientNetForImageClassification:()=>ZS,EfficientNetModel:()=>JS,EfficientNetPreTrainedModel:()=>hc,ElectraForMaskedLM:()=>tA,ElectraForQuestionAnswering:()=>sA,ElectraForSequenceClassification:()=>rA,ElectraForTokenClassification:()=>nA,ElectraModel:()=>eA,ElectraPreTrainedModel:()=>Ln,Ernie4_5ForCausalLM:()=>oA,Ernie4_5Model:()=>aA,Ernie4_5PretrainedModel:()=>fc,EsmForMaskedLM:()=>lA,EsmForSequenceClassification:()=>cA,EsmForTokenClassification:()=>uA,EsmModel:()=>iA,EsmPreTrainedModel:()=>Ms,ExaoneForCausalLM:()=>hA,ExaoneModel:()=>dA,ExaonePreTrainedModel:()=>_c,FalconForCausalLM:()=>_A,FalconH1ForCausalLM:()=>mA,FalconH1Model:()=>pA,FalconH1PreTrainedModel:()=>mc,FalconModel:()=>fA,FalconPreTrainedModel:()=>pc,FastViTForImageClassification:()=>wA,FastViTModel:()=>gA,FastViTPreTrainedModel:()=>gc,Florence2ForConditionalGeneration:()=>vA,Florence2PreTrainedModel:()=>sg,GLPNForDepthEstimation:()=>AA,GLPNModel:()=>SA,GLPNPreTrainedModel:()=>Mc,GPT2LMHeadModel:()=>RA,GPT2Model:()=>zA,GPT2PreTrainedModel:()=>Cc,GPTBigCodeForCausalLM:()=>FA,GPTBigCodeModel:()=>PA,GPTBigCodePreTrainedModel:()=>xc,GPTJForCausalLM:()=>GA,GPTJModel:()=>$A,GPTJPreTrainedModel:()=>Sc,GPTNeoForCausalLM:()=>IA,GPTNeoModel:()=>LA,GPTNeoPreTrainedModel:()=>Tc,GPTNeoXForCausalLM:()=>NA,GPTNeoXModel:()=>OA,GPTNeoXPreTrainedModel:()=>kc,Gemma2ForCausalLM:()=>xA,Gemma2Model:()=>MA,Gemma2PreTrainedModel:()=>vc,Gemma3ForCausalLM:()=>kA,Gemma3Model:()=>TA,Gemma3PreTrainedModel:()=>yc,Gemma3nForConditionalGeneration:()=>og,Gemma3nPreTrainedModel:()=>ag,GemmaForCausalLM:()=>bA,GemmaModel:()=>yA,GemmaPreTrainedModel:()=>wc,GlmForCausalLM:()=>CA,GlmModel:()=>EA,GlmPreTrainedModel:()=>bc,GptOssForCausalLM:()=>BA,GptOssModel:()=>DA,GptOssPreTrainedModel:()=>Ec,GraniteForCausalLM:()=>UA,GraniteModel:()=>VA,GraniteMoeHybridForCausalLM:()=>jA,GraniteMoeHybridModel:()=>WA,GraniteMoeHybridPreTrainedModel:()=>Pc,GranitePreTrainedModel:()=>Ac,GroundingDinoForObjectDetection:()=>qA,GroundingDinoPreTrainedModel:()=>ig,GroupViTModel:()=>HA,GroupViTPreTrainedModel:()=>lg,HeliumForCausalLM:()=>XA,HeliumModel:()=>QA,HeliumPreTrainedModel:()=>Fc,HieraForImageClassification:()=>KA,HieraModel:()=>YA,HieraPreTrainedModel:()=>Lc,HubertForCTC:()=>sP,HubertForSequenceClassification:()=>aP,HubertModel:()=>nP,HubertPreTrainedModel:()=>rP,HunYuanDenseV1ForCausalLM:()=>iP,HunYuanDenseV1Model:()=>oP,HunYuanDenseV1PreTrainedModel:()=>Ic,IJepaForImageClassification:()=>uP,IJepaModel:()=>cP,IJepaPreTrainedModel:()=>Oc,Idefics3ForConditionalGeneration:()=>ug,Idefics3PreTrainedModel:()=>cg,JAISLMHeadModel:()=>hP,JAISModel:()=>dP,JAISPreTrainedModel:()=>Nc,JinaCLIPModel:()=>fP,JinaCLIPPreTrainedModel:()=>ja,JinaCLIPTextModel:()=>dg,JinaCLIPVisionModel:()=>_P,Lfm2ForCausalLM:()=>mP,Lfm2Model:()=>pP,Lfm2MoeForCausalLM:()=>wP,Lfm2MoeModel:()=>gP,Lfm2MoePreTrainedModel:()=>Bc,Lfm2PreTrainedModel:()=>Dc,LiteWhisperForConditionalGeneration:()=>aO,Llama4ForCausalLM:()=>bP,Llama4PreTrainedModel:()=>hg,LlamaForCausalLM:()=>yP,LlamaModel:()=>vP,LlamaPreTrainedModel:()=>zc,LlavaForConditionalGeneration:()=>Oa,LlavaOnevisionForConditionalGeneration:()=>Oa,LlavaPreTrainedModel:()=>fg,LlavaQwen2ForCausalLM:()=>xP,LongT5ForConditionalGeneration:()=>kP,LongT5Model:()=>TP,LongT5PreTrainedModel:()=>Rc,M2M100ForConditionalGeneration:()=>CP,M2M100Model:()=>EP,M2M100PreTrainedModel:()=>$c,MBartForCausalLM:()=>NP,MBartForConditionalGeneration:()=>IP,MBartForSequenceClassification:()=>OP,MBartModel:()=>LP,MBartPreTrainedModel:()=>xs,MPNetForMaskedLM:()=>vF,MPNetForQuestionAnswering:()=>MF,MPNetForSequenceClassification:()=>yF,MPNetForTokenClassification:()=>bF,MPNetModel:()=>wF,MPNetPreTrainedModel:()=>In,MT5ForConditionalGeneration:()=>EF,MT5Model:()=>kF,MT5PreTrainedModel:()=>Yc,MarianMTModel:()=>AP,MarianModel:()=>SP,MarianPreTrainedModel:()=>Gc,MaskFormerForInstanceSegmentation:()=>FP,MaskFormerModel:()=>PP,MaskFormerPreTrainedModel:()=>Vc,Metric3DForDepthEstimation:()=>DP,Metric3DPreTrainedModel:()=>_g,Metric3Dv2ForDepthEstimation:()=>BP,Metric3Dv2PreTrainedModel:()=>pg,MgpstrForSceneTextRecognition:()=>zP,MgpstrModelOutput:()=>mg,MgpstrPreTrainedModel:()=>gg,MimiDecoderModel:()=>bg,MimiDecoderOutput:()=>vg,MimiEncoderModel:()=>yg,MimiEncoderOutput:()=>wg,MimiModel:()=>RP,MimiPreTrainedModel:()=>qa,MistralForCausalLM:()=>GP,MistralModel:()=>$P,MistralPreTrainedModel:()=>Uc,MobileBertForMaskedLM:()=>UP,MobileBertForQuestionAnswering:()=>jP,MobileBertForSequenceClassification:()=>WP,MobileBertModel:()=>VP,MobileBertPreTrainedModel:()=>Ts,MobileLLMForCausalLM:()=>HP,MobileLLMModel:()=>qP,MobileLLMPreTrainedModel:()=>Wc,MobileNetV1ForImageClassification:()=>XP,MobileNetV1ForSemanticSegmentation:()=>YP,MobileNetV1Model:()=>QP,MobileNetV1PreTrainedModel:()=>Ha,MobileNetV2ForImageClassification:()=>JP,MobileNetV2ForSemanticSegmentation:()=>ZP,MobileNetV2Model:()=>KP,MobileNetV2PreTrainedModel:()=>Qa,MobileNetV3ForImageClassification:()=>tF,MobileNetV3ForSemanticSegmentation:()=>rF,MobileNetV3Model:()=>eF,MobileNetV3PreTrainedModel:()=>Xa,MobileNetV4ForImageClassification:()=>sF,MobileNetV4ForSemanticSegmentation:()=>aF,MobileNetV4Model:()=>nF,MobileNetV4PreTrainedModel:()=>Ya,MobileViTForImageClassification:()=>iF,MobileViTModel:()=>oF,MobileViTPreTrainedModel:()=>jc,MobileViTV2ForImageClassification:()=>cF,MobileViTV2Model:()=>lF,MobileViTV2PreTrainedModel:()=>qc,ModernBertDecoderForCausalLM:()=>pF,ModernBertDecoderModel:()=>_F,ModernBertDecoderPreTrainedModel:()=>Hc,ModernBertForMaskedLM:()=>dF,ModernBertForSequenceClassification:()=>hF,ModernBertForTokenClassification:()=>fF,ModernBertModel:()=>uF,ModernBertPreTrainedModel:()=>ks,Moondream1ForConditionalGeneration:()=>MP,MoonshineForConditionalGeneration:()=>gF,MoonshineModel:()=>mF,MoonshinePreTrainedModel:()=>Qc,MptForCausalLM:()=>TF,MptModel:()=>xF,MptPreTrainedModel:()=>Xc,MultiModalityCausalLM:()=>CF,MultiModalityPreTrainedModel:()=>Mg,MusicgenForCausalLM:()=>AF,MusicgenForConditionalGeneration:()=>xg,MusicgenModel:()=>SF,MusicgenPreTrainedModel:()=>Kc,NanoChatForCausalLM:()=>FF,NanoChatModel:()=>PF,NanoChatPreTrainedModel:()=>Jc,NeoBertForMaskedLM:()=>IF,NeoBertForQuestionAnswering:()=>DF,NeoBertForSequenceClassification:()=>OF,NeoBertForTokenClassification:()=>NF,NeoBertModel:()=>LF,NeoBertPreTrainedModel:()=>On,NomicBertModel:()=>BF,NomicBertPreTrainedModel:()=>Tg,OPTForCausalLM:()=>XF,OPTModel:()=>QF,OPTPreTrainedModel:()=>su,Olmo2ForCausalLM:()=>GF,Olmo2Model:()=>$F,Olmo2PreTrainedModel:()=>eu,Olmo3ForCausalLM:()=>UF,Olmo3Model:()=>VF,Olmo3PreTrainedModel:()=>tu,OlmoForCausalLM:()=>RF,OlmoHybridForCausalLM:()=>jF,OlmoHybridModel:()=>WF,OlmoHybridPreTrainedModel:()=>ru,OlmoModel:()=>zF,OlmoPreTrainedModel:()=>Zc,OpenELMForCausalLM:()=>HF,OpenELMModel:()=>qF,OpenELMPreTrainedModel:()=>nu,OwlViTForObjectDetection:()=>ZF,OwlViTModel:()=>JF,OwlViTPreTrainedModel:()=>ou,Owlv2ForObjectDetection:()=>KF,Owlv2Model:()=>YF,Owlv2PreTrainedModel:()=>au,PaliGemmaForConditionalGeneration:()=>eL,PaliGemmaPreTrainedModel:()=>kg,ParakeetForCTC:()=>tL,ParakeetPreTrainedModel:()=>Eg,PatchTSMixerForPrediction:()=>nL,PatchTSMixerModel:()=>rL,PatchTSMixerPreTrainedModel:()=>iu,PatchTSTForPrediction:()=>aL,PatchTSTModel:()=>sL,PatchTSTPreTrainedModel:()=>lu,Phi3ForCausalLM:()=>cL,Phi3Model:()=>lL,Phi3PreTrainedModel:()=>uu,Phi3VForCausalLM:()=>Sg,Phi3VPreTrainedModel:()=>Cg,PhiForCausalLM:()=>iL,PhiModel:()=>oL,PhiPreTrainedModel:()=>cu,PreTrainedModel:()=>P,PvtForImageClassification:()=>dL,PvtModel:()=>uL,PvtPreTrainedModel:()=>du,PyAnnoteForAudioFrameClassification:()=>fL,PyAnnoteModel:()=>hL,PyAnnotePreTrainedModel:()=>hu,Qwen2ForCausalLM:()=>pL,Qwen2Model:()=>_L,Qwen2MoeForCausalLM:()=>gL,Qwen2MoeModel:()=>mL,Qwen2MoePreTrainedModel:()=>_u,Qwen2PreTrainedModel:()=>fu,Qwen2VLForConditionalGeneration:()=>Pg,Qwen2VLPreTrainedModel:()=>Ag,Qwen2_5_VLForConditionalGeneration:()=>Fg,Qwen3ForCausalLM:()=>vL,Qwen3Model:()=>wL,Qwen3MoeForCausalLM:()=>bL,Qwen3MoeModel:()=>yL,Qwen3MoePreTrainedModel:()=>mu,Qwen3NextForCausalLM:()=>xL,Qwen3NextModel:()=>ML,Qwen3NextPreTrainedModel:()=>gu,Qwen3PreTrainedModel:()=>pu,Qwen3VLForConditionalGeneration:()=>wu,Qwen3VLMoeForConditionalGeneration:()=>TL,Qwen3_5ForConditionalGeneration:()=>Lg,Qwen3_5MoeForConditionalGeneration:()=>kL,RFDetrForObjectDetection:()=>AL,RFDetrModel:()=>SL,RFDetrObjectDetectionOutput:()=>Ig,RFDetrPreTrainedModel:()=>yu,RTDetrForObjectDetection:()=>mS,RTDetrModel:()=>pS,RTDetrObjectDetectionOutput:()=>bs,RTDetrPreTrainedModel:()=>ac,RTDetrV2ForObjectDetection:()=>GL,RTDetrV2Model:()=>$L,RTDetrV2ObjectDetectionOutput:()=>Og,RTDetrV2PreTrainedModel:()=>bu,ResNetForImageClassification:()=>CL,ResNetModel:()=>EL,ResNetPreTrainedModel:()=>vu,RoFormerForMaskedLM:()=>DL,RoFormerForQuestionAnswering:()=>RL,RoFormerForSequenceClassification:()=>BL,RoFormerForTokenClassification:()=>zL,RoFormerModel:()=>NL,RoFormerPreTrainedModel:()=>Dn,RobertaForMaskedLM:()=>FL,RobertaForQuestionAnswering:()=>OL,RobertaForSequenceClassification:()=>LL,RobertaForTokenClassification:()=>IL,RobertaModel:()=>PL,RobertaPreTrainedModel:()=>Nn,Sam2ImageSegmentationOutput:()=>Bg,Sam2Model:()=>Mu,Sam2PreTrainedModel:()=>zg,Sam3TrackerModel:()=>WL,SamImageSegmentationOutput:()=>Ng,SamModel:()=>VL,SamPreTrainedModel:()=>Dg,SapiensForDepthEstimation:()=>qL,SapiensForNormalEstimation:()=>HL,SapiensForSemanticSegmentation:()=>jL,SapiensPreTrainedModel:()=>Ka,SegformerForImageClassification:()=>XL,SegformerForSemanticSegmentation:()=>YL,SegformerModel:()=>QL,SegformerPreTrainedModel:()=>Ja,SiglipModel:()=>KL,SiglipPreTrainedModel:()=>xu,SiglipTextModel:()=>Rg,SiglipVisionModel:()=>JL,SmolLM3ForCausalLM:()=>eI,SmolLM3Model:()=>ZL,SmolLM3PreTrainedModel:()=>Tu,SmolVLMForConditionalGeneration:()=>lP,SnacDecoderModel:()=>Gg,SnacEncoderModel:()=>$g,SnacModel:()=>tI,SnacPreTrainedModel:()=>Za,SpeechT5ForSpeechToText:()=>nI,SpeechT5ForTextToSpeech:()=>sI,SpeechT5HifiGan:()=>aI,SpeechT5Model:()=>rI,SpeechT5PreTrainedModel:()=>eo,SqueezeBertForMaskedLM:()=>iI,SqueezeBertForQuestionAnswering:()=>cI,SqueezeBertForSequenceClassification:()=>lI,SqueezeBertModel:()=>oI,SqueezeBertPreTrainedModel:()=>Es,StableLmForCausalLM:()=>dI,StableLmModel:()=>uI,StableLmPreTrainedModel:()=>ku,Starcoder2ForCausalLM:()=>fI,Starcoder2Model:()=>hI,Starcoder2PreTrainedModel:()=>Eu,StyleTextToSpeech2Model:()=>_I,StyleTextToSpeech2PreTrainedModel:()=>Vg,SupertonicForConditionalGeneration:()=>Wg,SupertonicPreTrainedModel:()=>Ug,Swin2SRForImageSuperResolution:()=>vI,Swin2SRModel:()=>wI,Swin2SRPreTrainedModel:()=>Cu,SwinForImageClassification:()=>mI,SwinForSemanticSegmentation:()=>gI,SwinModel:()=>pI,SwinPreTrainedModel:()=>to,T5ForConditionalGeneration:()=>bI,T5Model:()=>yI,T5PreTrainedModel:()=>Su,TableTransformerForObjectDetection:()=>xI,TableTransformerModel:()=>MI,TableTransformerObjectDetectionOutput:()=>jg,TableTransformerPreTrainedModel:()=>Au,TrOCRForCausalLM:()=>TI,TrOCRPreTrainedModel:()=>qg,UltravoxModel:()=>Qg,UltravoxPreTrainedModel:()=>Hg,UniSpeechForCTC:()=>FI,UniSpeechForSequenceClassification:()=>LI,UniSpeechModel:()=>PI,UniSpeechPreTrainedModel:()=>ro,UniSpeechSatForAudioFrameClassification:()=>DI,UniSpeechSatForCTC:()=>OI,UniSpeechSatForSequenceClassification:()=>NI,UniSpeechSatModel:()=>II,UniSpeechSatPreTrainedModel:()=>Cs,VaultGemmaForCausalLM:()=>zI,VaultGemmaModel:()=>BI,VaultGemmaPreTrainedModel:()=>Pu,ViTForImageClassification:()=>GI,ViTMAEModel:()=>VI,ViTMAEPreTrainedModel:()=>Kg,ViTMSNForImageClassification:()=>WI,ViTMSNModel:()=>UI,ViTMSNPreTrainedModel:()=>Lu,ViTModel:()=>$I,ViTPreTrainedModel:()=>Fu,VisionEncoderDecoderModel:()=>RI,VitMatteForImageMatting:()=>jI,VitMattePreTrainedModel:()=>Jg,VitPoseForPoseEstimation:()=>qI,VitPosePreTrainedModel:()=>Zg,VitsModel:()=>HI,VitsModelOutput:()=>ew,VitsPreTrainedModel:()=>tw,VoxtralForConditionalGeneration:()=>kI,VoxtralRealtimeForConditionalGeneration:()=>Yg,VoxtralRealtimePreTrainedModel:()=>Xg,Wav2Vec2BertForCTC:()=>XI,Wav2Vec2BertForSequenceClassification:()=>YI,Wav2Vec2BertModel:()=>QI,Wav2Vec2BertPreTrainedModel:()=>no,Wav2Vec2ForAudioFrameClassification:()=>tP,Wav2Vec2ForCTC:()=>ZA,Wav2Vec2ForSequenceClassification:()=>eP,Wav2Vec2Model:()=>JA,Wav2Vec2PreTrainedModel:()=>Ar,WavLMForAudioFrameClassification:()=>tO,WavLMForCTC:()=>JI,WavLMForSequenceClassification:()=>ZI,WavLMForXVector:()=>eO,WavLMModel:()=>KI,WavLMPreTrainedModel:()=>Bn,WeSpeakerResNetModel:()=>rO,WeSpeakerResNetPreTrainedModel:()=>nw,WhisperForConditionalGeneration:()=>sw,WhisperModel:()=>sO,WhisperPreTrainedModel:()=>Iu,XLMForQuestionAnswering:()=>uO,XLMForSequenceClassification:()=>lO,XLMForTokenClassification:()=>cO,XLMModel:()=>oO,XLMPreTrainedModel:()=>zn,XLMRobertaForMaskedLM:()=>hO,XLMRobertaForQuestionAnswering:()=>pO,XLMRobertaForSequenceClassification:()=>fO,XLMRobertaForTokenClassification:()=>_O,XLMRobertaModel:()=>dO,XLMRobertaPreTrainedModel:()=>Rn,XLMWithLMHeadModel:()=>iO,XVectorOutput:()=>rw,YolosForObjectDetection:()=>gO,YolosModel:()=>mO,YolosObjectDetectionOutput:()=>aw,YolosPreTrainedModel:()=>Ou,YoutuForCausalLM:()=>vO,YoutuModel:()=>wO,YoutuPreTrainedModel:()=>Nu});var ys=class extends P{},hC=class extends ys{},fC=class extends ys{async _call(e){return new oe(await super._call(e))}},_C=class extends ys{async _call(e){return new ut(await super._call(e))}},pC=class extends ys{async _call(e){return new Ye(await super._call(e))}},jl=class extends P{},mC=class extends jl{},gC=class extends jl{},ql=class extends P{},wC=class extends ql{},vC=class extends ql{},Hl=class extends P{},yC=class extends Hl{},bC=class extends Hl{},Ql=class extends P{},MC=class extends Ql{},xC=class extends Ql{},Ga=class extends P{},TC=class extends Ga{},kC=class extends Ga{},EC=class extends Ga{async _call(e){return new oe(await super._call(e))}},Xl=class extends P{},CC=class extends Xl{},SC=class extends Xl{async _call(e){return new oe(await super._call(e))}},En=class extends P{},AC=class extends En{},PC=class extends En{async _call(e){return new Ye(await super._call(e))}},FC=class extends En{async _call(e){return new oe(await super._call(e))}},LC=class extends En{async _call(e){return new qe(await super._call(e))}},IC=class extends En{async _call(e){return new ut(await super._call(e))}},Yl=class extends P{},OC=class extends Yl{},NC=class extends Yl{},Kl=class extends P{},DC=class extends Kl{},BC=class extends Kl{},Jl=class extends P{},zC=class extends Jl{},RC=class extends Jl{},Cn=class extends P{},$C=class extends Cn{},GC=class extends Cn{async _call(e){return new Ye(await super._call(e))}},VC=class extends Cn{async _call(e){return new oe(await super._call(e))}},UC=class extends Cn{async _call(e){return new qe(await super._call(e))}},WC=class extends Cn{async _call(e){return new ut(await super._call(e))}},jC=4299n,l_=6561n,Gm=class extends P{constructor(){super(...arguments);M(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"]);M(this,"main_input_name","input_ids");M(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},Vm=class extends Gm{async encode_speech(e){return Me(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:u=null,audio_tokens:h=null,speaker_embeddings:f=null,speaker_features:_=null,...g}){let w;if(!a){const b=this.sessions.embed_tokens.inputNames,k={input_ids:e};if(b.includes("exaggeration")){if(!(n instanceof j)){const E=e.dims[0];if(n==null)n=ct([E],.5);else if(typeof n=="number")n=ct([E],n);else if(Array.isArray(n))n=new j("float32",n,[E]);else throw new Error("Unsupported type for `exaggeration` input")}k.exaggeration=n}if(b.includes("position_ids")&&(k.position_ids=s),{inputs_embeds:a}=await Me(this.sessions.embed_tokens,k),u&&h&&f&&_&&(w={audio_features:u,audio_tokens:h,speaker_embeddings:f,speaker_features:_}),w||r)w??(w=await this.encode_speech(r)),a=Re([w.audio_features,a],1),t=Ft([a.dims[0],a.dims[1]]);else{const E=a.dims[1];if(!o||E!==1)throw new Error("Incorrect state encountered during generation.");const C=Object.values(o)[0].dims.at(-2);t=Ft([a.dims[0],C+E])}}return{...await Kt(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 n=Array.from({length:e.length},(s,a)=>e[a].length-e[a].findLastIndex(o=>o==l_)-1);t.position_ids=new j("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=l_?0:o++)});t.position_ids=new j("int64",s.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),La(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:n,speaker_features:s}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=ct([a.dims[0],3],jC),i=Re([r,a,o],1),{waveform:l}=await Me(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:s,speaker_embeddings:n});return l}},Um=class extends P{},qC=class extends Um{},Va=class extends P{},HC=class extends Va{},Wm=class extends Va{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},jm=class extends Va{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{},QC=class extends Kr{},XC=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},qm=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},YC=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},KC=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Zl=class extends P{},JC=class extends Zl{},ZC=class extends Zl{},ec=class extends P{},eS=class extends ec{},tS=class extends ec{},tc=class extends P{},rS=class extends tc{},nS=class extends tc{},rc=class extends P{},sS=class extends rc{},aS=class extends rc{},Sn=class extends P{},oS=class extends Sn{},iS=class extends Sn{async _call(e){return new Ye(await super._call(e))}},lS=class extends Sn{async _call(e){return new oe(await super._call(e))}},cS=class extends Sn{async _call(e){return new qe(await super._call(e))}},uS=class extends Sn{async _call(e){return new ut(await super._call(e))}},nc=class extends P{},dS=class extends nc{},hS=class extends nc{async _call(e){return new oe(await super._call(e))}},sc=class extends P{},fS=class extends sc{},_S=class extends sc{async _call(e){return new oe(await super._call(e))}},ac=class extends P{},pS=class extends ac{},mS=class extends ac{async _call(e){return new bs(await super._call(e))}},bs=class extends je{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},oc=class extends P{},gS=class extends oc{},wS=class extends oc{async _call(e){return new bs(await super._call(e))}},Hm=class extends je{constructor({audio_codes:e}){super(),this.audio_codes=e}},Qm=class extends je{constructor({audio_values:e}){super(),this.audio_values=e}},Ua=class extends P{constructor(){super(...arguments);M(this,"main_input_name","input_values");M(this,"forward_params",["input_values"])}},vS=class extends Ua{async encode(e){return new Hm(await Me(this.sessions.encoder_model,e))}async decode(e){return new Qm(await Me(this.sessions.decoder_model,e))}},Xm=class extends Ua{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Ym=class extends Ua{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},An=class extends P{},yS=class extends An{},bS=class extends An{async _call(e){return new Ye(await super._call(e))}},MS=class extends An{async _call(e){return new oe(await super._call(e))}},xS=class extends An{async _call(e){return new qe(await super._call(e))}},TS=class extends An{async _call(e){return new ut(await super._call(e))}},Pn=class extends P{},kS=class extends Pn{},ES=class extends Pn{async _call(e){return new Ye(await super._call(e))}},CS=class extends Pn{async _call(e){return new oe(await super._call(e))}},SS=class extends Pn{async _call(e){return new qe(await super._call(e))}},AS=class extends Pn{async _call(e){return new ut(await super._call(e))}},Km=class extends P{},PS=class extends Km{},ic=class extends P{},FS=class extends ic{},LS=class extends ic{async _call(e){return new oe(await super._call(e))}},Jm=class extends P{},IS=class extends Jm{},Zm=class extends P{},OS=class extends Zm{},Wa=class extends P{},NS=class extends Wa{},DS=class extends Wa{async _call(e){return new lc(await super._call(e))}},BS=class extends Wa{async _call(e){return new eg(await super._call(e))}},lc=class extends je{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},eg=class extends je{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},cc=class extends P{},zS=class extends cc{},RS=class extends cc{async _call(e){return new oe(await super._call(e))}},uc=class extends P{},$S=class extends uc{},GS=class extends uc{async _call(e){return new oe(await super._call(e))}},tg=class extends P{},VS=class extends tg{},rg=class extends P{},US=class extends rg{},Fn=class extends P{},WS=class extends Fn{},jS=class extends Fn{async _call(e){return new oe(await super._call(e))}},qS=class extends Fn{async _call(e){return new qe(await super._call(e))}},HS=class extends Fn{async _call(e){return new ut(await super._call(e))}},QS=class extends Fn{async _call(e){return new Ye(await super._call(e))}},ng=class extends P{},XS=class extends ng{},dc=class extends P{},YS=class extends dc{},KS=class extends dc{},hc=class extends P{},JS=class extends hc{},ZS=class extends hc{async _call(e){return new oe(await super._call(e))}},Ln=class extends P{},eA=class extends Ln{},tA=class extends Ln{async _call(e){return new Ye(await super._call(e))}},rA=class extends Ln{async _call(e){return new oe(await super._call(e))}},nA=class extends Ln{async _call(e){return new qe(await super._call(e))}},sA=class extends Ln{async _call(e){return new ut(await super._call(e))}},fc=class extends P{},aA=class extends fc{},oA=class extends fc{},Ms=class extends P{},iA=class extends Ms{},lA=class extends Ms{async _call(e){return new Ye(await super._call(e))}},cA=class extends Ms{async _call(e){return new oe(await super._call(e))}},uA=class extends Ms{async _call(e){return new qe(await super._call(e))}},_c=class extends P{},dA=class extends _c{},hA=class extends _c{},pc=class extends P{},fA=class extends pc{},_A=class extends pc{},mc=class extends P{},pA=class extends mc{},mA=class extends mc{},gc=class extends P{},gA=class extends gc{},wA=class extends gc{async _call(e){return new oe(await super._call(e))}},sg=class extends P{constructor(){super(...arguments);M(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"]);M(this,"main_input_name","inputs_embeds")}},vA=class extends sg{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Re([t,e],1),attention_mask:Re([Ft(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:n}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let s,a;return e&&(s=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),s&&a?{inputs_embeds:r,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:s,image_features:a,input_ids:e,attention_mask:n}):r=s||a,{inputs_embeds:r,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:n,decoder_attention_mask:s,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:h}=await kr(this,{inputs_embeds:i,attention_mask:r});a=h}if(!l){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}return await Kt(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},wc=class extends P{},yA=class extends wc{},bA=class extends wc{},vc=class extends P{},MA=class extends vc{},xA=class extends vc{},yc=class extends P{},TA=class extends yc{},kA=class extends yc{},ag=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},og=class extends ag{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:n=null,input_features_mask:s=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:u=null,logits_processor:h=null,...f}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await Me(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:g}=await Me(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){const{audio_features:g}=await Me(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Kt(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:u,logits_processor:h},!0)}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return vs({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 $m({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},bc=class extends P{},EA=class extends bc{},CA=class extends bc{},Mc=class extends P{},SA=class extends Mc{},AA=class extends Mc{},xc=class extends P{},PA=class extends xc{},FA=class extends xc{},Tc=class extends P{},LA=class extends Tc{},IA=class extends Tc{},kc=class extends P{},OA=class extends kc{},NA=class extends kc{},Ec=class extends P{},DA=class extends Ec{},BA=class extends Ec{},Cc=class extends P{},zA=class extends Cc{},RA=class extends Cc{},Sc=class extends P{},$A=class extends Sc{},GA=class extends Sc{},Ac=class extends P{},VA=class extends Ac{},UA=class extends Ac{},Pc=class extends P{},WA=class extends Pc{},jA=class extends Pc{},ig=class extends P{},qA=class extends ig{},lg=class extends P{},HA=class extends lg{},Fc=class extends P{},QA=class extends Fc{},XA=class extends Fc{},Lc=class extends P{},YA=class extends Lc{},KA=class extends Lc{async _call(e){return new oe(await super._call(e))}},Ar=class extends P{},JA=class extends Ar{},ZA=class extends Ar{async _call(e){return new Yr(await super._call(e))}},eP=class extends Ar{async _call(e){return new oe(await super._call(e))}},tP=class extends Ar{async _call(e){return new qe(await super._call(e))}},rP=class extends P{},nP=class extends Ar{},sP=class extends Ar{async _call(e){return new Yr(await super._call(e))}},aP=class extends Ar{async _call(e){return new oe(await super._call(e))}},Ic=class extends P{},oP=class extends Ic{},iP=class extends Ic{},cg=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},ug=class extends cg{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await Me(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:t})).image_features}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return vs({image_token_id:this.config.image_token_id,...e,image_features:r})}},lP=class extends ug{},Oc=class extends P{},cP=class extends Oc{},uP=class extends Oc{async _call(e){return new oe(await super._call(e))}},Nc=class extends P{},dP=class extends Nc{},hP=class extends Nc{},ja=class extends P{},fP=class extends ja{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=Ft([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:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=n,i.l2norm_text_embeddings=a),r||(i.image_embeddings=s,i.l2norm_image_embeddings=o),i}},dg=class extends ja{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_P=class extends ja{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Dc=class extends P{},pP=class extends Dc{},mP=class extends Dc{},Bc=class extends P{},gP=class extends Bc{},wP=class extends Bc{},zc=class extends P{},vP=class extends zc{},yP=class extends zc{},hg=class extends P{},bP=class extends hg{},fg=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},Oa=class extends fg{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return vs({image_token_id:this.config.image_token_index,...e,image_features:r})}},MP=class extends Oa{},xP=class extends Oa{},Rc=class extends P{},TP=class extends Rc{},kP=class extends Rc{},$c=class extends P{},EP=class extends $c{},CP=class extends $c{},Gc=class extends P{},SP=class extends Gc{},AP=class extends Gc{},Vc=class extends P{},PP=class extends Vc{},FP=class extends Vc{},xs=class extends P{},LP=class extends xs{},IP=class extends xs{},OP=class extends xs{async _call(e){return new oe(await super._call(e))}},NP=class extends xs{},_g=class extends P{},DP=class extends _g{},pg=class extends P{},BP=class extends pg{},mg=class extends je{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]}},gg=class extends P{},zP=class extends gg{async _call(e){return new mg(await super._call(e))}},wg=class extends je{constructor({audio_codes:e}){super(),this.audio_codes=e}},vg=class extends je{constructor({audio_values:e}){super(),this.audio_values=e}},qa=class extends P{constructor(){super(...arguments);M(this,"main_input_name","input_values");M(this,"forward_params",["input_values"])}},RP=class extends qa{async encode(e){return new wg(await Me(this.sessions.encoder_model,e))}async decode(e){return new vg(await Me(this.sessions.decoder_model,e))}},yg=class extends qa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},bg=class extends qa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Uc=class extends P{},$P=class extends Uc{},GP=class extends Uc{},Ts=class extends P{},VP=class extends Ts{},UP=class extends Ts{async _call(e){return new Ye(await super._call(e))}},WP=class extends Ts{async _call(e){return new oe(await super._call(e))}},jP=class extends Ts{async _call(e){return new ut(await super._call(e))}},Wc=class extends P{},qP=class extends Wc{},HP=class extends Wc{},Ha=class extends P{},QP=class extends Ha{},XP=class extends Ha{async _call(e){return new oe(await super._call(e))}},YP=class extends Ha{},Qa=class extends P{},KP=class extends Qa{},JP=class extends Qa{async _call(e){return new oe(await super._call(e))}},ZP=class extends Qa{},Xa=class extends P{},eF=class extends Xa{},tF=class extends Xa{async _call(e){return new oe(await super._call(e))}},rF=class extends Xa{},Ya=class extends P{},nF=class extends Ya{},sF=class extends Ya{async _call(e){return new oe(await super._call(e))}},aF=class extends Ya{},jc=class extends P{},oF=class extends jc{},iF=class extends jc{async _call(e){return new oe(await super._call(e))}},qc=class extends P{},lF=class extends qc{},cF=class extends qc{async _call(e){return new oe(await super._call(e))}},ks=class extends P{},uF=class extends ks{},dF=class extends ks{async _call(e){return new Ye(await super._call(e))}},hF=class extends ks{async _call(e){return new oe(await super._call(e))}},fF=class extends ks{async _call(e){return new qe(await super._call(e))}},Hc=class extends P{},_F=class extends Hc{},pF=class extends Hc{},Qc=class extends P{constructor(){super(...arguments);M(this,"requires_attention_mask",!1);M(this,"main_input_name","input_values");M(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},mF=class extends Qc{},gF=class extends Qc{},In=class extends P{},wF=class extends In{},vF=class extends In{async _call(e){return new Ye(await super._call(e))}},yF=class extends In{async _call(e){return new oe(await super._call(e))}},bF=class extends In{async _call(e){return new qe(await super._call(e))}},MF=class extends In{async _call(e){return new ut(await super._call(e))}},Xc=class extends P{},xF=class extends Xc{},TF=class extends Xc{},Yc=class extends P{},kF=class extends Yc{},EF=class extends Yc{},Mg=class extends P{},CF=class extends Mg{constructor(...t){super(...t);M(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 n;if(r==="text"||!t.past_key_values){const l=this.sessions.prepare_inputs_embeds,u=mt(t,l.inputNames);n=await Me(l,u)}else{const l=this.sessions.gen_img_embeds,u=mt({image_ids:t.input_ids},l.inputNames);n=await Me(l,u)}const s={...t,...n},a=await Kt(this,s),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);const i=await Me(o,mt(a,o.inputNames));return{...n,...a,...i}}prepare_inputs_for_generation(t,r,n){const s=!!r.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(s?r.input_ids=Re([r.input_ids,r.input_ids],0):(r.input_ids=Re([r.input_ids,Zi(r.input_ids,BigInt(n.pad_token_id))],0),r.attention_mask=Re([r.attention_mask,Zi(r.attention_mask,0n)],0))),(s||!r.pixel_values)&&(r.pixel_values=ct([0,0,3,384,384],1)),s&&(r.images_seq_mask=new j("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new j("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],s=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await Me(a,{generated_tokens:s}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(const u of i){const h=_s.fromTensor(u);l.push(h)}return l}},Kc=class extends P{},SF=class extends Kc{},AF=class extends Kc{},xg=class extends P{constructor(){super(...arguments);M(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,n]=t.dims,s=this.config.decoder.num_codebooks,a=n-s;let o=0;for(let u=0;u0&&_<=a&&(t.data[o++]=t.data[u])}const i=Math.floor(r/s),l=o/(i*s);return new j(t.type,t.data.slice(0,o),[i,s,l])}prepare_inputs_for_generation(t,r,n){const s=BigInt(this.config.decoder.pad_token_id);let a=structuredClone(t);for(let o=0;o=i&&(a[o][i]=s);return n.guidance_scale!==null&&n.guidance_scale>1&&(a=a.concat(a)),Ia(this,a,r)}async generate(t){const r=await super.generate(t),n=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:s}=await Me(this.sessions.encodec_decode,{audio_codes:n});return s}},Jc=class extends P{},PF=class extends Jc{},FF=class extends Jc{},On=class extends P{},LF=class extends On{},IF=class extends On{async _call(e){return new Ye(await super._call(e))}},OF=class extends On{async _call(e){return new oe(await super._call(e))}},NF=class extends On{async _call(e){return new qe(await super._call(e))}},DF=class extends On{async _call(e){return new ut(await super._call(e))}},Tg=class extends P{},BF=class extends Tg{},Zc=class extends P{},zF=class extends Zc{},RF=class extends Zc{},eu=class extends P{},$F=class extends eu{},GF=class extends eu{},tu=class extends P{},VF=class extends tu{},UF=class extends tu{},ru=class extends P{},WF=class extends ru{},jF=class extends ru{},nu=class extends P{},qF=class extends nu{},HF=class extends nu{},su=class extends P{},QF=class extends su{},XF=class extends su{},au=class extends P{},YF=class extends au{},KF=class extends au{},ou=class extends P{},JF=class extends ou{},ZF=class extends ou{},kg=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},eL=class extends kg{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return vs({image_token_id:this.config.image_token_index,...e,image_features:r})}},Eg=class extends P{},tL=class extends Eg{async _call(e){return new Yr(await super._call(e))}},iu=class extends P{},rL=class extends iu{},nL=class extends iu{},lu=class extends P{},sL=class extends lu{},aL=class extends lu{},cu=class extends P{},oL=class extends cu{},iL=class extends cu{},uu=class extends P{},lL=class extends uu{},cL=class extends uu{},Cg=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},Sg=class extends Cg{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...u}){if(!a){let f;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:f}=await Me(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const _=this.config.normalized_config.hidden_size;f=new j("float32",[],[0,_])}({inputs_embeds:a}=await Me(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:f}))}return await Kt(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l},!1)}},du=class extends P{},uL=class extends du{},dL=class extends du{async _call(e){return new oe(await super._call(e))}},hu=class extends P{},hL=class extends hu{},fL=class extends hu{async _call(e){return new qe(await super._call(e))}},fu=class extends P{},_L=class extends fu{},pL=class extends fu{},_u=class extends P{},mL=class extends _u{},gL=class extends _u{},Ag=class extends P{constructor(){super(...arguments);M(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},Pg=class extends Ag{constructor(){super(...arguments);M(this,"image_grid_thw_name","grid_thw")}get_rope_index(t,r,n,s){const{vision_config:a,image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,u=a.spatial_merge_size??2,h=[];if(r||n){let f=t.tolist();s||(s=Wp(t));const _=s.tolist(),g=Array.from({length:3},E=>Array.from({length:t.dims[0]},C=>Array.from({length:t.dims[1]},F=>1))),w=r?r.tolist():[],v=n?n.tolist():[];let b=0,k=0;for(let E=0;E_[E][S]==1),O=C.reduce((I,S,z)=>(S==l&&I.push(z),I),[]).map(I=>C[I+1]),G=O.filter(I=>I==o).length,T=O.filter(I=>I==i).length;let V=[],R=0,U=G,Z=T;for(let I=0;Iet>R&&Ve==o),z=C.findIndex((Ve,et)=>et>R&&Ve==i),re=U>0&&S!==-1?S:C.length+1,X=Z>0&&z!==-1?z:C.length+1;let pe,ue,Pe,Ke;re0?We(V.at(-1))[0]+1:0;V.push(Array.from({length:3*De},(Ve,et)=>He+et%De));const me=De+He,te=st*at*Je,ke=Array.from({length:te},(Ve,et)=>me+Math.floor(et/(at*Je))),Ze=Array.from({length:te},(Ve,et)=>me+Math.floor(et/Je)%at),Et=Array.from({length:te},(Ve,et)=>me+et%Je);V.push([ke,Ze,Et].flat()),R=pe+te}if(R0?We(V.at(-1))[0]+1:0,S=C.length-R;V.push(Array.from({length:3*S},(z,re)=>I+re%S))}const H=V.reduce((I,S)=>I+S.length,0),D=new Array(H);let N=0;for(let I=0;I<3;++I)for(let S=0;Sf[b%f.length]),w=Array.from({length:_[0]},(v,b)=>We(f.subarray(_[1]*b,_[1]*(b+1)))[0]+1n+BigInt(_[1]));return[new j("int64",g,[3,..._]),new j("int64",w,[w.length,1])]}else{const[f,_]=t.dims,g=BigInt64Array.from({length:3*f*_},(w,v)=>BigInt(Math.floor(v%_/f)));return[new j("int64",g,[3,...t.dims]),jp([f,1])]}}async encode_image({pixel_values:t,image_grid_thw:r}){return(await Me(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return vs({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,n){if(r.attention_mask&&!r.position_ids)if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;const s=ps(r.past_key_values);if(sa+i);r.position_ids=kn([o,o,o],0)}}return r}},Fg=class extends Pg{constructor(){super(...arguments);M(this,"image_grid_thw_name","image_grid_thw")}},pu=class extends P{},wL=class extends pu{},vL=class extends pu{},mu=class extends P{},yL=class extends mu{},bL=class extends mu{},gu=class extends P{},ML=class extends gu{},xL=class extends gu{},wu=class extends Fg{},TL=class extends wu{},Lg=class extends wu{},kL=class extends Lg{},vu=class extends P{},EL=class extends vu{},CL=class extends vu{async _call(e){return new oe(await super._call(e))}},yu=class extends P{},SL=class extends yu{},AL=class extends yu{async _call(e){return new Ig(await super._call(e))}},Ig=class extends bs{},Nn=class extends P{},PL=class extends Nn{},FL=class extends Nn{async _call(e){return new Ye(await super._call(e))}},LL=class extends Nn{async _call(e){return new oe(await super._call(e))}},IL=class extends Nn{async _call(e){return new qe(await super._call(e))}},OL=class extends Nn{async _call(e){return new ut(await super._call(e))}},Dn=class extends P{},NL=class extends Dn{},DL=class extends Dn{async _call(e){return new Ye(await super._call(e))}},BL=class extends Dn{async _call(e){return new oe(await super._call(e))}},zL=class extends Dn{async _call(e){return new qe(await super._call(e))}},RL=class extends Dn{async _call(e){return new ut(await super._call(e))}},bu=class extends P{},$L=class extends bu{},GL=class extends bu{async _call(e){return new Og(await super._call(e))}},Og=class extends bs{},Ng=class extends je{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Dg=class extends P{},VL=class extends Dg{async get_image_embeddings({pixel_values:e}){return await kr(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=Ft(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 Me(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new Ng(await super._call(e))}},Bg=class extends je{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}},zg=class extends P{},Mu=class extends zg{async get_image_embeddings({pixel_values:e}){return await kr(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=Ft(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 n=this.sessions.prompt_encoder_mask_decoder,s=mt(e,n.inputNames);return await Me(n,s)}async _call(e){return new Bg(await super._call(e))}},UL=class extends Mu{},WL=class extends Mu{},Ka=class extends P{},jL=class extends Ka{},qL=class extends Ka{},HL=class extends Ka{},Ja=class extends P{},QL=class extends Ja{},XL=class extends Ja{},YL=class extends Ja{},xu=class extends P{},KL=class extends xu{},Rg=class extends xu{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},JL=class extends Kr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Tu=class extends P{},ZL=class extends Tu{},eI=class extends Tu{},Za=class extends P{constructor(){super(...arguments);M(this,"main_input_name","input_values");M(this,"forward_params",["input_values"])}},tI=class extends Za{async encode(e){return await Me(this.sessions.encoder_model,e)}async decode(e){return await Me(this.sessions.decoder_model,e)}},$g=class extends Za{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Gg=class extends Za{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},eo=class extends P{},rI=class extends eo{},nI=class extends eo{},sI=class extends eo{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await kr(this,o),u=i.dims[1]/this.config.reduction_factor,h=Math.floor(u*s),f=Math.floor(u*n),_=this.config.num_mel_bins;let g=[],w=null,v=null,b=0;for(;;){++b;const C=Dm(!!v);let F;v?F=v.output_sequence_out:F=new j("float32",new Float32Array(_),[1,1,_]);let O={use_cache_branch:C,output_sequence:F,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};this.addPastKeyValues(O,w),v=await Me(this.sessions.decoder_model_merged,O),w=this.getPastKeyValues(v,w);const{prob:G,spectrum:T}=v;if(g.push(T),b>=f&&(Array.from(G.data).filter(V=>V>=r).length>0||b>=h))break}const k=Re(g),{waveform:E}=await Me(a.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:E}}},aI=class extends P{constructor(){super(...arguments);M(this,"main_input_name","spectrogram")}},Es=class extends P{},oI=class extends Es{},iI=class extends Es{async _call(e){return new Ye(await super._call(e))}},lI=class extends Es{async _call(e){return new oe(await super._call(e))}},cI=class extends Es{async _call(e){return new ut(await super._call(e))}},ku=class extends P{},uI=class extends ku{},dI=class extends ku{},Eu=class extends P{},hI=class extends Eu{},fI=class extends Eu{},Vg=class extends P{},_I=class extends Vg{},Ug=class extends P{},Wg=class extends Ug{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:n=5,speed:s=1.05}){const{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:u,durations:h}=await Me(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),f=h.div(s).mul_(a),_=i*o,g=f.data,w=Int32Array.from(g,R=>Math.ceil(R/_)),v=Math.max(...w),b=e.dims[0],k=new BigInt64Array(b*v);for(let R=0;R=v){const b=g.logits,k=b.data,E=b.dims[b.dims.length-1],C=b.dims.length===3?(b.dims[1]-1)*E:0;for(let F=0;F`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(r||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(ge.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(s=>s!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,...s}){t=this._prepare_generation_config(t,s);const a=s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new rl),r.push(new H2(t,a))),t.begin_suppress_tokens&&(r??(r=new rl),r.push(new Im(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"&&ge.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames)),o}_extract_token_timestamps(e,t,r=null,n=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&ge.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let s=this.config.median_filter_width;s===void 0&&(ge.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);const a=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(w,v)=>Re(a.map(b=>b[v]),2)),i=kn(t.map(([w,v])=>{if(w>=o.length)throw new Error(`Layer index ${w} is out of bounds for cross attentions (length ${o.length}).`);return r?o[w].slice(null,v,null,[0,r]):o[w].slice(null,v)})).transpose(1,0,2,3),[l,u]=IT(i,-2,0,!0),h=i.clone();for(let w=0;wb[G+1]-b[G]),C=Dt([1],E).map(O=>!!O),F=[];for(let O=0;Oe[0])),M(da,"BASE_IF_FAIL",!0);var pi;pi=class extends Ce{},M(pi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]);var mi;mi=class extends Ce{},M(mi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]);var gi;gi=class extends Ce{},M(gi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]);var wi;wi=class extends Ce{},M(wi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]);var vi;vi=class extends Ce{},M(vi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]);var yi;yi=class extends Ce{},M(yi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]);var bi;bi=class extends Ce{},M(bi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]);var Mi;Mi=class extends Ce{},M(Mi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_MASKED_LM_MAPPING_NAMES]);var xi;xi=class extends Ce{},M(xi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]);var Ti;Ti=class extends Ce{},M(Ti,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]);var ki;ki=class extends Ce{},M(ki,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]);var Ei;Ei=class extends Ce{},M(Ei,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]);var Ci;Ci=class extends Ce{},M(Ci,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]);var Si;Si=class extends Ce{},M(Si,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]);var Ai;Ai=class extends Ce{},M(Ai,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]);var Pi;Pi=class extends Ce{},M(Pi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]);var Fi;Fi=class extends Ce{},M(Fi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);var Li;Li=class extends Ce{},M(Li,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_CTC_MAPPING_NAMES]);var Ii;Ii=class extends Ce{},M(Ii,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]);var Oi;Oi=class extends Ce{},M(Oi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]);var Ni;Ni=class extends Ce{},M(Ni,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);var Di;Di=class extends Ce{},M(Di,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]);var Bi;Bi=class extends Ce{},M(Bi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);var zi;zi=class extends Ce{},M(zi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]);var Ri;Ri=class extends Ce{},M(Ri,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]);var $i;$i=class extends Ce{},M($i,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]);var Gi;Gi=class extends Ce{},M(Gi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]);var Vi;Vi=class extends Ce{},M(Vi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]);var Ui;Ui=class extends Ce{},M(Ui,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]);var Wi;Wi=class extends Ce{},M(Wi,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]);var AO=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,PO=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},u_=_e.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),FO=class extends PO{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,skip_special_tokens:s=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??u_,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:s,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){var a;if(e.length>1)throw Error("TextStreamer only supports batch size of 1");const t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const r=e[0];if((a=this.token_callback_function)==null||a.call(this,r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){const l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}const o=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(o,!1);return}this.token_cache=Dt(this.token_cache,r);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let s;t||n.endsWith(`
+`)?(s=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&AO(n.charCodeAt(n.length-1))?(s=n.slice(this.print_len),this.print_len+=s.length):(s=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=s.length),this.on_finalized_text(s,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){var r,n;e.length>0&&((r=this.callback_function)==null||r.call(this,e)),t&&this.callback_function===u_&&_e.IS_PROCESS_AVAILABLE&&((n=this.callback_function)==null||n.call(this,`
+`))}};const d_="onnx-community/Voxtral-Mini-4B-Realtime-2602-ONNX",LO=32n,IO=.015,OO=700,NO=400,Dw=16e3,gt=e=>document.getElementById(e),Du=gt("micBtn"),DO=gt("status"),ui=gt("transcript"),BO=gt("transcriptCard"),zO=gt("timing"),Bw=gt("progressBar"),zw=gt("progressFill"),ma=gt("loadStatus"),RO=gt("loadSection"),h_=gt("loadBtn"),$O=gt("activeUI"),lr=gt("waveCanvas"),rt=lr.getContext("2d");let Rw=null,sl=null,br=null,hs=null,cr=null,Gr=null,ga=null,vn=!1,wa=!1,yr=[],Vr=!1,dn=0,f_=0,di="";function jr(e){DO.textContent=e}function al(e){Bw.classList.add("visible"),zw.style.width=`${Math.round(e)}%`}function __(){Bw.classList.remove("visible"),zw.style.width="0%"}function GO(){lr.width=lr.offsetWidth*devicePixelRatio,lr.height=lr.offsetHeight*devicePixelRatio}function $w(){if(!cr)return;ga=requestAnimationFrame($w);const e=cr.frequencyBinCount,t=new Uint8Array(e);cr.getByteTimeDomainData(t);const r=lr.width,n=lr.height;rt.fillStyle="#1A1008",rt.fillRect(0,0,r,n),rt.lineWidth=2*devicePixelRatio,rt.strokeStyle=Vr?"#4ADE80":vn?"#554830":"#2A2018",rt.beginPath();const s=r/e;let a=0;for(let o=0;om_(r,0,.15)}),ma.textContent="Loading model...",al(15),Rw=await Yg.from_pretrained(d_,{dtype:{audio_encoder:e,embed_tokens:e,decoder_model_merged:e},device:t,progress_callback:r=>m_(r,15,.85)}),__(),RO.style.display="none",$O.style.display="block",BO.style.display="block",GO(),Gw(),jr("Click the mic to start listening")}catch(r){ma.textContent=`Error: ${r.message}`,h_.disabled=!1,__(),console.error(r)}}window.__loadModel=VO;function UO(e){let t=0;for(let r=0;rIO)Vr||(Vr=!0,f_=r,yr=[]),dn=0,yr.push(new Float32Array(e));else if(Vr){if(yr.push(new Float32Array(e)),dn===0)dn=r;else if(r-dn>=OO){if(Vr=!1,r-f_>=NO){const s=jO(yr);yr=[],QO(s)}else yr=[];dn=0}}}function jO(e){const t=e.reduce((s,a)=>s+a.length,0),r=new Float32Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}async function qO(){br=new AudioContext({sampleRate:Dw}),hs=await navigator.mediaDevices.getUserMedia({audio:!0});const e=br.createMediaStreamSource(hs);cr=br.createAnalyser(),cr.fftSize=2048,e.connect(cr),Gr=br.createScriptProcessor(4096,1,1),e.connect(Gr),Gr.connect(br.destination),Gr.onaudioprocess=t=>{vn&&!wa&&WO(t.inputBuffer.getChannelData(0))},vn=!0,Vr=!1,yr=[],dn=0,Du.classList.add("listening"),jr("Listening — speak naturally..."),$w()}function HO(){vn=!1,Vr=!1,yr=[],Du.classList.remove("listening"),ga&&(cancelAnimationFrame(ga),ga=null),Gr&&(Gr.disconnect(),Gr=null),hs&&(hs.getTracks().forEach(e=>e.stop()),hs=null),cr&&(cr.disconnect(),cr=null),br&&(br.close(),br=null),Gw(),jr("Click the mic to start listening")}async function QO(e){if(wa)return;wa=!0;const t=(e.length/Dw).toFixed(1);jr(`Transcribing ${t}s...`);try{const r=performance.now(),n=await sl(null,e);let s="";const a=new FO(sl.tokenizer,{skip_special_tokens:!0,skip_prompt:!0,callback_function:_=>{s+=_,ui.textContent=di+s}}),o=a.put.bind(a);a.put=_=>{if(!(_[0].length===1&&_[0][0]===LO))return o(_)};const i=await Rw.generate({...n,max_new_tokens:512,streamer:a}),l=performance.now();s.trim()&&(ui.classList.remove("placeholder"),di+=s.trim()+" ",ui.textContent=di);const u=i.dims.at(-1)-n.input_ids.dims.at(-1),h=((l-r)/1e3).toFixed(2),f=(u/((l-r)/1e3)).toFixed(1);zO.textContent=`${h}s | ${u} tok | ${f} tok/s`,vn&&jr("Listening — speak naturally...")}catch(r){jr(`Error: ${r.message}`),console.error(r)}finally{wa=!1}}Du.addEventListener("click",async()=>{if(vn)HO();else try{await qO()}catch(e){jr(`Mic error: ${e.message}`)}});