1
0
Fork 0
firefox/toolkit/components/ml/vendor/transformers.js
Daniel Baumann 5e9a113729
Adding upstream version 140.0.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
2025-06-25 09:37:52 +02:00

1 line
No EOL
340 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import*as e from"chrome://global/content/ml/ort.webgpu.mjs";var t={497:()=>{},61:()=>{},836:()=>{},603:()=>{},247:()=>{},645:()=>{}},s={};function n(e){var a=s[e];if(void 0!==a)return a.exports;var r=s[e]={exports:{}};return t[e](r,r.exports,n),r.exports}n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};n.d(a,{Bup:()=>Ww,O0k:()=>$l,MRG:()=>Ol,o57:()=>Bl,iKv:()=>Wi,ELH:()=>Gi,Hi6:()=>qi,G2X:()=>Ri,crd:()=>Ui,UH6:()=>Wn,ptb:()=>$y,EJs:()=>Ua,CMU:()=>ay,fZ7:()=>xw,rKH:()=>gf,m68:()=>Of,Plw:()=>Nf,$z$:()=>Xf,_TZ:()=>Bf,W6E:()=>Mf,QNG:()=>Uf,nuw:()=>Df,JP3:()=>Tf,w0O:()=>Gf,HMe:()=>Vf,vTA:()=>Ff,mvA:()=>Wf,FJW:()=>jf,qCM:()=>Lf,wju:()=>Ef,S9w:()=>Rf,Yd3:()=>zf,UVV:()=>qf,yGT:()=>Af,wrZ:()=>Sf,BRf:()=>xf,jQR:()=>wf,MOY:()=>bf,ZIt:()=>kf,V9g:()=>vf,TUv:()=>yf,xIA:()=>Pf,db0:()=>Cf,$TP:()=>$f,gqD:()=>If,oye:()=>xy,v6I:()=>Na,TWC:()=>Dy,Xh$:()=>Ry,F05:()=>al,MH$:()=>rl,vqx:()=>nl,hbt:()=>sl,hbT:()=>oa,E9I:()=>yo,V11:()=>nx,foZ:()=>mg,Dji:()=>Ou,EKW:()=>Bu,oaf:()=>Lu,bmk:()=>ko,VoY:()=>Eo,MRX:()=>vo,o2t:()=>Mo,rSR:()=>bo,DIv:()=>xo,Ft_:()=>Gn,bQt:()=>fg,tDL:()=>_l,JGb:()=>hl,Hvf:()=>ul,IrO:()=>fl,wZy:()=>ml,Sm3:()=>pl,eUP:()=>za,ZiE:()=>Pa,P3b:()=>Wd,$P2:()=>Gd,dg9:()=>qd,jld:()=>da,fv3:()=>yg,GEs:()=>wg,yaC:()=>oc,GEu:()=>rc,E_G:()=>vc,tUF:()=>kc,FIB:()=>bc,nD4:()=>ic,CAk:()=>lc,u2M:()=>Ca,CCt:()=>cc,N2L:()=>dc,S7g:()=>Yo,wc1:()=>si,h0m:()=>ei,LdY:()=>ti,Aib:()=>Zo,S9m:()=>Qo,kOS:()=>ta,qtL:()=>eg,mp$:()=>tg,SQp:()=>gg,XWm:()=>fc,lHM:()=>mc,PRX:()=>xp,$r3:()=>Hw,qWZ:()=>wp,IVZ:()=>gp,oZ3:()=>yp,ioA:()=>cr,hFk:()=>qc,riX:()=>Rc,bOZ:()=>Uc,F$M:()=>Aa,gGu:()=>_a,uRS:()=>gd,q7U:()=>fd,wYL:()=>md,qt5:()=>Oa,z1x:()=>jo,Vx0:()=>qo,y5s:()=>Uo,y_I:()=>Ro,FSH:()=>Vo,jJ4:()=>Do,fRb:()=>Zn,uku:()=>bg,aN4:()=>Jh,Llt:()=>xg,lf8:()=>Hh,NJd:()=>Xh,OBR:()=>Zh,nII:()=>Qh,$o$:()=>Kh,Wgp:()=>nh,E7x:()=>sh,MzU:()=>th,xCN:()=>Fg,YHO:()=>Ah,ALp:()=>Tg,c$o:()=>Eh,C2_:()=>Mh,ooI:()=>Em,Ex8:()=>km,A_V:()=>Mm,Efq:()=>bm,b5h:()=>Jw,EX5:()=>vm,Weu:()=>xm,xUX:()=>$e,XfN:()=>ri,xNh:()=>li,w4W:()=>oi,_yz:()=>ii,L3d:()=>ai,Zip:()=>ni,pGQ:()=>Jn,Nmr:()=>ui,lr8:()=>pi,Qs9:()=>hi,Ilc:()=>_i,pW7:()=>di,vTy:()=>ci,$Vt:()=>Kn,$MY:()=>em,jWB:()=>Yp,twb:()=>vg,Bl1:()=>dh,oB7:()=>kg,EPI:()=>ch,cXP:()=>lh,Dki:()=>Th,FoX:()=>Ch,bEM:()=>Ky,IgO:()=>Lh,A0R:()=>Ih,w4p:()=>Eg,Fbv:()=>Du,j9c:()=>Vu,fen:()=>Mg,ZM0:()=>Nu,JFO:()=>ju,DDe:()=>$u,HaQ:()=>Uu,LlQ:()=>t_,IeB:()=>e_,s8j:()=>Yh,jzC:()=>a_,gQI:()=>n_,SXK:()=>s_,YVy:()=>xi,uwI:()=>yi,NDb:()=>gi,xpG:()=>wi,yuQ:()=>fi,cpF:()=>mi,i8h:()=>ea,Oaj:()=>Xy,TNE:()=>Cg,KI$:()=>Ag,pHg:()=>Wh,fCQ:()=>Gh,X6D:()=>zp,KkK:()=>Sg,muz:()=>Pp,SIh:()=>Sp,CF0:()=>Xo,gEj:()=>Ko,Nyc:()=>Ho,vh2:()=>Jo,SzV:()=>Wo,SPn:()=>Go,_vb:()=>na,QSM:()=>Xw,qjJ:()=>Ar,nDC:()=>vi,QGw:()=>Mi,iGD:()=>Ei,nD1:()=>ki,pSU:()=>bi,fzV:()=>wa,q9s:()=>sd,Uc1:()=>td,cep:()=>ed,rGP:()=>ce,Hff:()=>fp,$ph:()=>mp,$Ld:()=>pp,nJ5:()=>fa,mvc:()=>yu,vgU:()=>wu,Tk_:()=>gu,e1W:()=>By,fQJ:()=>Sw,YKo:()=>Ty,syV:()=>Ql,IUW:()=>Kl,jIC:()=>bw,zMO:()=>er,uB5:()=>tr,qJs:()=>Pg,j2j:()=>qh,jt4:()=>Rh,vdi:()=>Uh,Cb2:()=>Ac,FuQ:()=>Ec,PBg:()=>Mc,pK1:()=>ra,Shx:()=>jc,SX4:()=>Vc,adp:()=>Dc,Xvs:()=>Nc,l2J:()=>$c,DbD:()=>Oc,j7p:()=>zc,XBq:()=>Pc,tAq:()=>Sc,bFh:()=>Bc,PV9:()=>Lc,FqW:()=>Ic,pw$:()=>ga,R0r:()=>vd,zJu:()=>kd,vlr:()=>bd,CIG:()=>Ad,AhC:()=>Ed,yyL:()=>Md,xJk:()=>xd,bKx:()=>yd,d56:()=>wd,VBL:()=>xa,UyU:()=>Yc,y71:()=>Zc,UkL:()=>Qc,uFN:()=>pd,okz:()=>_d,G$U:()=>hd,GLc:()=>ba,pSS:()=>o_,BQD:()=>zg,Vx1:()=>r_,O5n:()=>vw,kjR:()=>fu,UDe:()=>mu,Ed4:()=>Kc,mOb:()=>Jc,Ynb:()=>Hc,Kwv:()=>Qn,EVN:()=>_h,bRn:()=>hh,xCl:()=>uh,qQb:()=>G_,vnq:()=>W_,gqe:()=>q_,oO_:()=>R_,OPC:()=>au,Vvo:()=>nu,vi3:()=>su,Yiu:()=>tc,ePJ:()=>Ig,q56:()=>ec,d7u:()=>Ew,O0q:()=>jy,phI:()=>Oy,G_t:()=>pg,Vkl:()=>sg,CfF:()=>pg,I07:()=>Uy,GXe:()=>Jy,aJl:()=>Vy,dYU:()=>Cr,cw6:()=>Fc,VYv:()=>Tc,n3o:()=>Cc,WoL:()=>Bg,kn$:()=>wc,_i4:()=>gc,Fex:()=>Cw,tCA:()=>yc,g1K:()=>xc,AEy:()=>jl,jWM:()=>Xc,X0l:()=>Wc,RvM:()=>Gc,Hiq:()=>ha,K5U:()=>Xl,k5w:()=>Hl,c$b:()=>Og,ehA:()=>Wl,fim:()=>Qa,VT2:()=>Ya,yMg:()=>Za,LqK:()=>Zi,Rcj:()=>Qi,tm_:()=>Ki,VT:()=>y_,HT0:()=>w_,bZR:()=>g_,HfH:()=>Ma,$ow:()=>la,YZs:()=>dl,UNt:()=>ll,Pgx:()=>cl,Mt5:()=>il,YR3:()=>ol,cj6:()=>ia,QRP:()=>Ii,OOL:()=>Oi,xfe:()=>Li,zml:()=>Bi,C_m:()=>zi,Mjg:()=>Pi,IvO:()=>ma,kPE:()=>tl,KcC:()=>el,wXv:()=>Yi,FmT:()=>f_,W7k:()=>m_,U_I:()=>p_,OFW:()=>Fa,Hw7:()=>Dg,y1Z:()=>Ng,qph:()=>jh,FDZ:()=>$g,Hb:()=>Vh,T1J:()=>Dh,YqH:()=>Zf,_MQ:()=>Er,nj2:()=>Oh,$g1:()=>Bh,BK1:()=>Nh,nIe:()=>$h,hB$:()=>rm,mPV:()=>nm,b4i:()=>am,S37:()=>Fw,PWE:()=>$a,W0U:()=>ym,sG8:()=>fm,Oul:()=>wm,YCy:()=>mm,yZM:()=>gm,erL:()=>pm,pe4:()=>or,z_R:()=>ir,uA4:()=>dp,uKS:()=>cp,eQ7:()=>lp,vZB:()=>Ti,NlK:()=>Si,CBj:()=>Fi,J_N:()=>Ci,t8g:()=>Ai,jTN:()=>Xn,V7I:()=>rd,Jfh:()=>ad,Bz$:()=>nd,DN9:()=>jg,jgy:()=>Dp,M3c:()=>Vp,K66:()=>Vg,mKg:()=>Np,k1H:()=>$p,Uvp:()=>Rg,sIn:()=>Rp,pDc:()=>qp,Xxh:()=>Ug,Bls:()=>Up,TCq:()=>jp,jeS:()=>Gg,F6T:()=>Xp,aJ7:()=>Hp,Y0u:()=>qg,CJY:()=>Wp,kYJ:()=>Gp,g4F:()=>Xg,MHq:()=>Qp,rz8:()=>Zp,N5j:()=>Wg,rbM:()=>Kp,ZKw:()=>Jp,yiA:()=>Jg,qBz:()=>Mu,LFe:()=>Hg,Z9R:()=>vu,pBZ:()=>ku,IWp:()=>Cu,F75:()=>Au,hNN:()=>Eu,lX9:()=>wo,_Bh:()=>To,JE9:()=>Fo,t68:()=>So,S5F:()=>Co,wAB:()=>Ao,$Tv:()=>Jl,vZ9:()=>Kw,s7A:()=>ql,mKJ:()=>Rl,Ck8:()=>Ul,lmt:()=>ry,jZx:()=>Jd,rZ_:()=>Hd,zPm:()=>Xd,vMO:()=>sm,Obh:()=>tm,XW6:()=>Bp,jN0:()=>Op,TEh:()=>Lp,lPY:()=>Ip,ORI:()=>va,SPc:()=>lr,Y8J:()=>ar,Paj:()=>zo,Tc6:()=>Po,wfL:()=>Kg,EVf:()=>La,zEN:()=>Zd,LGm:()=>Qd,VD9:()=>Kd,Xuy:()=>Gy,Fip:()=>ud,FW1:()=>dd,FgJ:()=>cd,ZVw:()=>ld,vqf:()=>id,zgG:()=>od,a86:()=>Fd,A3P:()=>Td,knH:()=>Cd,GZ7:()=>Zg,$Mx:()=>Su,jCl:()=>Qg,jlM:()=>Fu,tU7:()=>Tu,k1d:()=>oy,oKc:()=>Iu,Uys:()=>Yg,MYn:()=>zu,WJS:()=>Pu,lAn:()=>Yl,ZNn:()=>Zl,_XV:()=>uy,$hY:()=>um,e3g:()=>dm,git:()=>cm,wcw:()=>lm,vN5:()=>im,nPB:()=>om,KzV:()=>Rd,izm:()=>Ud,Gzn:()=>jd,CR8:()=>ac,YEl:()=>rw,Ghe:()=>nc,ZnA:()=>cy,VkI:()=>Vd,L1Z:()=>Dd,jbx:()=>Nd,$Un:()=>My,Y2A:()=>go,_dY:()=>qn,Tyd:()=>ja,aLA:()=>Sm,Jlf:()=>ag,pgF:()=>cu,A0H:()=>ow,U0l:()=>lu,guh:()=>iu,tjD:()=>Qw,XyO:()=>C_,yD1:()=>A_,SJu:()=>E_,NXG:()=>hy,hf2:()=>Yf,DK6:()=>Cy,V2z:()=>zd,jZD:()=>Pd,f7H:()=>Sd,XNj:()=>ya,lyK:()=>$d,bHs:()=>iw,d52:()=>Od,mdL:()=>_y,yWo:()=>Bd,oXw:()=>Ld,u2I:()=>Id,p$Q:()=>Yu,D9b:()=>Zu,T2J:()=>eh,FS1:()=>Qu,xIZ:()=>Gu,h6w:()=>lw,zcr:()=>qu,Tl7:()=>Wu,RZG:()=>Ru,Vsd:()=>Ju,Lub:()=>Hu,lAo:()=>Ku,t7I:()=>Xu,REm:()=>Gw,YOx:()=>br,MNq:()=>tx,vts:()=>ex,hKP:()=>rr,Giz:()=>fh,d8n:()=>mh,fl$:()=>ph,sns:()=>Bo,eu8:()=>No,Xi0:()=>Oo,Xsl:()=>$o,Ilk:()=>Lo,Ccq:()=>Io,yQp:()=>Yn,bpB:()=>yl,Vnd:()=>kl,MgS:()=>xl,sbd:()=>bl,tKX:()=>wl,RIx:()=>gl,Bi5:()=>ca,FlD:()=>cw,G3L:()=>__,fX1:()=>h_,Xrw:()=>u_,q85:()=>py,DJ0:()=>Ph,DVM:()=>zh,rQe:()=>Sh,rgj:()=>Fh,RBo:()=>Zw,HLV:()=>uw,dBN:()=>Ep,YjU:()=>Ap,SsB:()=>dw,U14:()=>Mp,g$7:()=>vp,dt5:()=>Hf,AVh:()=>Jf,iAJ:()=>hw,gJd:()=>hc,UX7:()=>uc,Z83:()=>_c,wRc:()=>Ta,cR9:()=>pc,MNc:()=>sc,gbg:()=>Ig,zPu:()=>Ew,NIO:()=>Fm,XN3:()=>Tm,OJc:()=>Yw,Z40:()=>Cm,v3L:()=>Am,QiY:()=>ey,Pqo:()=>np,fqH:()=>ap,oJL:()=>rp,FEt:()=>sp,LN6:()=>tp,GqW:()=>my,LvX:()=>Ia,D$4:()=>Di,z45:()=>ji,qvY:()=>Vi,rb:()=>Ni,RWH:()=>$i,T$2:()=>Hn,UaF:()=>Fp,E6D:()=>Tp,I04:()=>Cp,fjb:()=>_p,diq:()=>hp,nR6:()=>up,oZv:()=>vr,EpU:()=>Mr,Dlv:()=>ep,vn6:()=>Y_,sCu:()=>Sy,S3$:()=>sr,Kul:()=>vh,O_r:()=>_w,c93:()=>kh,qcZ:()=>bh,crA:()=>yh,TzE:()=>xh,TrS:()=>wh,VG4:()=>gh,dAU:()=>Ji,j_7:()=>Hi,j6y:()=>Xi,fGD:()=>aa,vf1:()=>oh,Fzc:()=>rh,b9b:()=>ih,xbg:()=>ah,_0v:()=>dr,qYS:()=>Ne,H6X:()=>Fy,EbS:()=>Ey,AOe:()=>Iy,T1P:()=>rx,psK:()=>Hy,iaN:()=>Ay,sKA:()=>Qf,hTz:()=>Rs,COx:()=>hr,HBQ:()=>ur,A4X:()=>ip,SNK:()=>op,OP6:()=>Py,LsV:()=>_m,n_R:()=>hm,cU1:()=>fy,GNt:()=>z_,dp7:()=>I_,IzE:()=>P_,ct5:()=>S_,bGU:()=>N_,WIq:()=>O_,xI8:()=>$_,W5i:()=>B_,UqB:()=>L_,$gq:()=>Aw,VeZ:()=>Lg,wY7:()=>mw,gxi:()=>tu,D_:()=>pw,WFR:()=>uu,w2j:()=>du,IMK:()=>pu,bg1:()=>_u,xrW:()=>hu,h_s:()=>eu,LJl:()=>Yd,qLW:()=>Gl,ZGD:()=>bu,eJU:()=>fw,m1H:()=>xu,GPY:()=>ou,Y_v:()=>gw,uzq:()=>ru,KJ:()=>kp,PyP:()=>ng,Ct0:()=>bp,Kt3:()=>Ba,P_g:()=>j_,cl7:()=>U_,x5Z:()=>V_,fGl:()=>D_,OQ0:()=>Sa,bAw:()=>ty,ltw:()=>M_,aGV:()=>k_,dMI:()=>v_,i3J:()=>b_,YyD:()=>x_,RT2:()=>gy,K_R:()=>wy,AyL:()=>Z_,Xyp:()=>J_,Eh_:()=>K_,ag_:()=>Q_,Pyv:()=>H_,zys:()=>X_,e25:()=>sy,eU0:()=>F_,iYt:()=>T_,VFU:()=>ny,EAC:()=>Vl,aHU:()=>Dl,gSt:()=>Nl,Vf$:()=>yy,pgB:()=>ox,Fg4:()=>nr,I_U:()=>Ea,d7$:()=>Tl,_Dc:()=>Al,cD:()=>Cl,v11:()=>Ml,Pzh:()=>vl,QJ0:()=>Pl,czX:()=>Ll,vGK:()=>zl,pJ8:()=>Il,OK_:()=>Sl,klo:()=>Fl,gN:()=>pa,jN2:()=>sa,GXK:()=>El,Z0G:()=>Kf,nWJ:()=>yw,ajg:()=>c_,WLR:()=>ww,mjH:()=>l_,URg:()=>d_,CbL:()=>i_,vHC:()=>Ny,$3d:()=>Ly,KPo:()=>qy,ZUB:()=>Wy,gEG:()=>he,$qk:()=>Ze,gJr:()=>se,Omf:()=>te,TyF:()=>_e,_K2:()=>E,a2Z:()=>at,ck6:()=>rt,dOS:()=>Va,kvc:()=>Bw,s_v:()=>Lw,GWP:()=>Ve,vZh:()=>je,vdP:()=>Q,WFC:()=>$s,l8C:()=>He,vaw:()=>kr,BW4:()=>sx,CMs:()=>ee,VOO:()=>ne,DDf:()=>Ue,T9B:()=>re,i2o:()=>st,X7P:()=>Xe,jV8:()=>de,Brl:()=>Vw,jkA:()=>ae,SaS:()=>ot,oCF:()=>it,Ny6:()=>De,SXi:()=>Z,TkF:()=>Yy,Jaq:()=>ut,_9M:()=>dt,_2u:()=>zw,z8$:()=>Re,LIG:()=>ue,dik:()=>We,Vs9:()=>Y,OjR:()=>Uw,t$z:()=>Ye,cQR:()=>tt,rfw:()=>qe,E:()=>Rw,Ul9:()=>lt,aFj:()=>ct});var r={};n.r(r),n.d(r,{BeitFeatureExtractor:()=>mg,BitImageProcessor:()=>fg,CLIPFeatureExtractor:()=>yg,CLIPImageProcessor:()=>wg,ChineseCLIPFeatureExtractor:()=>gg,ConvNextFeatureExtractor:()=>bg,ConvNextImageProcessor:()=>xg,DPTFeatureExtractor:()=>Fg,DPTImageProcessor:()=>Tg,DeiTFeatureExtractor:()=>vg,DeiTImageProcessor:()=>kg,DetrFeatureExtractor:()=>Eg,DetrImageProcessor:()=>Mg,DonutFeatureExtractor:()=>Cg,DonutImageProcessor:()=>Ag,EfficientNetImageProcessor:()=>Sg,GLPNFeatureExtractor:()=>Pg,GroundingDinoImageProcessor:()=>zg,Idefics3ImageProcessor:()=>Ig,JinaCLIPImageProcessor:()=>Bg,LlavaOnevisionImageProcessor:()=>Og,Mask2FormerImageProcessor:()=>Dg,MaskFormerFeatureExtractor:()=>Ng,MaskFormerImageProcessor:()=>$g,MobileNetV1FeatureExtractor:()=>jg,MobileNetV1ImageProcessor:()=>Vg,MobileNetV2FeatureExtractor:()=>Rg,MobileNetV2ImageProcessor:()=>Ug,MobileNetV3FeatureExtractor:()=>Gg,MobileNetV3ImageProcessor:()=>qg,MobileNetV4FeatureExtractor:()=>Xg,MobileNetV4ImageProcessor:()=>Wg,MobileViTFeatureExtractor:()=>Jg,MobileViTImageProcessor:()=>Hg,NougatImageProcessor:()=>Kg,OwlViTFeatureExtractor:()=>Zg,OwlViTImageProcessor:()=>Qg,Owlv2ImageProcessor:()=>Yg,Phi3VImageProcessor:()=>rw,PvtImageProcessor:()=>ow,Qwen2VLImageProcessor:()=>iw,RTDetrImageProcessor:()=>lw,SamImageProcessor:()=>cw,SegformerFeatureExtractor:()=>uw,SegformerImageProcessor:()=>dw,SiglipImageProcessor:()=>hw,SmolVLMImageProcessor:()=>Ig,Swin2SRImageProcessor:()=>_w,VLMImageProcessor:()=>Lg,ViTFeatureExtractor:()=>mw,ViTImageProcessor:()=>pw,VitMatteImageProcessor:()=>fw,VitPoseImageProcessor:()=>gw,YolosFeatureExtractor:()=>yw,YolosImageProcessor:()=>ww});var o={};n.r(o),n.d(o,{ASTFeatureExtractor:()=>Ww,ClapFeatureExtractor:()=>Hw,DacFeatureExtractor:()=>Jw,EncodecFeatureExtractor:()=>Xw,ImageFeatureExtractor:()=>pg,MoonshineFeatureExtractor:()=>Kw,PyAnnoteFeatureExtractor:()=>Qw,SeamlessM4TFeatureExtractor:()=>Zw,SnacFeatureExtractor:()=>Yw,SpeechT5FeatureExtractor:()=>ey,Wav2Vec2FeatureExtractor:()=>ty,WeSpeakerFeatureExtractor:()=>sy,WhisperFeatureExtractor:()=>ny});var i={};n.r(i),n.d(i,{Florence2Processor:()=>bw,GroundingDinoProcessor:()=>vw,Idefics3Processor:()=>Ew,JinaCLIPProcessor:()=>Cw,MgpstrProcessor:()=>Fw,MoonshineProcessor:()=>ry,OwlViTProcessor:()=>oy,PaliGemmaProcessor:()=>uy,Phi3VProcessor:()=>cy,PyAnnoteProcessor:()=>hy,Qwen2VLProcessor:()=>_y,SamProcessor:()=>py,SmolVLMProcessor:()=>Ew,SpeechT5Processor:()=>my,UltravoxProcessor:()=>fy,VLChatProcessor:()=>Aw,Wav2Vec2Processor:()=>gy,Wav2Vec2ProcessorWithLM:()=>wy,WhisperProcessor:()=>yy});var l=n(603),c=n(247),d=n(645);const u="undefined"!=typeof window&&void 0!==window.document,h="undefined"!=typeof self&&"DedicatedWorkerGlobalScope"===self.constructor?.name,_="undefined"!=typeof self&&"caches"in self,p="undefined"!=typeof navigator&&"gpu"in navigator,m="undefined"!=typeof navigator&&"ml"in navigator,f="undefined"!=typeof process,g=f&&"node"===process?.release?.name,w=!A(l),y=!A(c),x=Object.freeze({IS_BROWSER_ENV:u,IS_WEBWORKER_ENV:h,IS_WEB_CACHE_AVAILABLE:_,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:m,IS_PROCESS_AVAILABLE:f,IS_NODE_ENV:g,IS_FS_AVAILABLE:w,IS_PATH_AVAILABLE:y}),b=w&&y;let k="./";if(b){const e=Object(import.meta).url;e?k=c.dirname(c.dirname(d.fileURLToPath(e))):"undefined"!=typeof __dirname&&(k=c.dirname(__dirname))}const v=b?c.join(k,"/.cache/"):null,M="/models/",E={version:"3.5.1",backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(u||h),localModelPath:b?c.join(k,M):M,useFS:w,useBrowserCache:_,useFSCache:w,cacheDir:v,useCustomCache:!1,customCache:null};function A(e){return 0===Object.keys(e).length}const C=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function T(e,t){e&&e(t)}function F(e){return null==e||-1===e}function S(e){const t=[];let s=e;for(;Array.isArray(s);)t.push(s.length),s=s[0];return t}function P(...e){return Array.prototype.concat.apply([],e)}function z(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t]))))))}function I(e,t){return Math.abs((e+t)%(2*t)-t)}function L(e,t){const s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(s)}function B(e,t){return Object.assign({},...t.map((t=>{if(void 0!==e[t])return{[t]:e[t]}})))}function O(e){let t=0;for(const s of e)++t;return t}function $(e,t){let s=0;for(const n of e)n===t&&++s;return s}var N=n(497),D=n(61);const V=100,j={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class U{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=N.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=N.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();const s=N.createReadStream(e);this.body=new ReadableStream({start(e){s.on("data",(t=>e.enqueue(t))),s.on("end",(()=>e.close())),s.on("error",(t=>e.error(t)))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",j[e]??"application/octet-stream")}clone(){let e=new U(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await N.promises.readFile(this.filePath)).buffer}async blob(){const e=await N.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await N.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function R(e,t=null,s=null){let n;try{n=new URL(e)}catch(e){return!1}return!(t&&!t.includes(n.protocol))&&!(s&&!s.includes(n.hostname))}const q=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;async function G(e){if(E.useFS&&!R(e,["http:","https:","blob:"]))return new U(e instanceof URL?"file:"===e.protocol?e.pathname:e.toString():e);if("undefined"!=typeof process&&"node"===process?.release?.name){const t=!!process.env?.TESTING_REMOTELY,s=E.version,n=new Headers;n.set("User-Agent",`transformers.js/${s}; is_ci/${t};`);if(R(e,["http:","https:"],["huggingface.co","hf.co"])){const e=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;e&&n.set("Authorization",`Bearer ${e}`)}return fetch(e,{headers:n})}return fetch(e)}const W={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"};class X{constructor(e){this.path=e}async match(e){let t=D.join(this.path,e),s=new U(t);return s.exists?s:void 0}async put(e,t,s=void 0){let n=D.join(this.path,e);try{const e=t.headers.get("Content-Length"),a=parseInt(e??"0");let r=0;await N.promises.mkdir(D.dirname(n),{recursive:!0});const o=N.createWriteStream(n),i=t.body.getReader();for(;;){const{done:e,value:t}=await i.read();if(e)break;await new Promise(((e,s)=>{o.write(t,(t=>{t?s(t):e()}))})),r+=t.length;const n=a?r/a*100:0;s?.({progress:n,loaded:r,total:a})}o.close()}catch(e){try{await N.promises.unlink(n)}catch{}throw e}}}async function H(e,t,s=!0,n={},a=!1){if(!E.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(!E.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let r;if(T(n.progress_callback,{status:"initiate",name:e,file:t}),!r&&E.useCustomCache){if(!E.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!E.customCache.match||!E.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");r=E.customCache}if(!r&&E.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{r=await caches.open("transformers-cache")}catch(e){console.warn("An error occurred while opening the browser cache:",e)}}if(!r&&E.useFSCache){if(!x.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");r=new X(n.cache_dir??E.cacheDir)}const o=n.revision??"main",i=K(e,t),l=(c=e,!(!q.test(c)||c.includes("..")||c.includes("--")||c.endsWith(".git")||c.endsWith(".ipynb")));var c;const d=l?K(E.localModelPath,i):i,u=K(E.remoteHost,E.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(o)),t);let h;const _=r instanceof X?"main"===o?i:K(e,o,t):u;let p,m=!1;r&&(p=await async function(e,...t){for(let s of t)try{let t=await e.match(s);if(t)return t}catch(e){continue}}(r,d,_));const f=void 0!==p;if(void 0===p){if(E.allowLocalModels){if(R(i,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${i}.`);if(!E.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${i}.`)}else try{p=await G(d),h=d}catch(e){console.warn(`Unable to load from local path "${d}": "${e}"`)}}if(void 0===p||404===p.status){if(n.local_files_only||!E.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${d}".`);return null}if(!l)throw Error(`Local file missing at "${d}" and download aborted due to invalid model ID "${e}".`);if(p=await G(u),200!==p.status)return function(e,t,s){if(!s)return null;const n=W[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}(p.status,u,s);h=_}m=r&&"undefined"!=typeof Response&&p instanceof Response&&200===p.status}let g;if(T(n.progress_callback,{status:"download",name:e,file:t}),!x.IS_NODE_ENV||!a){let s;n.progress_callback?f&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent)?(s=new Uint8Array(await p.arrayBuffer()),T(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:s.length,total:s.length})):s=await async function(e,t){const s=e.headers.get("Content-Length");null===s&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let n=parseInt(s??"0"),a=new Uint8Array(n),r=0;const o=e.body.getReader();async function i(){const{done:e,value:s}=await o.read();if(e)return;const l=r+s.length;if(l>n){n=l;const e=new Uint8Array(n);e.set(a),a=e}a.set(s,r),r=l;return t({progress:r/n*100,loaded:r,total:n}),i()}return await i(),a}(p,(s=>{T(n.progress_callback,{status:"progress",name:e,file:t,...s})})):s=new Uint8Array(await p.arrayBuffer()),g=s}if(m&&h&&void 0===await r.match(h)&&(g?await r.put(h,new Response(g,{headers:p.headers})).catch((e=>{console.warn(`Unable to add response to browser cache: ${e}.`)})):await r.put(h,p,n.progress_callback)),T(n.progress_callback,{status:"done",name:e,file:t}),g){if(!x.IS_NODE_ENV&&a)throw new Error("Cannot return path in a browser environment.");return g}if(p instanceof U)return p.filePath;const w=await(r?.match(h));if(w instanceof U)return w.filePath;if(w instanceof Response)return new Uint8Array(await w.arrayBuffer());if("string"==typeof w)return w;throw new Error("Unable to get model file path or buffer.")}async function J(e,t,s=!0,n={}){const a=await H(e,t,s,n,!1);if(null===a)return{};const r=new TextDecoder("utf-8").decode(a);return JSON.parse(r)}function K(...e){return(e=e.map(((t,s)=>(s&&(t=t.replace(new RegExp("^/"),"")),s!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)))).join("/")}function Q(e,[t,s,n],[a,r],o="bilinear",i=!1){const l=r/n,c=a/s,d=new e.constructor(a*r*t),u=s*n,h=a*r;for(let o=0;o<a;++o)for(let a=0;a<r;++a){const i=o*r+a,_=(a+.5)/l-.5,p=(o+.5)/c-.5;let m=Math.floor(_),f=Math.floor(p);const g=Math.min(m+1,n-1),w=Math.min(f+1,s-1);m=Math.max(m,0),f=Math.max(f,0);const y=_-m,x=p-f,b=(1-y)*(1-x),k=y*(1-x),v=(1-y)*x,M=y*x,E=f*n,A=w*n,C=E+m,T=E+g,F=A+m,S=A+g;for(let s=0;s<t;++s){const t=s*u;d[s*h+i]=b*e[t+C]+k*e[t+T]+v*e[t+F]+M*e[t+S]}}return d}function Z(e,t,s){const n=new Array(s.length),a=new Array(s.length);for(let e=s.length-1,r=1;e>=0;--e)a[e]=r,n[e]=t[s[e]],r*=n[e];const r=s.map(((e,t)=>a[s.indexOf(t)])),o=new e.constructor(e.length);for(let s=0;s<e.length;++s){let n=0;for(let e=t.length-1,a=s;e>=0;--e)n+=a%t[e]*r[e],a=Math.floor(a/t[e]);o[n]=e[s]}return[o,n]}function Y(e){const t=re(e)[0],s=e.map((e=>Math.exp(e-t))),n=s.reduce(((e,t)=>e+t),0);return s.map((e=>e/n))}function ee(e){const t=re(e)[0];let s=0;for(let n=0;n<e.length;++n)s+=Math.exp(e[n]-t);const n=Math.log(s);return e.map((e=>e-t-n))}function te(e,t){let s=0;for(let n=0;n<e.length;++n)s+=e[n]*t[n];return s}function se(e,t){return te(e,t)/(ne(e)*ne(t))}function ne(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}function ae(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],s=n);return[t,s]}function re(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let n=1;n<e.length;++n)e[n]>t&&(t=e[n],s=n);return[t,s]}function oe(e){return e>0&&!(e&e-1)}class ie{constructor(e){if(this.size=0|e,this.size<=1||!oe(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;e<this.table.length;e+=2){const t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){const s=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const s=t||new Array(e.length>>>1);for(let t=0;t<e.length;t+=2)s[t>>>1]=e[t];return s}toComplexArray(e,t){const s=t||this.createComplexArray();for(let t=0;t<s.length;t+=2)s[t]=e[t>>>1],s[t+1]=0;return s}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 t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,s){const n=this._csize;let a,r,o=1<<this._width,i=n/o<<1;const l=this._bitrev;if(4===i)for(a=0,r=0;a<n;a+=i,++r){const s=l[r];this._singleTransform2(t,e,a,s,o)}else for(a=0,r=0;a<n;a+=i,++r){const n=l[r];this._singleTransform4(t,e,a,n,o,s)}const c=this.table;for(o>>=2;o>=2;o>>=2){i=n/o<<1;const t=i>>>2;for(a=0;a<n;a+=i){const n=a+t-1;for(let r=a,i=0;r<n;r+=2,i+=o){const n=r,a=n+t,o=a+t,l=o+t,d=e[n],u=e[n+1],h=e[a],_=e[a+1],p=e[o],m=e[o+1],f=e[l],g=e[l+1],w=c[i],y=s*c[i+1],x=h*w-_*y,b=h*y+_*w,k=c[2*i],v=s*c[2*i+1],M=p*k-m*v,E=p*v+m*k,A=c[3*i],C=s*c[3*i+1],T=f*A-g*C,F=f*C+g*A,S=d+M,P=u+E,z=d-M,I=u-E,L=x+T,B=b+F,O=s*(x-T),$=s*(b-F);e[n]=S+L,e[n+1]=P+B,e[a]=z+$,e[a+1]=I-O,e[o]=S-L,e[o+1]=P-B,e[l]=z-$,e[l+1]=I+O}}}}_singleTransform2(e,t,s,n,a){const r=e[n],o=e[n+1],i=e[n+a],l=e[n+a+1];t[s]=r+i,t[s+1]=o+l,t[s+2]=r-i,t[s+3]=o-l}_singleTransform4(e,t,s,n,a,r){const o=2*a,i=3*a,l=e[n],c=e[n+1],d=e[n+a],u=e[n+a+1],h=e[n+o],_=e[n+o+1],p=e[n+i],m=e[n+i+1],f=l+h,g=c+_,w=l-h,y=c-_,x=d+p,b=u+m,k=r*(d-p),v=r*(u-m);t[s]=f+x,t[s+1]=g+b,t[s+2]=w+v,t[s+3]=y-k,t[s+4]=f-x,t[s+5]=g-b,t[s+6]=w-v,t[s+7]=y+k}_realTransform4(e,t,s){const n=this._csize;let a,r,o=1<<this._width,i=n/o<<1;const l=this._bitrev;if(4===i)for(a=0,r=0;a<n;a+=i,++r){const s=l[r];this._singleRealTransform2(t,e,a,s>>>1,o>>>1)}else for(a=0,r=0;a<n;a+=i,++r){const n=l[r];this._singleRealTransform4(t,e,a,n>>>1,o>>>1,s)}const c=this.table;for(o>>=2;o>=2;o>>=2){i=n/o<<1;const t=i>>>1,r=t>>>1,l=r>>>1;for(a=0;a<n;a+=i)for(let n=0,i=0;n<=l;n+=2,i+=o){const o=a+n,d=o+r,u=d+r,h=u+r,_=e[o],p=e[o+1],m=e[d],f=e[d+1],g=e[u],w=e[u+1],y=e[h],x=e[h+1],b=_,k=p,v=c[i],M=s*c[i+1],E=m*v-f*M,A=m*M+f*v,C=c[2*i],T=s*c[2*i+1],F=g*C-w*T,S=g*T+w*C,P=c[3*i],z=s*c[3*i+1],I=y*P-x*z,L=y*z+x*P,B=b+F,O=k+S,$=b-F,N=k-S,D=E+I,V=A+L,j=s*(E-I),U=s*(A-L);if(e[o]=B+D,e[o+1]=O+V,e[d]=$+U,e[d+1]=N-j,0===n){e[u]=B-D,e[u+1]=O-V;continue}if(n===l)continue;const R=a+r-n,q=a+t-n;e[R]=$-s*U,e[R+1]=-N-s*j,e[q]=B-s*D,e[q+1]=s*V-O}}const d=n>>>1;for(let t=2;t<d;t+=2)e[n-t]=e[t],e[n-t+1]=-e[t+1]}_singleRealTransform2(e,t,s,n,a){const r=e[n],o=e[n+a];t[s]=r+o,t[s+1]=0,t[s+2]=r-o,t[s+3]=0}_singleRealTransform4(e,t,s,n,a,r){const o=2*a,i=3*a,l=e[n],c=e[n+a],d=e[n+o],u=e[n+i],h=l+d,_=l-d,p=c+u,m=r*(c-u);t[s]=h+p,t[s+1]=0,t[s+2]=_,t[s+3]=-m,t[s+4]=h-p,t[s+5]=0,t[s+6]=_,t[s+7]=m}}class le{constructor(e){const t=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=t;const a=new Float64Array(s),r=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let t=0;t<s>>1;++t){const s=(t+1-e)**2/2,n=Math.sqrt(i**2+l**2)**s,o=s*Math.atan2(l,i),c=2*t;a[c]=n*Math.cos(o),a[c+1]=n*Math.sin(o),r[c]=a[c],r[c+1]=-a[c+1]}this._slicedChirpBuffer=a.subarray(t,s),this._f=new ie(n>>1),this._f.transform(this._chirpBuffer,r)}_transform(e,t,s){const n=this._buffer1,a=this._buffer2,r=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(s)for(let e=0;e<l.length;e+=2){const s=e+1,a=t[e>>1];n[e]=a*l[e],n[s]=a*l[s]}else for(let e=0;e<l.length;e+=2){const s=e+1;n[e]=t[e]*l[e]-t[s]*l[s],n[s]=t[e]*l[s]+t[s]*l[e]}this._f.transform(r,n);for(let e=0;e<i.length;e+=2){const t=e+1;a[e]=r[e]*i[e]-r[t]*i[t],a[t]=r[e]*i[t]+r[t]*i[e]}this._f.inverseTransform(o,a);for(let t=0;t<o.length;t+=2){const s=o[t+c],n=o[t+c+1],a=l[t],r=l[t+1];e[t]=s*a-n*r,e[t+1]=s*r+n*a}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}}class ce{constructor(e){this.fft_length=e,this.isPowerOfTwo=oe(e),this.isPowerOfTwo?(this.fft=new ie(e),this.outputBufferSize=2*e):(this.fft=new le(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}}function de(e,t){if(t%2==0||t<=0)throw new Error("Window size must be a positive odd number");const s=new e.constructor(e.length),n=new e.constructor(t),a=Math.floor(t/2);for(let t=0;t<e.length;++t){let r=0;for(let s=-a;s<=a;++s){let a=t+s;a<0?a=Math.abs(a):a>=e.length&&(a=2*(e.length-1)-a),n[r++]=e[a]}n.sort(),s[t]=n[a]}return s}function ue(e,t){const s=Math.pow(10,t);return Math.round(e*s)/s}function he(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function _e(e){const t=e.length,s=e[0].length,n=[t+1,s+1],a=Array.from({length:n[0]},(()=>Array(n[1]).fill(1/0)));a[0][0]=0;const r=Array.from({length:n[0]},(()=>Array(n[1]).fill(-1)));for(let t=1;t<n[1];++t)for(let s=1;s<n[0];++s){const n=a[s-1][t-1],o=a[s-1][t],i=a[s][t-1];let l,c;n<o&&n<i?(l=n,c=0):o<n&&o<i?(l=o,c=1):(l=i,c=2),a[s][t]=e[s-1][t-1]+l,r[s][t]=c}for(let e=0;e<n[1];++e)r[0][e]=2;for(let e=0;e<n[0];++e)r[e][0]=1;let o=t,i=s,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),r[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}const pe=e;new Map;let me="warning";const fe={wasm:{},webgl:{},webgpu:{},versions:{common:"1.21.0"},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);me=e}},get logLevel(){return me}};Object.defineProperty(fe,"logLevel",{enumerable:!0});const ge=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");const{height:s,width:n}=t,a=t.norm??{mean:255,bias:0};let r,o;r="number"==typeof a.mean?[a.mean,a.mean,a.mean,a.mean]:[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],o="number"==typeof a.bias?[a.bias,a.bias,a.bias,a.bias]:[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];const i=void 0!==t.format?t.format:"RGBA",l=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",c=s*n,d="RGBA"===l?new Float32Array(4*c):new Float32Array(3*c);let u=4,h=0,_=1,p=2,m=3,f=0,g=c,w=2*c,y=-1;"RGB"===i&&(u=3,h=0,_=1,p=2,m=-1),"RGBA"===l?y=3*c:"RBG"===l?(f=0,w=c,g=2*c):"BGR"===l&&(w=0,g=c,f=2*c);for(let t=0;t<c;t++,h+=u,p+=u,_+=u,m+=u)d[f++]=(e[h]+o[0])/r[0],d[g++]=(e[_]+o[1])/r[1],d[w++]=(e[p]+o[2])/r[2],-1!==y&&-1!==m&&(d[y++]=(e[m]+o[3])/r[3]);return new be("float32",d,"RGBA"===l?[1,4,s,n]:[1,3,s,n])},we=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let xe=!1;class be{constructor(e,t,s){let n,a;if((()=>{if(!xe){xe=!0;const e="undefined"!=typeof BigInt64Array&&BigInt64Array.from,t="undefined"!=typeof BigUint64Array&&BigUint64Array.from,s=globalThis.Float16Array,n=void 0!==s&&s.from;e&&(we.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(we.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),n?(we.set("float16",s),ye.set(s,"float16")):we.set("float16",Uint16Array)}})(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,n=e.type,a=e.dims,e.location){case"cpu-pinned":{const t=we.get(n);if(!t)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==n)throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==n&&"float16"!==n&&"int32"!==n&&"int64"!==n&&"uint32"!==n&&"uint8"!==n&&"bool"!==n&&"uint4"!==n&&"int4"!==n)throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==n&&"float16"!==n&&"int32"!==n&&"int64"!==n&&"uint32"!==n&&"uint64"!==n&&"int8"!==n&&"uint8"!==n&&"bool"!==n&&"uint4"!==n&&"int4"!==n)throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let r,o;if("string"==typeof e)if(n=e,o=s,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");r=t}else{const s=we.get(e);if(void 0===s)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&s===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);r="uint64"===e||"int64"===e?s.from(t,BigInt):s.from(t)}else if(t instanceof s)r=t;else if(t instanceof Uint8ClampedArray){if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");r=Uint8Array.from(t)}else{if(!("float16"===e&&t instanceof Uint16Array&&s!==Uint16Array))throw new TypeError(`A ${n} tensor's data must be type of ${s}`);r=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(o=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const t=typeof e[0];if("string"===t)n="string",r=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);n="bool",r=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)n="uint8",r=Uint8Array.from(e);else{const t=ye.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=t,r=e}if(void 0===o)o=[r.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");a=o,this.cpuData=r,this.dataLocation="cpu"}const r=(e=>{let t=1;for(let s=0;s<e.length;s++){const n=e[s];if("number"!=typeof n||!Number.isSafeInteger(n))throw new TypeError(`dims[${s}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${n}`);t*=n}return t})(a);if(this.cpuData&&r!==this.cpuData.length&&("uint4"!==n&&"int4"!==n||Math.ceil(r/2)!==this.cpuData.length))throw new Error(`Tensor's size(${r}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=r}static async fromImage(e,t){return(async(e,t)=>{const s="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,n="undefined"!=typeof ImageData&&e instanceof ImageData,a="undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap,r="string"==typeof e;let o,i=t??{};const l=()=>{if("undefined"!=typeof document)return document.createElement("canvas");if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=e=>"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(s){const s=l();s.width=e.width,s.height=e.height;const n=c(s);if(null==n)throw new Error("Can not access image data");{let s=e.height,a=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(s=t.resizedHeight,a=t.resizedWidth),void 0!==t){if(i=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=s,i.width=a}else i.tensorFormat="RGBA",i.height=s,i.width=a;n.drawImage(e,0,0),o=n.getImageData(0,0,a,s).data}}else{if(!n){if(a){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");const s=l();s.width=e.width,s.height=e.height;const n=c(s);if(null!=n){const t=e.height,s=e.width;return n.drawImage(e,0,0,s,t),o=n.getImageData(0,0,s,t).data,i.height=t,i.width=s,ge(o,i)}throw new Error("Can not access image data")}if(r)return new Promise(((t,s)=>{const n=l(),a=c(n);if(!e||!a)return s();const r=new Image;r.crossOrigin="Anonymous",r.src=e,r.onload=()=>{n.width=r.width,n.height=r.height,a.drawImage(r,0,0,n.width,n.height);const e=a.getImageData(0,0,n.width,n.height);i.height=n.height,i.width=n.width,t(ge(e.data,i))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let s,n;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(s=t.resizedHeight,n=t.resizedWidth):(s=e.height,n=e.width),void 0!==t&&(i=t),i.format="RGBA",i.height=s,i.width=n,void 0!==t){const t=l();t.width=n,t.height=s;const a=c(t);if(null==a)throw new Error("Can not access image data");a.putImageData(e,0,0),o=a.getImageData(0,0,n,s).data}else o=e.data}}if(void 0!==o)return ge(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")})(e,t)}static fromTexture(e,t){return((e,t)=>{const{width:s,height:n,download:a,dispose:r}=t;return new be({location:"texture",type:"float32",texture:e,dims:[1,n,s,4],download:a,dispose:r})})(e,t)}static fromGpuBuffer(e,t){return((e,t)=>{const{dataType:s,dims:n,download:a,dispose:r}=t;return new be({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:a,dispose:r})})(e,t)}static fromMLTensor(e,t){return((e,t)=>{const{dataType:s,dims:n,download:a,dispose:r}=t;return new be({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:a,dispose:r})})(e,t)}static fromPinnedBuffer(e,t,s){return((e,t,s)=>new be({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]}))(e,t,s)}toDataURL(e){return((e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];const n=s.getContext("2d");if(null!=n){let a,r;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],r=e.dims[3]):(a=e.dims[3],r=e.dims[2]);const o=void 0!==t?.format?t.format:"RGB",i=t?.norm;let l,c;void 0===i||void 0===i.mean?l=[255,255,255,255]:"number"==typeof i.mean?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],void 0!==i.mean[3]&&(l[3]=i.mean[3])),void 0===i||void 0===i.bias?c=[0,0,0,0]:"number"==typeof i.bias?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],void 0!==i.bias[3]&&(c[3]=i.bias[3]));const d=r*a;let u=0,h=d,_=2*d,p=-1;"RGBA"===o?(u=0,h=d,_=2*d,p=3*d):"RGB"===o?(u=0,h=d,_=2*d):"RBG"===o&&(u=0,_=d,h=2*d);for(let t=0;t<r;t++)for(let s=0;s<a;s++){const a=(e.data[u++]-c[0])*l[0],r=(e.data[h++]-c[1])*l[1],o=(e.data[_++]-c[2])*l[2],i=-1===p?255:(e.data[p++]-c[3])*l[3];n.fillStyle="rgba("+a+","+r+","+o+","+i+")",n.fillRect(s,t,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")})(this,e)}toImageData(e){return((e,t)=>{const s="undefined"!=typeof document?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(null==s)throw new Error("Can not access image data");{let a,r,o;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(a=e.dims[2],r=e.dims[1],o=e.dims[3]):(a=e.dims[3],r=e.dims[2],o=e.dims[1]);const i=void 0!==t&&void 0!==t.format?t.format:"RGB",l=t?.norm;let c,d;void 0===l||void 0===l.mean?c=[255,255,255,255]:"number"==typeof l.mean?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],void 0!==l.mean[3]&&(c[3]=l.mean[3])),void 0===l||void 0===l.bias?d=[0,0,0,0]:"number"==typeof l.bias?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(d[3]=l.bias[3]));const u=r*a;if(void 0!==t&&(void 0!==t.format&&4===o&&"RGBA"!==t.format||3===o&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let _=0,p=1,m=2,f=3,g=0,w=u,y=2*u,x=-1;"RGBA"===i?(g=0,w=u,y=2*u,x=3*u):"RGB"===i?(g=0,w=u,y=2*u):"RBG"===i&&(g=0,y=u,w=2*u),n=s.createImageData(a,r);for(let t=0;t<r*a;_+=h,p+=h,m+=h,f+=h,t++)n.data[_]=(e.data[g++]-d[0])*c[0],n.data[p]=(e.data[w++]-d[1])*c[1],n.data[m]=(e.data[y++]-d[2])*c[2],n.data[f]=-1===x?255:(e.data[x++]-d[3])*c[3]}return n})(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return((e,t)=>{switch(e.location){case"cpu":return new be(e.type,e.data,t);case"cpu-pinned":return new be({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new be({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new be({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new be({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}})(this,e)}}const ke=be;const ve=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),Me=[];let Ee,Ae;const Ce=Symbol.for("onnxruntime");if(Ce in globalThis)Ae=globalThis[Ce],Me.push(...Ae.supportedDevices),Ee=Ae.defaultDevices;else if(x.IS_NODE_ENV){switch(Ae=null.default??null,process.platform){case"win32":Me.push("dml");break;case"linux":"x64"===process.arch&&Me.push("cuda")}Me.push("cpu"),Ee=["cpu"]}else Ae=pe,x.IS_WEBNN_AVAILABLE&&Me.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),x.IS_WEBGPU_AVAILABLE&&Me.push("webgpu"),Me.push("wasm"),Ee=["wasm"];const Te=Ae.InferenceSession;let Fe=null;async function Se(e,t,s){Fe&&await Fe;const n=Te.create(e,t);Fe??=n;const a=await n;return a.config=s,a}function Pe(e){return e instanceof Ae.Tensor}const ze=Ae?.env;function Ie(){return ze?.wasm?.proxy}ze?.wasm&&("undefined"!=typeof ServiceWorkerGlobalScope&&self instanceof ServiceWorkerGlobalScope||ze.wasm.wasmPaths||(ze.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${E.version}/dist/`),ze.wasm.proxy=!1),ze?.webgpu&&(ze.webgpu.powerPreference="high-performance"),E.backends.onnx=ze;const Le=x.IS_BROWSER_ENV||x.IS_WEBWORKER_ENV,Be=async(e,t,s)=>{const n=await Se(new Uint8Array(e),t);let a=Promise.resolve();return async e=>{const t=Ie(),r=Object.fromEntries(Object.entries(e).map((([e,s])=>[e,(t?s.clone():s).ort_tensor]))),o=await(a=Le?a.then((()=>n.run(r))):n.run(r));return Array.isArray(s)?s.map((e=>new Ne(o[e]))):new Ne(o[s])}};class Oe{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Be([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=Be([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=Be([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=Be([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=Be([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=Be([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=Be([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=Be([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}}const $e=Object.freeze({float32:Float32Array,float16:"undefined"!=typeof Float16Array?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class Ne{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){if(Pe(e[0]))this.ort_tensor=e[0];else{const t=Symbol.for("onnxruntime")in globalThis?globalThis.Tensor:ke;this.ort_tensor=new t(e[0],e[1],e[2])}return new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let s=Number(t);if(Number.isInteger(s))return e._getitem(s)}return e[t]},set:(e,t,s)=>e[t]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const s=t.reduce(((e,t)=>e*t));for(let n=0;n<e;++n)yield this._subarray(n,s,t)}else yield*this.data}_getitem(e){const[t,...s]=this.dims;if(e=Qe(e,t),s.length>0){const t=s.reduce(((e,t)=>e*t));return this._subarray(e,t,s)}return new Ne(this.type,[this.data[e]],s)}indexOf(e){const t=this.data;for(let s=0;s<t.length;++s)if(t[s]==e)return s;return-1}_subarray(e,t,s){const n=e*t,a=(e+1)*t,r="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new Ne(this.type,r,s)}item(){const e=this.data;if(1!==e.length)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return function(e,t){const s=e.length,n=t.reduce(((e,t)=>e*t));if(s!==n)throw Error(`cannot reshape array of size ${s} into shape (${t})`);let a=e;for(let e=t.length-1;e>=0;e--)a=a.reduce(((s,n)=>{let a=s[s.length-1];return a.length<t[e]?a.push(n):s.push([n]),s}),[[]]);return a[0]}(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]=e(t[s],s,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){const t=this.data;for(let s=0;s<t.length;++s)t[s]-=e;return this}clone(){return new Ne(this.type,this.data.slice(),this.dims.slice())}slice(...e){const t=[],s=[];for(let n=0;n<this.dims.length;++n){let a=e[n];if(null==a)s.push([0,this.dims[n]]),t.push(this.dims[n]);else if("number"==typeof a)a=Qe(a,this.dims[n],n),s.push([a,a+1]);else{if(!Array.isArray(a)||2!==a.length)throw new Error(`Invalid slice: ${a}`);{let[e,r]=a;if(e=null===e?0:Qe(e,this.dims[n],n,!1),r=null===r?this.dims[n]:Qe(r,this.dims[n],n,!1),e>r)throw new Error(`Invalid slice: ${a}`);const o=[Math.max(e,0),Math.min(r,this.dims[n])];s.push(o),t.push(o[1]-o[0])}}}const n=s.map((([e,t])=>t-e)),a=n.reduce(((e,t)=>e*t)),r=this.data,o=new r.constructor(a),i=this.stride();for(let e=0;e<a;++e){let t=0;for(let a=n.length-1,r=e;a>=0;--a){const e=n[a];t+=(r%e+s[a][0])*i[a],r=Math.floor(r/e)}o[e]=r[t]}return new Ne(this.type,o,t)}permute(...e){return De(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,s=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const n=this.data,a=(t,s)=>t+s**e;if(null===t){const t=n.reduce(a,0)**(1/e);return new Ne(this.type,[t],[])}const[r,o,i]=et(a,this,t,s);if(1!==e)for(let t=0;t<o.length;++t)o[t]=o[t]**(1/e);return new Ne(r,o,i)}normalize_(e=2,t=1){t=Qe(t,this.dims.length);const s=this.norm(e,t,!0),n=this.data,a=s.data;for(let e=0;e<n.length;++e){let s=0;for(let n=this.dims.length-1,a=e,r=1;n>=0;--n){const e=this.dims[n];if(n!==t){s+=a%e*r,r*=this.dims[n]}a=Math.floor(a/e)}n[e]/=a[s]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){const t=new Array(e.length);for(let s=e.length-1,n=1;s>=0;--s)t[s]=n,n*=e[s];return t}(this.dims)}squeeze(e=null){return new Ne(this.type,this.data,Je(this.dims,e))}squeeze_(e=null){return this.dims=Je(this.dims,e),this}unsqueeze(e=null){return new Ne(this.type,this.data,Ke(this.dims,e))}unsqueeze_(e=null){return this.dims=Ke(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,t+1),a=this.dims.slice(t+1);return this.dims=[...s,n.reduce(((e,t)=>e*t),1),...a],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let s=0;s<e.length;++s)if(-1===e[s]){if(-1!==t)throw new Error("Only one dimension can be inferred");t=s}const s=this.data;if(-1!==t){const n=e.reduce(((e,s,n)=>n!==t?e*s:e),1);e[t]=s.length/n}return new Ne(this.type,s,e)}neg_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(e){const t=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)t[n]=s[n]>e?1:0;return new Ne("bool",t,this.dims)}lt(e){const t=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)t[n]=s[n]<e?1:0;return new Ne("bool",t,this.dims)}clamp_(e,t){const s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){const e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return st(this,e,t)}min(e=null,t=!1){if(null===e){const e=ae(this.data)[0];return new Ne(this.type,[e],[])}const[s,n,a]=et(((e,t)=>Math.min(e,t)),this,e,t,1/0);return new Ne(s,n,a)}max(e=null,t=!1){if(null===e){const e=re(this.data)[0];return new Ne(this.type,[e],[])}const[s,n,a]=et(((e,t)=>Math.max(e,t)),this,e,t,-1/0);return new Ne(s,n,a)}argmin(e=null,t=!1){if(null!==e)throw new Error("`dim !== null` not yet implemented.");const s=ae(this.data)[1];return new Ne("int64",[BigInt(s)],[])}argmax(e=null,t=!1){if(null!==e)throw new Error("`dim !== null` not yet implemented.");const s=re(this.data)[1];return new Ne("int64",[BigInt(s)],[])}to(e){if(this.type===e)return this;if(!$e.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let t;const s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);return s&&!n?t=Number:!s&&n&&(t=BigInt),new Ne(e,$e[e].from(this.data,t),this.dims)}}function De(e,t){const[s,n]=Z(e.data,e.dims,t);return new Ne(e.type,s,n)}function Ve(e,[t,s],n="bilinear",a=!1){const r=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1);let l=Q(e.data,[r,o,i],[t,s],n,a);return new Ne(e.type,l,[r,t,s])}async function je(e,{size:t=null,mode:s="bilinear"}={}){if(4!==e.dims.length)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let n,a;if(2===t.length)n=[...e.dims.slice(0,2),...t];else if(3===t.length)n=[e.dims[0],...t];else{if(4!==t.length)throw new Error("`size` must be of length 2, 3, or 4.");n=t}if("nearest"===s)a=await Oe.nearest_interpolate_4d;else if("bilinear"===s)a=await Oe.bilinear_interpolate_4d;else{if("bicubic"!==s)throw new Error(`Unsupported mode: ${s}`);a=await Oe.bicubic_interpolate_4d}const r=new Ne("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await a({x:e,s:r})}async function Ue(e,t){const s=await Oe.matmul;return await s({a:e,b:t})}async function Re(e,t){const s=await Oe.rfft;return await s({x:e,a:t})}async function qe(e,t){const s=await Oe.top_k;return t=null==t?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await s({x:e,k:new Ne("int64",[BigInt(t)],[1])})}const Ge=e=>new Ne("int64",e,[e.length]);async function We(e,t,s,n,a){const r=await Oe.slice;return await r({x:e,s:Ge(t),e:Ge(s),a:Ge(n),t:Ge(a??new Array(n.length).fill(1))})}function Xe(e,t){const s=e.data,n=t.data,a=[e.dims[0],e.dims[2]],r=new s.constructor(a[0]*a[1]),[o,i,l]=e.dims;let c=0;for(let e=0;e<o;++e){const t=e*l*i;for(let a=0;a<l;++a){let o=0,d=0;const u=e*i,h=t+a;for(let e=0;e<i;++e){const t=Number(n[u+e]);d+=t,o+=s[h+e*l]*t}const _=o/d;r[c++]=_}}return new Ne(e.type,r,a)}function He(e,t,{eps:s=1e-5}={}){if(2!==e.dims.length)throw new Error("`layer_norm` currently only supports 2D input.");const[n,a]=e.dims;if(1!==t.length&&t[0]!==a)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[r,o]=tt(e,1,0,!0),i=r.data,l=o.data,c=e.data,d=new c.constructor(c.length);for(let e=0;e<n;++e){const t=e*a;for(let n=0;n<a;++n){const a=t+n;d[a]=(c[a]-l[e])/(i[e]+s)}}return new Ne(e.type,d,e.dims)}function Je(e,t){return e=e.slice(),null===t?e=e.filter((e=>1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,s)=>1!==e||!t.includes(s)))),e}function Ke(e,t){return t=Qe(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function Qe(e,t,s=null,n=!0){if(e<-t||e>=t){if(n)throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===s?"":" "+s} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Ze(e,t=0){t=Qe(t,e[0].dims.length);const s=e[0].dims.slice();s[t]=e.reduce(((e,s)=>e+s.dims[t]),0);const n=s.reduce(((e,t)=>e*t),1),a=new e[0].data.constructor(n),r=e[0].type;if(0===t){let t=0;for(const s of e){const e=s.data;a.set(e,t),t+=e.length}}else{let n=0;for(let r=0;r<e.length;++r){const{data:o,dims:i}=e[r];for(let e=0;e<o.length;++e){let r=0;for(let a=i.length-1,o=e,l=1;a>=0;--a){const e=i[a];let c=o%e;a===t&&(c+=n),r+=c*l,l*=s[a],o=Math.floor(o/e)}a[r]=o[e]}n+=i[t]}}return new Ne(r,a,s)}function Ye(e,t=0){return Ze(e.map((e=>e.unsqueeze(t))),t)}function et(e,t,s=null,n=!1,a=null){const r=t.data,o=t.dims;s=Qe(s,o.length);const i=o.slice();i[s]=1;const l=new r.constructor(r.length/o[s]);null!==a&&l.fill(a);for(let t=0;t<r.length;++t){let n=0;for(let e=o.length-1,a=t,r=1;e>=0;--e){const t=o[e];if(e!==s){n+=a%t*r,r*=i[e]}a=Math.floor(a/t)}l[n]=e(l[n],r[t],t,n)}return n||i.splice(s,1),[t.type,l,i]}function tt(e,t=null,s=1,n=!1){const a=e.data,r=e.dims;if(null===t){const t=a.reduce(((e,t)=>e+t),0)/a.length,n=Math.sqrt(a.reduce(((e,s)=>e+(s-t)**2),0)/(a.length-s)),r=new Ne(e.type,[t],[]);return[new Ne(e.type,[n],[]),r]}const o=st(e,t=Qe(t,r.length),n),i=o.data,[l,c,d]=et(((e,t,s,n)=>e+(t-i[n])**2),e,t,n);for(let e=0;e<c.length;++e)c[e]=Math.sqrt(c[e]/(r[t]-s));return[new Ne(l,c,d),o]}function st(e,t=null,s=!1){const n=e.dims,a=e.data;if(null===t){const t=a.reduce(((e,t)=>e+t),0);return new Ne(e.type,[t/a.length],[])}t=Qe(t,n.length);const[r,o,i]=et(((e,t)=>e+t),e,t,s);if(1!==n[t])for(let e=0;e<o.length;++e)o[e]/=n[t];return new Ne(r,o,i)}function nt(e,t,s,n){const a=e.reduce(((e,t)=>e*t),1);return new Ne(s,new n(a).fill(t),e)}function at(e,t){let s,n;if("number"==typeof t)s="float32",n=Float32Array;else if("bigint"==typeof t)s="int64",n=BigInt64Array;else{if("boolean"!=typeof t)throw new Error("Unsupported data type: "+typeof t);s="bool",n=Uint8Array}return nt(e,t,s,n)}function rt(e,t){return at(e.dims,t)}function ot(e){return nt(e,1n,"int64",BigInt64Array)}function it(e){return ot(e.dims)}function lt(e){return nt(e,0n,"int64",BigInt64Array)}function ct(e){return lt(e.dims)}function dt(e){const t=e.reduce(((e,t)=>e*t),1);return new Ne("float32",Float32Array.from({length:t},(()=>Math.random())),e)}function ut(e,t){if(2!==e.dims.length)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const s="binary"===t,n=s?"int8":"uint8",a=s?Int8Array:Uint8Array,r=e.data,o=new a(r.length/8);for(let e=0;e<r.length;++e){const t=r[e]>0?1:0,n=Math.floor(e/8),a=e%8;o[n]|=t<<7-a,s&&0===a&&(o[n]-=128)}return new Ne(n,o,[e.dims[0],e.dims[1]/8])}class ht{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._maxSize=t}get size(){return this._heap.length}isEmpty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size<this._maxSize)this._heap.push(t),this._siftUp();else{const e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._siftUpFrom(e))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._siftDown(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._siftDown(),t}_parent(e){return(e+1>>>1)-1}_left(e){return 1+(e<<1)}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const s=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=s}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_siftDown(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}}class _t{constructor(){this.root=pt.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const s of e){let e=t.children.get(s);void 0===e&&(e=pt.default(),t.children.set(s,e)),t=e}t.isLeaf=!0}*commonPrefixSearch(e){let t=this.root;if(void 0===t)return;let s="";for(const n of e){if(s+=n,t=t.children.get(n),void 0===t)return;t.isLeaf&&(yield s)}}}class pt{constructor(e,t){this.isLeaf=e,this.children=t}static default(){return new pt(!1,new Map)}}class mt{constructor(e,t,s){this.chars=Array.from(e),this.len=this.chars.length,this.bosTokenId=t,this.eosTokenId=s,this.nodes=[],this.beginNodes=Array.from({length:this.len+1},(()=>[])),this.endNodes=Array.from({length:this.len+1},(()=>[]));const n=new ft(this.bosTokenId,0,0,0,0),a=new ft(this.eosTokenId,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(a.clone()),this.beginNodes[this.len].push(a),this.endNodes[0].push(n)}insert(e,t,s,n){const a=this.nodes.length,r=new ft(n,a,e,t,s);this.beginNodes[e].push(r),this.endNodes[e+t].push(r),this.nodes.push(r)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(0==this.beginNodes[t].length)return[];for(let e of this.beginNodes[t]){e.prev=null;let s=0,n=null;for(let a of this.endNodes[t]){const t=a.backtraceScore+e.score;(null===n||t>s)&&(n=a.clone(),s=t)}if(null===n)return[];e.prev=n,e.backtraceScore=s}++t}const s=[],n=this.beginNodes[e][0].prev;if(null===n)return[];let a=n.clone();for(;null!==a.prev;){s.push(a.clone());const e=a.clone();a=e.prev.clone()}return s.reverse(),s}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map((e=>this.piece(e)))}tokenIds(){return this.viterbi().map((e=>e.tokenId))}}class ft{constructor(e,t,s,n,a){this.tokenId=e,this.nodeId=t,this.pos=s,this.length=n,this.score=a,this.prev=null,this.backtraceScore=0}clone(){const e=new ft(this.tokenId,this.nodeId,this.pos,this.length,this.score);return e.prev=this.prev,e.backtraceScore=this.backtraceScore,e}}class gt{constructor(e){this.trie=this._buildTrie(e)}_buildTrie(e){const t=Object.create(null);for(const s of e){let e=t;for(let t=0;t<s.length;++t)e=e[s[t]]??=Object.create(null);e.end=s}return t}split(e){const t=[],s=e.length;let n=0,a=0;for(;a<s;){let r=this.trie,o=null,i=a;for(;i<s&&(r=r[e[i]]);)r.end&&(o=r.end),++i;o?(a>n&&t.push(e.slice(n,a)),t.push(o),a+=o.length,n=a):++a}return n<s&&t.push(e.slice(n)),t}}class wt{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}var yt=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro",Break:"Break",Continue:"Continue"}),xt=Object.freeze({set:yt.Set,for:yt.For,in:yt.In,is:yt.Is,if:yt.If,else:yt.Else,endset:yt.EndSet,endif:yt.EndIf,elif:yt.ElseIf,endfor:yt.EndFor,and:yt.And,or:yt.Or,not:yt.Not,"not in":yt.NotIn,macro:yt.Macro,endmacro:yt.EndMacro,break:yt.Break,continue:yt.Continue,true:yt.BooleanLiteral,false:yt.BooleanLiteral,none:yt.NullLiteral,True:yt.BooleanLiteral,False:yt.BooleanLiteral,None:yt.NullLiteral}),bt=class{constructor(e,t){this.value=e,this.type=t}};function kt(e){return/\w/.test(e)}function vt(e){return/[0-9]/.test(e)}var Mt=[["{%",yt.OpenStatement],["%}",yt.CloseStatement],["{{",yt.OpenExpression],["}}",yt.CloseExpression],["(",yt.OpenParen],[")",yt.CloseParen],["{",yt.OpenCurlyBracket],["}",yt.CloseCurlyBracket],["[",yt.OpenSquareBracket],["]",yt.CloseSquareBracket],[",",yt.Comma],[".",yt.Dot],[":",yt.Colon],["|",yt.Pipe],["<=",yt.ComparisonBinaryOperator],[">=",yt.ComparisonBinaryOperator],["==",yt.ComparisonBinaryOperator],["!=",yt.ComparisonBinaryOperator],["<",yt.ComparisonBinaryOperator],[">",yt.ComparisonBinaryOperator],["+",yt.AdditiveBinaryOperator],["-",yt.AdditiveBinaryOperator],["*",yt.MultiplicativeBinaryOperator],["/",yt.MultiplicativeBinaryOperator],["%",yt.MultiplicativeBinaryOperator],["=",yt.Equals]],Et=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var At=class{type="Statement"},Ct=class extends At{constructor(e){super(),this.body=e}type="Program"},Tt=class extends At{constructor(e,t,s){super(),this.test=e,this.body=t,this.alternate=s}type="If"},Ft=class extends At{constructor(e,t,s,n){super(),this.loopvar=e,this.iterable=t,this.body=s,this.defaultBlock=n}type="For"},St=class extends At{type="Break"},Pt=class extends At{type="Continue"},zt=class extends At{constructor(e,t,s){super(),this.assignee=e,this.value=t,this.body=s}type="Set"},It=class extends At{constructor(e,t,s){super(),this.name=e,this.args=t,this.body=s}type="Macro"},Lt=class extends At{type="Expression"},Bt=class extends Lt{constructor(e,t,s){super(),this.object=e,this.property=t,this.computed=s}type="MemberExpression"},Ot=class extends Lt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},$t=class extends Lt{constructor(e){super(),this.value=e}type="Identifier"},Nt=class extends Lt{constructor(e){super(),this.value=e}type="Literal"},Dt=class extends Nt{type="NumericLiteral"},Vt=class extends Nt{type="StringLiteral"},jt=class extends Nt{type="BooleanLiteral"},Ut=class extends Nt{type="NullLiteral"},Rt=class extends Nt{type="ArrayLiteral"},qt=class extends Nt{type="TupleLiteral"},Gt=class extends Nt{type="ObjectLiteral"},Wt=class extends Lt{constructor(e,t,s){super(),this.operator=e,this.left=t,this.right=s}type="BinaryExpression"},Xt=class extends Lt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},Ht=class extends Lt{constructor(e,t){super(),this.iterable=e,this.test=t}type="SelectExpression"},Jt=class extends Lt{constructor(e,t,s){super(),this.operand=e,this.negate=t,this.test=s}type="TestExpression"},Kt=class extends Lt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},Qt=class extends Lt{constructor(e=void 0,t=void 0,s=void 0){super(),this.start=e,this.stop=t,this.step=s}type="SliceExpression"},Zt=class extends Lt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function Yt(e){const t=new Ct([]);let s=0;function n(t,n){const a=e[s++];if(!a||a.type!==t)throw new Error(`Parser Error: ${n}. ${a.type} !== ${t}.`);return a}function a(){switch(e[s].type){case yt.Text:return new Vt(n(yt.Text,"Expected text token").value);case yt.OpenStatement:return function(){let t;switch(n(yt.OpenStatement,"Expected opening statement token"),e[s].type){case yt.Set:++s,t=function(){const t=c();if(o(yt.Equals)){++s;const e=c();return new zt(t,e,[])}{const r=[];for(n(yt.CloseStatement,"Expected %} token");e[s]?.type!==yt.OpenStatement||e[s+1]?.type!==yt.EndSet;){const e=a();r.push(e)}return n(yt.OpenStatement,"Expected {% token"),n(yt.EndSet,"Expected endset token"),new zt(t,null,r)}}(),n(yt.CloseStatement,"Expected closing statement token");break;case yt.If:++s,t=i(),n(yt.OpenStatement,"Expected {% token"),n(yt.EndIf,"Expected endif token"),n(yt.CloseStatement,"Expected %} token");break;case yt.Macro:++s,t=function(){const e=x();if("Identifier"!==e.type)throw new SyntaxError("Expected identifier following macro statement");const t=m();n(yt.CloseStatement,"Expected closing statement token");const s=[];for(;r(yt.OpenStatement,yt.EndMacro);)s.push(a());return new It(e,t,s)}(),n(yt.OpenStatement,"Expected {% token"),n(yt.EndMacro,"Expected endmacro token"),n(yt.CloseStatement,"Expected %} token");break;case yt.For:++s,t=function(){const e=l(!0);if(!(e instanceof $t||e instanceof qt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);n(yt.In,"Expected `in` keyword following loop variable");const t=c();n(yt.CloseStatement,"Expected closing statement token");const i=[];for(;r(yt.OpenStatement,yt.EndFor)&&r(yt.OpenStatement,yt.Else);)i.push(a());const d=[];if(o(yt.OpenStatement,yt.Else))for(++s,++s,n(yt.CloseStatement,"Expected closing statement token");r(yt.OpenStatement,yt.EndFor);)d.push(a());return new Ft(e,t,i,d)}(),n(yt.OpenStatement,"Expected {% token"),n(yt.EndFor,"Expected endfor token"),n(yt.CloseStatement,"Expected %} token");break;case yt.Break:++s,n(yt.CloseStatement,"Expected closing statement token"),t=new St;break;case yt.Continue:++s,n(yt.CloseStatement,"Expected closing statement token"),t=new Pt;break;default:throw new SyntaxError(`Unknown statement type: ${e[s].type}`)}return t}();case yt.OpenExpression:return function(){n(yt.OpenExpression,"Expected opening expression token");const e=c();return n(yt.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[s].type}`)}}function r(...t){return s+t.length<=e.length&&t.some(((t,n)=>t!==e[s+n].type))}function o(...t){return s+t.length<=e.length&&t.every(((t,n)=>t===e[s+n].type))}function i(){const t=c();n(yt.CloseStatement,"Expected closing statement token");const r=[],l=[];for(;e[s]?.type!==yt.OpenStatement||e[s+1]?.type!==yt.ElseIf&&e[s+1]?.type!==yt.Else&&e[s+1]?.type!==yt.EndIf;)r.push(a());if(e[s]?.type===yt.OpenStatement&&e[s+1]?.type!==yt.EndIf)if(++s,o(yt.ElseIf))n(yt.ElseIf,"Expected elseif token"),l.push(i());else for(n(yt.Else,"Expected else token"),n(yt.CloseStatement,"Expected closing statement token");e[s]?.type!==yt.OpenStatement||e[s+1]?.type!==yt.EndIf;)l.push(a());return new Tt(t,r,l)}function l(e=!1){const t=e?x:c,n=[t()],a=o(yt.Comma);for(;a&&(++s,n.push(t()),o(yt.Comma)););return a?new qt(n):n[0]}function c(){return function(){const e=d();if(o(yt.If)){++s;const t=d();if(o(yt.Else)){++s;const n=d();return new Tt(t,[e],[n])}return new Ht(e,t)}return e}()}function d(){let t=u();for(;o(yt.Or);){const n=e[s];++s;const a=u();t=new Wt(n,t,a)}return t}function u(){let t=h();for(;o(yt.And);){const n=e[s];++s;const a=h();t=new Wt(n,t,a)}return t}function h(){let t;for(;o(yt.Not);){const n=e[s];++s;const a=h();t=new Kt(n,a)}return t??function(){let t=_();for(;o(yt.ComparisonBinaryOperator)||o(yt.In)||o(yt.NotIn);){const n=e[s];++s;const a=_();t=new Wt(n,t,a)}return t}()}function _(){let t=w();for(;o(yt.AdditiveBinaryOperator);){const n=e[s];++s;const a=w();t=new Wt(n,t,a)}return t}function p(e){let t=new Ot(e,m());return t=g(t),o(yt.OpenParen)&&(t=p(t)),t}function m(){n(yt.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!o(yt.CloseParen);){let t=c();if(o(yt.Equals)){if(++s,!(t instanceof $t))throw new SyntaxError("Expected identifier for keyword argument");const e=c();t=new Zt(t,e)}e.push(t),o(yt.Comma)&&++s}return e}();return n(yt.CloseParen,"Expected closing parenthesis for arguments list"),e}function f(){const e=[];let t=!1;for(;!o(yt.CloseSquareBracket);)o(yt.Colon)?(e.push(void 0),++s,t=!0):(e.push(c()),o(yt.Colon)&&(++s,t=!0));if(0===e.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Qt(...e)}return e[0]}function g(t){for(;o(yt.Dot)||o(yt.OpenSquareBracket);){const a=e[s];let r;++s;const o=a.type!==yt.Dot;if(o)r=f(),n(yt.CloseSquareBracket,"Expected closing square bracket");else if(r=x(),"Identifier"!==r.type)throw new SyntaxError("Expected identifier following dot operator");t=new Bt(t,r,o)}return t}function w(){let t=y();for(;o(yt.MultiplicativeBinaryOperator);){const n=e[s];++s;const a=y();t=new Wt(n,t,a)}return t}function y(){let e=function(){let e=function(){const e=g(x());return o(yt.OpenParen)?p(e):e}();for(;o(yt.Pipe);){++s;let t=x();if(!(t instanceof $t))throw new SyntaxError("Expected identifier for the filter");o(yt.OpenParen)&&(t=p(t)),e=new Xt(e,t)}return e}();for(;o(yt.Is);){++s;const t=o(yt.Not);t&&++s;let n=x();if(n instanceof jt?n=new $t(n.value.toString()):n instanceof Ut&&(n=new $t("none")),!(n instanceof $t))throw new SyntaxError("Expected identifier for the test");e=new Jt(e,t,n)}return e}function x(){const t=e[s];switch(t.type){case yt.NumericLiteral:return++s,new Dt(Number(t.value));case yt.StringLiteral:return++s,new Vt(t.value);case yt.BooleanLiteral:return++s,new jt("true"===t.value.toLowerCase());case yt.NullLiteral:return++s,new Ut(null);case yt.Identifier:return++s,new $t(t.value);case yt.OpenParen:{++s;const t=l();if(e[s].type!==yt.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[s].type} instead`);return++s,t}case yt.OpenSquareBracket:{++s;const e=[];for(;!o(yt.CloseSquareBracket);)e.push(c()),o(yt.Comma)&&++s;return++s,new Rt(e)}case yt.OpenCurlyBracket:{++s;const e=new Map;for(;!o(yt.CloseCurlyBracket);){const t=c();n(yt.Colon,"Expected colon between key and value in object literal");const a=c();e.set(t,a),o(yt.Comma)&&++s}return++s,new Gt(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;s<e.length;)t.body.push(a());return t}function es(e,t,s=1){void 0===t&&(t=e,e=0);const n=[];for(let a=e;a<t;a+=s)n.push(a);return n}function ts(e,t,s,n=1){const a=Math.sign(n);a>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),s=(s??=e.length)<0?Math.max(e.length+s,0):Math.min(s,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),s=(s??=-1)<-1?Math.max(e.length+s,-1):Math.min(s,e.length-1));const r=[];for(let o=t;a*o<a*s;o+=n)r.push(e[o]);return r}function ss(e){return e.replace(/\b\w/g,(e=>e.toUpperCase()))}var ns=class extends Error{},as=class extends Error{},rs=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new ls(!!this.value)}},os=class extends rs{type="NumericValue"},is=class extends rs{type="StringValue";builtins=new Map([["upper",new _s((()=>new is(this.value.toUpperCase())))],["lower",new _s((()=>new is(this.value.toLowerCase())))],["strip",new _s((()=>new is(this.value.trim())))],["title",new _s((()=>new is(ss(this.value))))],["length",new os(this.value.length)],["rstrip",new _s((()=>new is(this.value.trimEnd())))],["lstrip",new _s((()=>new is(this.value.trimStart())))],["startswith",new _s((e=>{if(0===e.length)throw new Error("startswith() requires at least one argument");const t=e[0];if(!(t instanceof is))throw new Error("startswith() argument must be a string");return new ls(this.value.startsWith(t.value))}))],["endswith",new _s((e=>{if(0===e.length)throw new Error("endswith() requires at least one argument");const t=e[0];if(!(t instanceof is))throw new Error("endswith() argument must be a string");return new ls(this.value.endsWith(t.value))}))],["split",new _s((e=>{const t=e[0]??new ps;if(!(t instanceof is||t instanceof ps))throw new Error("sep argument must be a string or null");const s=e[1]??new os(-1);if(!(s instanceof os))throw new Error("maxsplit argument must be a number");let n=[];if(t instanceof ps){const e=this.value.trimStart();for(const{0:t,index:a}of e.matchAll(/\S+/g)){if(-1!==s.value&&n.length>=s.value&&void 0!==a){n.push(t+e.slice(a+t.length));break}n.push(t)}}else{if(""===t.value)throw new Error("empty separator");n=this.value.split(t.value),-1!==s.value&&n.length>s.value&&n.push(n.splice(s.value).join(t.value))}return new us(n.map((e=>new is(e))))}))]])},ls=class extends rs{type="BooleanValue"},cs=class extends rs{type="ObjectValue";__bool__(){return new ls(this.value.size>0)}builtins=new Map([["get",new _s((([e,t])=>{if(!(e instanceof is))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new ps}))],["items",new _s((()=>new us(Array.from(this.value.entries()).map((([e,t])=>new us([new is(e),t]))))))]])},ds=class extends cs{type="KeywordArgumentsValue"},us=class extends rs{type="ArrayValue";builtins=new Map([["length",new os(this.value.length)]]);__bool__(){return new ls(this.value.length>0)}},hs=class extends us{type="TupleValue"},_s=class extends rs{type="FunctionValue"},ps=class extends rs{type="NullValue"},ms=class extends rs{type="UndefinedValue"},fs=class{constructor(e){this.parent=e}variables=new Map([["namespace",new _s((e=>{if(0===e.length)return new cs(new Map);if(1!==e.length||!(e[0]instanceof cs))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]}))]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof _s],["odd",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!=0}],["even",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["none",e=>"NullValue"===e.type],["string",e=>"StringValue"===e.type],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>"ArrayValue"===e.type||"StringValue"===e.type],["mapping",e=>"ObjectValue"===e.type],["lower",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,ws(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 ms}catch{return new ms}}},gs=class{global;constructor(e){this.global=e??new fs}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const s=this.evaluate(e.left,t);switch(e.operator.value){case"and":return s.__bool__().value?this.evaluate(e.right,t):s;case"or":return s.__bool__().value?s:this.evaluate(e.right,t)}const n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ls(s.value==n.value);case"!=":return new ls(s.value!=n.value)}if(s instanceof ms||n instanceof ms)throw new Error("Cannot perform operation on undefined values");if(s instanceof ps||n instanceof ps)throw new Error("Cannot perform operation on null values");if(s instanceof os&&n instanceof os)switch(e.operator.value){case"+":return new os(s.value+n.value);case"-":return new os(s.value-n.value);case"*":return new os(s.value*n.value);case"/":return new os(s.value/n.value);case"%":return new os(s.value%n.value);case"<":return new ls(s.value<n.value);case">":return new ls(s.value>n.value);case">=":return new ls(s.value>=n.value);case"<=":return new ls(s.value<=n.value)}else if(s instanceof us&&n instanceof us){if("+"===e.operator.value)return new us(s.value.concat(n.value))}else if(n instanceof us){const t=void 0!==n.value.find((e=>e.value===s.value));switch(e.operator.value){case"in":return new ls(t);case"not in":return new ls(!t)}}if((s instanceof is||n instanceof is)&&"+"===e.operator.value)return new is(s.value.toString()+n.value.toString());if(s instanceof is&&n instanceof is)switch(e.operator.value){case"in":return new ls(n.value.includes(s.value));case"not in":return new ls(!n.value.includes(s.value))}if(s instanceof is&&n instanceof cs)switch(e.operator.value){case"in":return new ls(n.value.has(s.value));case"not in":return new ls(!n.value.has(s.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${s.type} and ${n.type}`)}evaluateArguments(e,t){const s=[],n=new Map;for(const a of e)if("KeywordArgumentExpression"===a.type){const e=a;n.set(e.key.value,this.evaluate(e.value,t))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");s.push(this.evaluate(a,t))}return[s,n]}evaluateFilterExpression(e,t){const s=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if("tojson"===t.value)return new is(ys(s));if(s instanceof us)switch(t.value){case"list":return s;case"first":return s.value[0];case"last":return s.value[s.value.length-1];case"length":return new os(s.value.length);case"reverse":return new us(s.value.reverse());case"sort":return new us(s.value.sort(((e,t)=>{if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));case"join":return new is(s.value.map((e=>e.value)).join(""));case"string":return new is(ys(s));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}else if(s instanceof is)switch(t.value){case"length":return new os(s.value.length);case"upper":return new is(s.value.toUpperCase());case"lower":return new is(s.value.toLowerCase());case"title":return new is(ss(s.value));case"capitalize":return new is(s.value.charAt(0).toUpperCase()+s.value.slice(1));case"trim":return new is(s.value.trim());case"indent":return new is(s.value.split("\n").map(((e,t)=>0===t||0===e.length?e:" "+e)).join("\n"));case"join":case"string":return s;default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(s instanceof os){if("abs"===t.value)return new os(Math.abs(s.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(s instanceof cs)switch(t.value){case"items":return new us(Array.from(s.value.entries()).map((([e,t])=>new us([new is(e),t]))));case"length":return new os(s.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${s.type}`)}if("CallExpression"===e.filter.type){const n=e.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const a=n.callee.value;if("tojson"===a){const[,e]=this.evaluateArguments(n.args,t),a=e.get("indent")??new ps;if(!(a instanceof os||a instanceof ps))throw new Error("If set, indent must be a number");return new is(ys(s,a.value))}if("join"===a){let e;if(s instanceof is)e=Array.from(s.value);else{if(!(s instanceof us))throw new Error(`Cannot apply filter "${a}" to type: ${s.type}`);e=s.value.map((e=>e.value))}const[r,o]=this.evaluateArguments(n.args,t),i=r.at(0)??o.get("separator")??new is("");if(!(i instanceof is))throw new Error("separator must be a string");return new is(e.join(i.value))}if(s instanceof us){switch(a){case"selectattr":case"rejectattr":{const e="selectattr"===a;if(s.value.some((e=>!(e instanceof cs))))throw new Error(`\`${a}\` can only be applied to array of objects`);if(n.args.some((e=>"StringLiteral"!==e.type)))throw new Error(`arguments of \`${a}\` must be strings`);const[r,o,i]=n.args.map((e=>this.evaluate(e,t)));let l;if(o){const e=t.tests.get(o.value);if(!e)throw new Error(`Unknown test: ${o.value}`);l=e}else l=(...e)=>e[0].__bool__().value;const c=s.value.filter((t=>{const s=t.value.get(r.value),n=!!s&&l(s,i);return e?n:!n}));return new us(c)}case"map":{const[,e]=this.evaluateArguments(n.args,t);if(e.has("attribute")){const t=e.get("attribute");if(!(t instanceof is))throw new Error("attribute must be a string");const n=e.get("default"),a=s.value.map((e=>{if(!(e instanceof cs))throw new Error("items in map must be an object");return e.value.get(t.value)??n??new ms}));return new us(a)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${a}`)}if(s instanceof is){if("indent"===a){const[e,a]=this.evaluateArguments(n.args,t),r=e.at(0)??a.get("width")??new os(4);if(!(r instanceof os))throw new Error("width must be a number");const o=e.at(1)??a.get("first")??new ls(!1),i=e.at(2)??a.get("blank")??new ls(!1),l=s.value.split("\n"),c=" ".repeat(r.value),d=l.map(((e,t)=>!o.value&&0===t||!i.value&&0===e.length?e:c+e));return new is(d.join("\n"))}throw new Error(`Unknown StringValue filter: ${a}`)}throw new Error(`Cannot apply filter "${a}" to type: ${s.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const s=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw new Error(`Unknown test: ${e.test.value}`);const a=n(s);return new ls(e.negate?!a:a)}evaluateUnaryExpression(e,t){const s=this.evaluate(e.argument,t);if("not"===e.operator.value)return new ls(!s.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let s="";for(const n of e){const e=this.evaluate(n,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(s+=e.value)}return new is(s)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[s,n]=this.evaluateArguments(e.args,t);n.size>0&&s.push(new ds(n));const a=this.evaluate(e.callee,t);if("FunctionValue"!==a.type)throw new Error(`Cannot call something that is not a function: got ${a.type}`);return a.value(s,t)}evaluateSliceExpression(e,t,s){if(!(e instanceof us||e instanceof is))throw new Error("Slice object must be an array or string");const n=this.evaluate(t.start,s),a=this.evaluate(t.stop,s),r=this.evaluate(t.step,s);if(!(n instanceof os||n instanceof ms))throw new Error("Slice start must be numeric or undefined");if(!(a instanceof os||a instanceof ms))throw new Error("Slice stop must be numeric or undefined");if(!(r instanceof os||r instanceof ms))throw new Error("Slice step must be numeric or undefined");return e instanceof us?new us(ts(e.value,n.value,a.value,r.value)):new is(ts(Array.from(e.value),n.value,a.value,r.value).join(""))}evaluateMemberExpression(e,t){const s=this.evaluate(e.object,t);let n,a;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(s,e.property,t);n=this.evaluate(e.property,t)}else n=new is(e.property.value);if(s instanceof cs){if(!(n instanceof is))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=s.value.get(n.value)??s.builtins.get(n.value)}else if(s instanceof us||s instanceof is)if(n instanceof os)a=s.value.at(n.value),s instanceof is&&(a=new is(s.value.at(n.value)));else{if(!(n instanceof is))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);a=s.builtins.get(n.value)}else{if(!(n instanceof is))throw new Error(`Cannot access property with non-string: got ${n.type}`);a=s.builtins.get(n.value)}return a instanceof rs?a:new ms}evaluateSet(e,t){const s=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if("Identifier"===e.assignee.type){const n=e.assignee.value;t.setVariable(n,s)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const n=e.assignee,a=this.evaluate(n.object,t);if(!(a instanceof cs))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");a.value.set(n.property.value,s)}}return new ps}evaluateIf(e,t){const s=this.evaluate(e.test,t);return this.evaluateBlock(s.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const s=new fs(t);let n,a;if("SelectExpression"===e.iterable.type){const t=e.iterable;a=this.evaluate(t.iterable,s),n=t.test}else a=this.evaluate(e.iterable,s);if(!(a instanceof us))throw new Error(`Expected iterable type in for loop: got ${a.type}`);const r=[],o=[];for(let t=0;t<a.value.length;++t){const i=new fs(s),l=a.value[t];let c;if("Identifier"===e.loopvar.type)c=t=>t.setVariable(e.loopvar.value,l);else{if("TupleLiteral"!==e.loopvar.type)throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);{const t=e.loopvar;if("ArrayValue"!==l.type)throw new Error(`Cannot unpack non-iterable type: ${l.type}`);const s=l;if(t.value.length!==s.value.length)throw new Error(`Too ${t.value.length>s.value.length?"few":"many"} items to unpack`);c=e=>{for(let n=0;n<t.value.length;++n){if("Identifier"!==t.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${t.value[n].type}`);e.setVariable(t.value[n].value,s.value[n])}}}}if(n){c(i);if(!this.evaluate(n,i).__bool__().value)continue}r.push(l),o.push(c)}let i="",l=!0;for(let t=0;t<r.length;++t){const n=new Map([["index",new os(t+1)],["index0",new os(t)],["revindex",new os(r.length-t)],["revindex0",new os(r.length-t-1)],["first",new ls(0===t)],["last",new ls(t===r.length-1)],["length",new os(r.length)],["previtem",t>0?r[t-1]:new ms],["nextitem",t<r.length-1?r[t+1]:new ms]]);s.setVariable("loop",new cs(n)),o[t](s);try{i+=this.evaluateBlock(e.body,s).value}catch(e){if(e instanceof as)continue;if(e instanceof ns)break;throw e}l=!1}if(l){i+=this.evaluateBlock(e.defaultBlock,s).value}return new is(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new _s(((t,s)=>{const n=new fs(s);let a;t=t.slice(),"KeywordArgumentsValue"===t.at(-1)?.type&&(a=t.pop());for(let s=0;s<e.args.length;++s){const r=e.args[s],o=t[s];if("Identifier"===r.type){const e=r;if(!o)throw new Error(`Missing positional argument: ${e.value}`);n.setVariable(e.value,o)}else{if("KeywordArgumentExpression"!==r.type)throw new Error(`Unknown argument type: ${r.type}`);{const e=r,t=o??a?.value.get(e.key.value)??this.evaluate(e.value,n);n.setVariable(e.key.value,t)}}}return this.evaluateBlock(e.body,n)}))),new ps}evaluate(e,t){if(void 0===e)return new ms;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"Break":throw new ns;case"Continue":throw new as;case"NumericLiteral":return new os(Number(e.value));case"StringLiteral":return new is(e.value);case"BooleanLiteral":return new ls(e.value);case"NullLiteral":return new ps(e.value);case"ArrayLiteral":return new us(e.value.map((e=>this.evaluate(e,t))));case"TupleLiteral":return new hs(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const s=new Map;for(const[n,a]of e.value){const e=this.evaluate(n,t);if(!(e instanceof is))throw new Error(`Object keys must be strings: got ${e.type}`);s.set(e.value,this.evaluate(a,t))}return new cs(s)}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"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function ws(e){switch(typeof e){case"number":return new os(e);case"string":return new is(e);case"boolean":return new ls(e);case"undefined":return new ms;case"object":return null===e?new ps:Array.isArray(e)?new us(e.map(ws)):new cs(new Map(Object.entries(e).map((([e,t])=>[e,ws(t)]))));case"function":return new _s(((t,s)=>ws(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function ys(e,t,s){const n=s??0;switch(e.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(e.value);case"ArrayValue":case"ObjectValue":{const s=t?" ".repeat(t):"",a="\n"+s.repeat(n),r=a+s;if("ArrayValue"===e.type){const s=e.value.map((e=>ys(e,t,n+1)));return t?`[${r}${s.join(`,${r}`)}${a}]`:`[${s.join(", ")}]`}{const s=Array.from(e.value.entries()).map((([e,s])=>{const a=`"${e}": ${ys(s,t,n+1)}`;return t?`${r}${a}`:a}));return t?`{${s.join(",")}${a}}`:`{${s.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var xs="\n",bs="{%- ",ks=" -%}",vs={MultiplicativeBinaryOperator:2,AdditiveBinaryOperator:1,ComparisonBinaryOperator:0};function Ms(...e){return bs+e.join(" ")+ks}function Es(e,t,s){return e.map((e=>function(e,t,s){const n=s.repeat(t);switch(e.type){case"Program":return Es(e.body,t,s);case"If":return function(e,t,s){const n=s.repeat(t),a=[];let r=e;for(;r&&(a.push({test:r.test,body:r.body}),1===r.alternate.length&&"If"===r.alternate[0].type);)r=r.alternate[0];let o=n+Ms("if",As(a[0].test))+xs+Es(a[0].body,t+1,s);for(let e=1;e<a.length;e++)o+=xs+n+Ms("elif",As(a[e].test))+xs+Es(a[e].body,t+1,s);r&&r.alternate.length>0&&(o+=xs+n+Ms("else")+xs+Es(r.alternate,t+1,s));return o+=xs+n+Ms("endif"),o}(e,t,s);case"For":return function(e,t,s){const n=s.repeat(t);let a="";if("SelectExpression"===e.iterable.type){const t=e.iterable;a=`${As(t.iterable)} if ${As(t.test)}`}else a=As(e.iterable);let r=n+Ms("for",As(e.loopvar),"in",a)+xs+Es(e.body,t+1,s);e.defaultBlock.length>0&&(r+=xs+n+Ms("else")+xs+Es(e.defaultBlock,t+1,s));return r+=xs+n+Ms("endfor"),r}(e,t,s);case"Set":return function(e,t,s){const n=s.repeat(t),a=As(e.assignee),r=e.value?As(e.value):"",o=n+Ms("set",`${a}${e.value?" = "+r:""}`);if(0===e.body.length)return o;return o+xs+Es(e.body,t+1,s)+xs+n+Ms("endset")}(e,t,s);case"Macro":return function(e,t,s){const n=s.repeat(t),a=e.args.map(As).join(", ");return n+Ms("macro",`${e.name.value}(${a})`)+xs+Es(e.body,t+1,s)+xs+n+Ms("endmacro")}(e,t,s);case"Break":return n+Ms("break");case"Continue":return n+Ms("continue");default:return n+"{{- "+As(e)+" -}}"}}(e,t,s))).join(xs)}function As(e,t=-1){switch(e.type){case"Identifier":return e.value;case"NullLiteral":return"none";case"NumericLiteral":case"BooleanLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const s=e,n=vs[s.operator.type]??0,a=As(s.left,n),r=As(s.right,n+1),o=`${a} ${s.operator.value} ${r}`;return n<t?`(${o})`:o}case"UnaryExpression":{const t=e;return t.operator.value+("not"===t.operator.value?" ":"")+As(t.argument,1/0)}case"LogicalNegationExpression":return`not ${As(e.argument,1/0)}`;case"CallExpression":{const t=e,s=t.args.map((e=>As(e,-1))).join(", ");return`${As(t.callee,-1)}(${s})`}case"MemberExpression":{const t=e;let s=As(t.object,-1);"Identifier"!==t.object.type&&(s=`(${s})`);let n=As(t.property,-1);return t.computed||"Identifier"===t.property.type||(n=`(${n})`),t.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{const t=e,s=As(t.operand,1/0);return"CallExpression"===t.filter.type?`${s} | ${As(t.filter,-1)}`:`${s} | ${t.filter.value}`}case"SelectExpression":{const t=e;return`${As(t.iterable,-1)} | select(${As(t.test,-1)})`}case"TestExpression":{const t=e;return`${As(t.operand,-1)} is${t.negate?" not":""} ${t.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const t=e.value.map((e=>As(e,-1))),s="ArrayLiteral"===e.type?"[]":"()";return`${s[0]}${t.join(", ")}${s[1]}`}case"ObjectLiteral":return`{ ${Array.from(e.value.entries()).map((([e,t])=>`${As(e,-1)}: ${As(t,-1)}`)).join(", ")} }`;case"SliceExpression":{const t=e;return`${t.start?As(t.start,-1):""}:${t.stop?As(t.stop,-1):""}${t.step?`:${As(t.step,-1)}`:""}`}case"KeywordArgumentExpression":{const t=e;return`${t.key.value}=${As(t.value,-1)}`}case"If":{const t=e,s=As(t.test,-1);return`${As(t.body[0],0)} if ${s} else ${As(t.alternate[0],-1)}`}default:throw new Error(`Unknown expression type: ${e.type}`)}}var Cs=class{parsed;constructor(e){const t=function(e,t={}){const s=[],n=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(e,t);let a=0;const r=e=>{let t="";for(;e(n[a]);)if("\\"!==n[a]){if(t+=n[a++],a>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++a,a>=n.length)throw new SyntaxError("Unexpected end of input");const e=n[a++],s=Et.get(e);if(void 0===s)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=s}return t};e:for(;a<n.length;){const e=s.at(-1)?.type;if(void 0===e||e===yt.CloseStatement||e===yt.CloseExpression){let e="";for(;a<n.length&&("{"!==n[a]||"%"!==n[a+1]&&"{"!==n[a+1]);)e+=n[a++];if(e.length>0){s.push(new bt(e,yt.Text));continue}}r((e=>/\s/.test(e)));const t=n[a];if("-"===t||"+"===t){const e=s.at(-1)?.type;if(e===yt.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case yt.Identifier:case yt.NumericLiteral:case yt.BooleanLiteral:case yt.NullLiteral:case yt.StringLiteral:case yt.CloseParen:case yt.CloseSquareBracket:break;default:{++a;const e=r(vt);s.push(new bt(`${t}${e}`,e.length>0?yt.NumericLiteral:yt.UnaryOperator));continue}}}for(const[e,t]of Mt)if(n.slice(a,a+e.length)===e){s.push(new bt(e,t)),a+=e.length;continue e}if("'"!==t&&'"'!==t)if(vt(t)){const e=r(vt);s.push(new bt(e,yt.NumericLiteral))}else{if(!kt(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=r(kt),t=Object.hasOwn(xt,e)?xt[e]:yt.Identifier;t===yt.In&&s.at(-1)?.type===yt.Not?(s.pop(),s.push(new bt("not in",yt.NotIn))):s.push(new bt(e,t))}}else{++a;const e=r((e=>e!==t));s.push(new bt(e,yt.StringLiteral)),++a}}return s}(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Yt(t)}render(e){const t=new fs;if(t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",es),e)for(const[s,n]of Object.entries(e))t.set(s,n);return new gs(t).run(this.parsed).value}format(e){return function(e,t="\t"){const s="number"==typeof t?" ".repeat(t):t;return Es(e.body,0,s).replace(/\n$/,"")}(this.parsed,e?.indent||"\t")}};const Ts=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Fs=new Map(Ts),Ss=new Map([...Ts.map((([e,t])=>[t,e])),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);async function Ps(e,t){const s=await Promise.all([J(e,"tokenizer.json",!0,t),J(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(s[1].legacy=t.legacy),s}function zs(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,s]of js)t=t.replaceAll(e,s);return new RegExp(t,"gu")}if(void 0!==e.String){const s=e.String.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(t?s:`(${s})`,"gu")}return console.warn("Unknown pattern type:",e),null}function Is(e){return new Map(Object.entries(e))}function Ls(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function Bs(e){return 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")}function Os(e){return e.replace(/\p{M}/gu,"")}function $s(e){return 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}const Ns="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Ds=new RegExp(`^[${Ns}]+$`,"gu"),Vs=".,!?۔،",js=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],[` ?[^(\\s|[${Vs}])]+`,` ?[^\\s${Vs}]+`]]);class Us{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}}class Rs extends C{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new qs(e);case"Unigram":return new Gs(e,...t);case"BPE":return new Js(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Gs(e,...t):"object"==typeof e.vocab&&e.continuing_subword_prefix&&e.unk_token?new qs(e):new Ks(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return e=this.encode(e),this.fuse_unk&&(e=function(e,t,s){const n=[];let a=0;for(;a<e.length;)if(n.push(e[a]),(t.get(e[a])??s)===s)for(;++a<e.length&&(t.get(e[a])??s)===s;)t.get(n.at(-1))!==s&&(n[n.length-1]+=e[a]);else++a;return n}(e,this.tokens_to_ids,this.unk_token_id)),e}encode(e){throw Error("encode should be implemented in subclass.")}convert_tokens_to_ids(e){return e.map((e=>this.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class qs extends Rs{constructor(e){super(e),this.tokens_to_ids=Is(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){const t=[];for(const s of e){const e=[...s];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,a=0;const r=[];for(;a<e.length;){let t=e.length,s=null;for(;a<t;){let n=e.slice(a,t).join("");if(a>0&&(n=this.config.continuing_subword_prefix+n),this.tokens_to_ids.has(n)){s=n;break}--t}if(null===s){n=!0;break}r.push(s),a=t}n?t.push(this.unk_token):t.push(...r)}return t}}class Gs extends Rs{constructor(e,t){super(e);const s=e.vocab.length;this.vocab=new Array(s),this.scores=new Array(s);for(let t=0;t<s;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map(((e,t)=>[e,t]))),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=ae(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new _t,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.chars;let s=0;for(;s<t.length;){let n=!1;const a=[],r=t.slice(s).join(""),o=this.trie.commonPrefixSearch(r);for(const t of o){a.push(t);const r=this.tokens_to_ids.get(t),o=this.scores[r],i=O(t);e.insert(s,i,o,r),n||1!==i||(n=!0)}n||e.insert(s,1,this.unk_score,this.unk_token_id),s+=1}}tokenize(e){const t=new mt(e,this.bos_token_id,this.eos_token_id);return this.populateNodes(t),t.tokens()}encode(e){const t=[];for(const s of e){const e=this.tokenize(s);t.push(...e)}return t}}const Ws=(()=>{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))],t=e.slice();let s=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+s),s+=1);const n=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,n[t]])))})(),Xs=(Hs=Ws,Object.fromEntries(Object.entries(Hs).map((([e,t])=>[t,e]))));var Hs;class Js extends Rs{constructor(e){super(e),this.tokens_to_ids=Is(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[e,t]of this.tokens_to_ids)this.vocab[t]=e;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map((e=>e.split(" ",2))),this.bpe_ranks=new Map(this.merges.map(((e,t)=>[JSON.stringify(e),t]))),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new wt(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const s=Array.from(e);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let n=[];if(s.length>1){const e=new ht(((e,t)=>e.score<t.score));let t={token:s[0],bias:0,prev:null,next:null},a=t;for(let t=1;t<s.length;++t){const n={bias:t/s.length,token:s[t],prev:a,next:null};a.next=n,this._add_node(e,a),a=n}for(;!e.isEmpty();){const s=e.pop();if(s.deleted||!s.next||s.next.deleted)continue;if(s.deleted=!0,s.next.deleted=!0,s.prev){const e={...s.prev};s.prev.deleted=!0,s.prev=e,e.prev?e.prev.next=e:t=e}const n={token:s.token+s.next.token,bias:s.bias,prev:s.prev,next:s.next.next};n.prev?(n.prev.next=n,this._add_node(e,n.prev)):t=n,n.next&&(n.next.prev=n,this._add_node(e,n))}for(let e=t;null!==e;e=e.next)n.push(e.token)}else n=s;if(this.continuing_subword_suffix)for(let e=0;e<n.length-1;++e)n[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}_add_node(e,t){const s=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));void 0!==s&&(t.score=s+t.bias,e.push(t))}encode(e){const t=[];for(const s of e){if(this.ignore_merges&&this.tokens_to_ids.has(s)){t.push(s);continue}const e=this.bpe(s);for(const s of e)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const e=Array.from(this.text_encoder.encode(s)).map((e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`));e.every((e=>this.tokens_to_ids.has(e)))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}}class Ks extends Rs{constructor(e,t){super(e),this.tokens_to_ids=Is(t.target_lang?e.vocab[t.target_lang]:e.vocab),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[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}}class Qs extends C{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new dn(e);case"Precompiled":return new On(e);case"Sequence":return new cn(e);case"Replace":return new Zs(e);case"NFC":return new en(e);case"NFD":return new tn(e);case"NFKC":return new sn(e);case"NFKD":return new nn(e);case"Strip":return new an(e);case"StripAccents":return new rn(e);case"Lowercase":return new on(e);case"Prepend":return new ln(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class Zs extends Qs{normalize(e){const t=zs(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class Ys extends Qs{form=void 0;normalize(e){return e=e.normalize(this.form)}}class en extends Ys{form="NFC"}class tn extends Ys{form="NFD"}class sn extends Ys{form="NFKC"}class nn extends Ys{form="NFKD"}class an extends Qs{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}}class rn extends Qs{normalize(e){return e=Os(e)}}class on extends Qs{normalize(e){return e=e.toLowerCase()}}class ln extends Qs{normalize(e){return e=this.config.prepend+e}}class cn extends Qs{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>Qs.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class dn extends Qs{_tokenize_chinese_chars(e){const t=[];for(let s=0;s<e.length;++s){const n=e[s];$s(n.charCodeAt(0))?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}stripAccents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}_is_control(e){switch(e){case"\t":case"\n":case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}_clean_text(e){const t=[];for(const s of e){const e=s.charCodeAt(0);0===e||65533===e||this._is_control(s)||(/^\s$/.test(s)?t.push(" "):t.push(s))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this._clean_text(e)),this.config.handle_chinese_chars&&(e=this._tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),!1!==this.config.strip_accents&&(e=this.stripAccents(e))):this.config.strip_accents&&(e=this.stripAccents(e)),e}}class un extends C{static fromConfig(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new hn(e);case"Sequence":return new $n(e);case"Whitespace":return new Nn(e);case"WhitespaceSplit":return new Dn(e);case"Metaspace":return new Ln(e);case"ByteLevel":return new _n(e);case"Split":return new pn(e);case"Punctuation":return new mn(e);case"Digits":return new fn(e);case"Replace":return new Vn(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}pre_tokenize_text(e,t){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(e,t){return(Array.isArray(e)?e.map((e=>this.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class hn extends un{constructor(e){super(),this.pattern=new RegExp(`[^\\s${Ns}]+|[${Ns}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class _n extends un{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=Ws,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e);return(this.use_regex?e.match(this.pattern)||[]:[e]).map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class pn extends un{constructor(e){super(),this.config=e,this.pattern=zs(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:"removed"===this.config.behavior?.toLowerCase()?e.split(this.pattern).filter((e=>e)):function(e,t){const s=[];let n=0;for(const a of e.matchAll(t)){const t=a[0];n<a.index&&s.push(e.slice(n,a.index)),t.length>0&&s.push(t),n=a.index+t.length}return n<e.length&&s.push(e.slice(n)),s}(e,this.pattern)}}class mn extends un{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Ns}]+|[${Ns}]+`,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class fn extends un{constructor(e){super(),this.config=e;const t="[^\\d]+|\\d"+(this.config.individual_digits?"":"+");this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e,t){return e.match(this.pattern)||[]}}class gn extends C{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new xn(e);case"ByteLevel":return new bn(e);case"RobertaProcessing":return new yn(e);case"BertProcessing":return new wn(e);case"Sequence":return new kn(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}post_process(e,...t){throw Error("post_process should be implemented in subclass.")}_call(e,...t){return this.post_process(e,...t)}}class wn extends gn{constructor(e){super(e),this.cls=e.cls[0],this.sep=e.sep[0]}post_process(e,t=null,{add_special_tokens:s=!0}={}){s&&(e=P([this.cls],e,[this.sep]));let n=new Array(e.length).fill(0);if(null!==t){const a=s&&this instanceof yn?[this.sep]:[],r=s?[this.sep]:[];e=P(e,a,t,r),n=P(n,new Array(t.length+a.length+r.length).fill(1))}return{tokens:e,token_type_ids:n}}}class yn extends wn{}class xn extends gn{constructor(e){super(e),this.single=e.single,this.pair=e.pair}post_process(e,t=null,{add_special_tokens:s=!0}={}){const n=null===t?this.single:this.pair;let a=[],r=[];for(const o of n)"SpecialToken"in o?s&&(a.push(o.SpecialToken.id),r.push(o.SpecialToken.type_id)):"Sequence"in o&&("A"===o.Sequence.id?(a=P(a,e),r=P(r,new Array(e.length).fill(o.Sequence.type_id))):"B"===o.Sequence.id&&(a=P(a,t),r=P(r,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:a,token_type_ids:r}}}class bn extends gn{post_process(e,t=null){return t&&(e=P(e,t)),{tokens:e}}}class kn extends gn{constructor(e){super(e),this.processors=e.processors.map((e=>gn.fromConfig(e)))}post_process(e,t=null,s={}){let n;for(const a of this.processors)if(a instanceof bn){if(e=a.post_process(e).tokens,t){t=a.post_process(t).tokens}}else{const r=a.post_process(e,t,s);e=r.tokens,n=r.token_type_ids}return{tokens:e,token_type_ids:n}}}class vn extends C{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(null===e)return null;switch(e.type){case"WordPiece":return new Tn(e);case"Metaspace":return new Bn(e);case"ByteLevel":return new Fn(e);case"Replace":return new Mn(e);case"ByteFallback":return new En(e);case"Fuse":return new An(e);case"Strip":return new Cn(e);case"Sequence":return new Pn(e);case"CTC":return new Sn(e);case"BPEDecoder":return new zn(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class Mn extends vn{decode_chain(e){const t=zs(this.config.pattern);return null===t?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class En extends vn{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let s=[];for(const n of e){let e=null;if(6===n.length&&n.startsWith("<0x")&&n.endsWith(">")){const t=parseInt(n.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)s.push(e);else{if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}t.push(n)}}if(s.length>0){const e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}return t}}class An extends vn{decode_chain(e){return[e.join("")]}}class Cn extends vn{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map((e=>{let t=0;for(let s=0;s<this.start&&e[s]===this.content;++s)t=s+1;let s=e.length;for(let t=0;t<this.stop;++t){const n=e.length-t-1;if(e[n]!==this.content)break;s=n}return e.slice(t,s)}))}}class Tn extends vn{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map(((e,t)=>(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=Bs(e)),e)))}}class Fn extends vn{constructor(e){super(e),this.byte_decoder=Xs,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(""),s=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(s)}decode_chain(e){const t=[];let s=[];for(const n of e)void 0!==this.added_tokens.find((e=>e.content===n))?(s.length>0&&(t.push(this.convert_tokens_to_string(s)),s=[]),t.push(n)):s.push(n);return s.length>0&&t.push(this.convert_tokens_to_string(s)),t}}class Sn extends vn{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";const t=[e[0]];for(let s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let s=t.filter((e=>e!==this.pad_token)).join("");return this.cleanup&&(s=Bs(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class Pn extends vn{constructor(e){super(e),this.decoders=e.decoders.map((e=>vn.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class zn extends vn{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,s)=>t.replaceAll(this.suffix,s===e.length-1?"":" ")))}}class In extends vn{decode_chain(e){let t="";for(let s=1;s<e.length;s+=2)t+=e[s];return[t]}}class Ln extends un{constructor(e){super(),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement,this.strRep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,{section_index:t}={}){let s=e.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!s.startsWith(this.replacement)&&("always"===this.prepend_scheme||"first"===this.prepend_scheme&&0===t)&&(s=this.strRep+s),[s]}}class Bn extends vn{constructor(e){super(e),this.addPrefixSpace=e.add_prefix_space,this.replacement=e.replacement}decode_chain(e){const t=[];for(let s=0;s<e.length;++s){let n=e[s].replaceAll(this.replacement," ");this.addPrefixSpace&&0==s&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}}class On extends Qs{constructor(e){super(e),this.charsmap=e.precompiled_charsmap}normalize(e){if((e=(e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"")).replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," ")).includes("")){const t=e.split("");e=t.map((e=>e.normalize("NFKC"))).join("")}else e=e.normalize("NFKC");return e}}class $n extends un{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>un.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,s)=>s.pre_tokenize(e,t)),[e])}}class Nn extends un{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class Dn extends un{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class Vn extends un{constructor(e){super(),this.config=e,this.pattern=zs(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const jn=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Un(e,t,s,n){for(const a of Object.keys(e)){const r=t-e[a].length,o=s(a),i=new Array(r).fill(o);e[a]="right"===n?P(e[a],i):P(i,e[a])}}function Rn(e,t){for(const s of Object.keys(e))e[s].length=t}class qn extends C{return_token_type_ids=!1;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=Qs.fromConfig(e.normalizer),this.pre_tokenizer=un.fromConfig(e.pre_tokenizer),this.model=Rs.fromConfig(e.model,t),this.post_processor=gn.fromConfig(e.post_processor),this.decoder=vn.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new Us(t);this.added_tokens.push(e),this.model.tokens_to_ids.set(e.content,e.id),this.model.vocab[e.id]=e.content,e.special&&(this.special_tokens.push(e.content),this.all_special_ids.push(e.id))}if(this.additional_special_tokens=t.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new gt(this.added_tokens.map((e=>e.content))),this.added_tokens_map=new Map(this.added_tokens.map((e=>[e.content,e]))),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:s}of this.chat_template){if("string"!=typeof t||"string"!=typeof s)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=s}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(e){if("object"==typeof e){if("AddedToken"===e.__type)return e.content;throw Error(`Unknown token: ${e}`)}return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:r="main",legacy:o=null}={}){return new this(...await Ps(e,{progress_callback:t,config:s,cache_dir:n,local_files_only:a,revision:r,legacy:o}))}_call(e,{text_pair:t=null,add_special_tokens:s=!0,padding:n=!1,truncation:a=null,max_length:r=null,return_tensor:o=!0,return_token_type_ids:i=null}={}){const l=Array.isArray(e);let c;if(l){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(!Array.isArray(t))throw Error("text_pair must also be an array");if(e.length!==t.length)throw Error("text and text_pair must have the same length");c=e.map(((e,n)=>this._encode_plus(e,{text_pair:t[n],add_special_tokens:s,return_token_type_ids:i})))}else c=e.map((e=>this._encode_plus(e,{add_special_tokens:s,return_token_type_ids:i})))}else{if(null==e)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:i})]}if(null===r?r=this.model_max_length:null===a&&(!0===n?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),r=this.model_max_length):!1===n&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),a=!0)),!0===n&&(r=Math.min(re(c.map((e=>e.input_ids.length)))[0],r??1/0)),r=Math.min(r,this.model_max_length??1/0),n||a)for(let e=0;e<c.length;++e)c[e].input_ids.length!==r&&(c[e].input_ids.length>r?a&&Rn(c[e],r):n&&Un(c[e],r,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const d={};if(o){if((!n||!a)&&c.some((e=>{for(const t of Object.keys(e))if(e[t].length!==c[0][t]?.length)return!0;return!1})))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const e=[c.length,c[0].input_ids.length];for(const t of Object.keys(c[0]))d[t]=new Ne("int64",BigInt64Array.from(c.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(c[0]))d[e]=c.map((t=>t[e]));if(!l)for(const e of Object.keys(d))d[e]=d[e][0]}return d}_encode_text(e){if(null===e)return null;const t=this.added_tokens_splitter.split(e);for(let e=0;e<t.length;++e){const s=this.added_tokens_map.get(t[e]);s&&(s.lstrip&&e>0&&(t[e-1]=t[e-1].trimEnd()),s.rstrip&&e<t.length-1&&(t[e+1]=t[e+1].trimStart()))}const s=t.flatMap(((e,t)=>{if(0===e.length)return[];if(this.added_tokens_map.has(e))return[e];if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=function(e){return Os(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const s=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(s)}));return s}_encode_plus(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){const{tokens:a,token_type_ids:r}=this._tokenize_helper(e,{pair:t,add_special_tokens:s}),o=this.model.convert_tokens_to_ids(a),i={input_ids:o,attention_mask:new Array(o.length).fill(1)};return(n??this.return_token_type_ids)&&r&&(i.token_type_ids=r),i}_tokenize_helper(e,{pair:t=null,add_special_tokens:s=!1}={}){const n=this._encode_text(e),a=this._encode_text(t);return this.post_processor?this.post_processor(n,a,{add_special_tokens:s}):{tokens:P(n??[],a??[])}}tokenize(e,{pair:t=null,add_special_tokens:s=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:s}).tokens}encode(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:n}).input_ids}batch_decode(e,t={}){return e instanceof Ne&&(e=e.tolist()),e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof Ne&&(e=Ls(e)),!Array.isArray(e)||0===e.length||(s=e[0],!Number.isInteger(s)&&"bigint"!=typeof s))throw Error("token_ids must be a non-empty array of integers.");var s;return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:s=null}){let n=this.model.convert_ids_to_tokens(e);t&&(n=n.filter((e=>!this.special_tokens.includes(e))));let a=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(a=a.replaceAll(this.decoder.end_of_word_suffix," "),t&&(a=a.trim())),(s??this.clean_up_tokenization_spaces)&&(a=Bs(a)),a}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){const s=this.chat_template;if(null!==e&&Object.hasOwn(s,e))e=s[e];else if(null===e)if(null!==t&&"tool_use"in s)e=s.tool_use;else{if(!("default"in s))throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`);e=s.default}}else if(null===e){if(!this.chat_template)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");e=this.chat_template}return e}apply_chat_template(e,{tools:t=null,documents:s=null,chat_template:n=null,add_generation_prompt:a=!1,tokenize:r=!0,padding:o=!1,truncation:i=!1,max_length:l=null,return_tensor:c=!0,return_dict:d=!1,tokenizer_kwargs:u={},...h}={}){if("string"!=typeof(n=this.get_chat_template({chat_template:n,tools:t})))throw Error("chat_template must be a string, but got "+typeof n);let _=this._compiled_template_cache.get(n);void 0===_&&(_=new Cs(n),this._compiled_template_cache.set(n,_));const p=Object.create(null);for(const e of jn){const t=this.getToken(e);t&&(p[e]=t)}const m=_.render({messages:e,add_generation_prompt:a,tools:t,documents:s,...p,...h});if(r){const e=this._call(m,{add_special_tokens:!1,padding:o,truncation:i,max_length:l,return_tensor:c,...u});return d?e:e.input_ids}return m}}class Gn extends qn{return_token_type_ids=!0}class Wn extends qn{return_token_type_ids=!0}class Xn extends qn{return_token_type_ids=!0}class Hn extends qn{return_token_type_ids=!0}class Jn extends qn{return_token_type_ids=!0}class Kn extends qn{return_token_type_ids=!0}class Qn extends qn{return_token_type_ids=!0}class Zn extends qn{return_token_type_ids=!0}class Yn extends qn{return_token_type_ids=!0}class ea extends qn{}class ta extends qn{}class sa extends qn{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class na extends qn{return_token_type_ids=!0}class aa extends qn{}class ra extends qn{}class oa extends qn{}class ia extends qn{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,s){return ka(this,e,t,s)}}class la extends ia{}class ca extends qn{}class da extends qn{}const ua="";class ha extends qn{padding_side="left";constructor(e,t){super(e,t),this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Ln({replacement:ua,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(null===e)return null;if(this.legacy||0===e.length)return super._encode_text(e);let t=super._encode_text(ua+e.replaceAll(ua," "));return t.length>1&&t[0]===ua&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}}class _a extends qn{}class pa extends qn{}class ma extends qn{}class fa extends qn{}class ga extends qn{}class wa extends qn{}class ya extends qn{}class xa extends qn{}class ba extends qn{}function ka(e,t,s,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)||"function"!=typeof e.lang_to_token)throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const a=n.src_lang,r=n.tgt_lang;if(!e.language_codes.includes(r))throw new Error(`Target language code "${r}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==a){if(!e.language_codes.includes(a))throw new Error(`Source language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(a);break}}return n.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(r)])[0],e._call(t,s)}class va extends qn{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,s){return ka(this,e,t,s)}}class Ma extends qn{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2))),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,s){return ka(this,e,t,s)}}class Ea extends qn{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:a=!0}={}){if(null===n)throw Error("Must specify time_precision");let r=null;const o="word"===t;function i(){return{language:r,timestamp:[null,null],text:""}}const l=[];let c=i(),d=0;const u=this.timestamp_begin,h=u+1500;let _=[],p=[],m=!1,f=null;const g=new Set(this.all_special_ids);for(const s of e){const e=s.tokens,a=o?s.token_timestamps:null;let w=null,y=u;if("stride"in s){const[t,a,r]=s.stride;if(d-=a,f=t-r,a&&(y=a/n+u),r)for(let t=e.length-1;t>=0;--t){const s=Number(e[t]);if(s>=u){if(null!==w&&(s-u)*n<f)break;w=s}}}let x=[],b=[];for(let s=0;s<e.length;++s){const f=Number(e[s]);if(g.has(f)){const e=this.decode([f]),s=Fs.get(e.slice(2,-2));if(void 0!==s){if(null!==r&&s!==r&&!t){_.push(x);const e=this.findLongestCommonSequence(_)[0],t=this.decode(e);c.text=t,l.push(c),_=[],x=[],c=i()}r=c.language=s}}else if(f>=u&&f<=h){const e=ue((f-u)*n+d,2);if(null!==w&&f>=w)m=!0;else if(m||_.length>0&&f<y)m=!1;else if(null===c.timestamp[0])c.timestamp[0]=e;else if(e===c.timestamp[0]);else{c.timestamp[1]=e,_.push(x),o&&p.push(b);const[t,s]=this.findLongestCommonSequence(_,p),n=this.decode(t);c.text=n,o&&(c.words=this.collateWordTimestamps(t,s,r)),l.push(c),_=[],x=[],p=[],b=[],c=i()}}else if(x.push(f),o){let e,t=ue(a[s]+d,2);if(s+1<a.length){e=ue(a[s+1]+d,2);const r=this.decode([f]);Ds.test(r)&&(e=ue(Math.min(t+n,e),2))}else e=null;b.push([t,e])}}if("stride"in s){const[e,t,n]=s.stride;d+=e-n}x.length>0?(_.push(x),o&&p.push(b)):_.every((e=>0===e.length))&&(c=i(),_=[],x=[],p=[],b=[])}if(_.length>0){if(a&&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[e,s]=this.findLongestCommonSequence(_,p),n=this.decode(e);c.text=n,o&&(c.words=this.collateWordTimestamps(e,s,r)),l.push(c)}let w=Object.create(null);const y=l.map((e=>e.text)).join("");if(t||s){for(let e=0;e<l.length;++e){const n=l[e];t||delete n.timestamp,s||delete n.language}if(o){const e=[];for(const t of l)for(const s of t.words)e.push(s);w={chunks:e}}else w={chunks:l}}return[y,w]}findLongestCommonSequence(e,t=null){let s=e[0],n=s.length,a=[];const r=Array.isArray(t)&&t.length>0;let o=r?[]:null,i=r?t[0]:null;for(let l=1;l<e.length;++l){const c=e[l];let d=0,u=[n,n,0,0];const h=c.length;for(let e=1;e<n+h;++e){const a=Math.max(0,n-e),o=Math.min(n,n+h-e),_=s.slice(a,o),p=Math.max(0,e-n),m=Math.min(h,e),f=c.slice(p,m);if(_.length!==f.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let g;g=r?_.filter(((e,s)=>e===f[s]&&i[a+s]<=t[l][p+s])).length:_.filter(((e,t)=>e===f[t])).length;const w=g/e+e/1e4;g>1&&w>d&&(d=w,u=[a,o,p,m])}const[_,p,m,f]=u,g=Math.floor((p+_)/2),w=Math.floor((f+m)/2);a.push(...s.slice(0,g)),s=c.slice(w),n=s.length,r&&(o.push(...i.slice(0,g)),i=t[l].slice(w))}return a.push(...s),r?(o.push(...i),[a,o]):[a,[]]}collateWordTimestamps(e,t,s){const[n,a,r]=this.combineTokensIntoWords(e,s),o=[];for(let e=0;e<n.length;++e){const s=r[e];o.push({text:n[e],timestamp:[t[s.at(0)][0],t[s.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,s="\"'¡¿([{-",n="\"'.,!?:)]}"){let a,r,o;return["chinese","japanese","thai","lao","myanmar"].includes(t=t??"english")?[a,r,o]=this.splitTokensOnUnicode(e):[a,r,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(a,r,o,s,n)}decode(e,t){let s;return t?.decode_with_timestamps?(e instanceof Ne&&(e=Ls(e)),s=this.decodeWithTimestamps(e,t)):s=super.decode(e,t),s}decodeWithTimestamps(e,t){const s=t?.time_precision??.02,n=Array.from(this.all_special_ids).at(-1)+1;let a=[[]];for(let t of e)if(t=Number(t),t>=n){const e=((t-n)*s).toFixed(2);a.push(`<|${e}|>`),a.push([])}else a[a.length-1].push(t);return a=a.map((e=>"string"==typeof e?e:super.decode(e,t))),a.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),s=[],n=[],a=[];let r=[],o=[],i=0;for(let l=0;l<e.length;++l){const c=e[l];r.push(c),o.push(l);const d=this.decode(r,{decode_with_timestamps:!0});d.includes("<EFBFBD>")&&"<EFBFBD>"!==t[i+d.indexOf("<EFBFBD>")]||(s.push(d),n.push(r),a.push(o),r=[],o=[],i+=d.length)}return[s,n,a]}splitTokensOnSpaces(e){const[t,s,n]=this.splitTokensOnUnicode(e),a=[],r=[],o=[],i=new RegExp(`^[${Ns}]$`,"gu");for(let e=0;e<t.length;++e){const l=t[e],c=s[e],d=n[e],u=c[0]>=this.model.tokens_to_ids.get("<|endoftext|>"),h=l.startsWith(" "),_=l.trim(),p=i.test(_);if(u||h||p||0===a.length)a.push(l),r.push(c),o.push(d);else{const e=a.length-1;a[e]+=l,r[e].push(...c),o[e].push(...d)}}return[a,r,o]}mergePunctuations(e,t,s,n,a){const r=structuredClone(e),o=structuredClone(t),i=structuredClone(s);let l=r.length-2,c=r.length-1;for(;l>=0;)r[l].startsWith(" ")&&n.includes(r[l].trim())?(r[c]=r[l]+r[c],o[c]=P(o[l],o[c]),i[c]=P(i[l],i[c]),r[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<r.length;)!r[l].endsWith(" ")&&a.includes(r[c])?(r[l]+=r[c],o[l]=P(o[l],o[c]),i[l]=P(i[l],i[c]),r[c]="",o[c]=[],i[c]=[]):l=c,++c;return[r.filter((e=>e)),o.filter((e=>e.length>0)),i.filter((e=>e.length>0))]}}class Aa extends qn{}class Ca extends qn{}class Ta extends qn{}class Fa extends qn{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter((e=>this.languageRegex.test(e))),console.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(null===e)return null;const[t,...s]=e.trim().split(this.languageRegex);if(0===s.length)return super._encode_text(t);if(2===s.length){const[e,t]=s;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),P([e],super._encode_text(t))}}}class Sa extends qn{}class Pa extends qn{}class za extends qn{}class Ia extends qn{}class La extends qn{}class Ba extends qn{constructor(e,t){super(e,t),this.decoder=new In({})}}class Oa extends qn{}class $a extends qn{}class Na{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:aa,DistilBertTokenizer:ea,CamembertTokenizer:ta,DebertaTokenizer:Jn,DebertaV2Tokenizer:Kn,BertTokenizer:Gn,HerbertTokenizer:Qn,ConvBertTokenizer:Zn,RoFormerTokenizer:Yn,XLMTokenizer:sa,ElectraTokenizer:na,MobileBertTokenizer:Xn,SqueezeBertTokenizer:Hn,AlbertTokenizer:Wn,GPT2Tokenizer:ra,BartTokenizer:oa,MBartTokenizer:ia,MBart50Tokenizer:la,RobertaTokenizer:ca,WhisperTokenizer:Ea,CodeGenTokenizer:Aa,CLIPTokenizer:Ca,SiglipTokenizer:Ta,MarianTokenizer:Fa,BloomTokenizer:da,NllbTokenizer:va,M2M100Tokenizer:Ma,LlamaTokenizer:ha,CodeLlamaTokenizer:_a,XLMRobertaTokenizer:pa,MPNetTokenizer:ma,FalconTokenizer:fa,GPTNeoXTokenizer:ga,EsmTokenizer:wa,Wav2Vec2CTCTokenizer:Sa,BlenderbotTokenizer:Pa,BlenderbotSmallTokenizer:za,SpeechT5Tokenizer:Ia,NougatTokenizer:La,VitsTokenizer:Ba,Qwen2Tokenizer:ya,GemmaTokenizer:xa,Grok1Tokenizer:ba,CohereTokenizer:Oa,MgpstrTokenizer:$a,PreTrainedTokenizer:qn};static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:r="main",legacy:o=null}={}){const[i,l]=await Ps(e,{progress_callback:t,config:s,cache_dir:n,local_files_only:a,revision:r,legacy:o}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let d=this.TOKENIZER_CLASS_MAPPING[c];return d||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),d=qn),new d(i,l)}}function Da(e){const t={};let s={};switch(e.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":s=Da(e.text_config);break;case"moondream1":s=Da(e.phi_config);break;case"musicgen":s=Da(e.decoder);break;case"multi_modality":s=Da(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const n=Da(e.decoder),a="num_decoder_layers"in n,r=B(e,["model_type","is_encoder_decoder"]);return a?(r.num_decoder_layers=n.num_decoder_layers,r.num_decoder_heads=n.num_decoder_heads,r.decoder_hidden_size=n.decoder_hidden_size,r.num_encoder_layers=n.num_encoder_layers,r.num_encoder_heads=n.num_encoder_heads,r.encoder_hidden_size=n.encoder_hidden_size):(r.num_layers=n.num_layers,r.num_heads=n.num_heads,r.hidden_size=n.hidden_size),r}const n={...s,...B(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function Va(e,{prefix:t="past_key_values",batch_size:s=1}={}){const n={},a=e.normalized_config;if(a.is_encoder_decoder&&"num_encoder_heads"in a&&"num_decoder_heads"in a){const e=a.encoder_dim_kv??a.encoder_hidden_size/a.num_encoder_heads,r=a.decoder_dim_kv??a.decoder_hidden_size/a.num_decoder_heads,o=[s,a.num_encoder_heads,0,e],i=[s,a.num_decoder_heads,0,r];for(let e=0;e<a.num_decoder_layers;++e)n[`${t}.${e}.encoder.key`]=o,n[`${t}.${e}.encoder.value`]=o,n[`${t}.${e}.decoder.key`]=i,n[`${t}.${e}.decoder.value`]=i}else{const e=a.num_heads,r=a.num_layers,o=a.dim_kv??a.hidden_size/(a.num_attention_heads??e);if("falcon"===a.model_type){const a=[s*e,0,o];for(let e=0;e<r;++e)n[`${t}.${e}.key`]=a,n[`${t}.${e}.value`]=a}else if(a.multi_query){const a=[s*e,0,2*o];for(let e=0;e<r;++e)n[`${t}.${e}.key_value`]=a}else if("bloom"===a.model_type){const a=[s*e,o,0],i=[s*e,0,o];for(let e=0;e<r;++e)n[`${t}.${e}.key`]=a,n[`${t}.${e}.value`]=i}else if("openelm"===a.model_type)for(let a=0;a<r;++a){const r=[s,e[a],0,o];n[`${t}.${a}.key`]=r,n[`${t}.${a}.value`]=r}else{const a=[s,e,0,o];for(let e=0;e<r;++e)n[`${t}.${e}.key`]=a,n[`${t}.${e}.value`]=a}}return n}class ja{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=Da(this)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:r="main"}={}){!s||s instanceof ja||(s=new ja(s));const o=s??await async function(e,t){return await J(e,"config.json",!0,t)}(e,{progress_callback:t,config:s,cache_dir:n,local_files_only:a,revision:r});return new this(o)}}class Ua{static async from_pretrained(...e){return ja.from_pretrained(...e)}}const Ra=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),qa=function(){let e;return async function(){if(void 0===e)if(x.IS_WEBGPU_AVAILABLE)try{const t=await navigator.gpu.requestAdapter();e=t.features.has("shader-f16")}catch(t){e=!1}else e=!1;return e}}(),Ga=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Wa=Object.freeze({[Ra.wasm]:Ga.q8}),Xa=Object.freeze({[Ga.fp32]:"",[Ga.fp16]:"_fp16",[Ga.int8]:"_int8",[Ga.uint8]:"_uint8",[Ga.q8]:"_quantized",[Ga.q4]:"_q4",[Ga.q4f16]:"_q4f16",[Ga.bnb4]:"_bnb4"}),Ha="https://github.com/huggingface/transformers.js/issues/new/choose",Ja="preprocessor_config.json",Ka=Ja;class Qa extends C{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class Za extends C{_call(e,t){throw Error("`_call` should be implemented in a subclass")}}class Ya extends C{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let s=t;for(const t of this.processors)s=t(e,s);return s}[Symbol.iterator](){return this.processors.values()}}class er extends Qa{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let s=0;s<e.length;++s)if(1===e[s].length){const e=t[s].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}}class tr extends Qa{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){const e=t[s].data;e.fill(-1/0);for(const t of this.eos_token_id)e[t]=0}return t}}class sr extends Qa{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){const e=t[s].data;for(const t of this.begin_suppress_tokens)e[t]=-1/0}return t}}class nr extends Qa{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let s=0;s<e.length;++s){const n=t[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}const a=e[s].slice(this.begin_index),r=a.length>=1&&a[a.length-1]>=this.timestamp_begin,o=a.length<2||a[a.length-2]>=this.timestamp_begin;if(r&&(o?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&null!==this.max_initial_timestamp_index){const e=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(e+1).fill(-1/0)}const i=ee(n);Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce(((e,t)=>e+t)))>re(i.subarray(0,this.timestamp_begin))[0]&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}}class ar extends Qa{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,s=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){const t=[];for(let s=0;s<this.no_repeat_ngram_size;++s)t.push(e[n+s]);s.push(t.map(Number))}const n=new Map;for(const e of s){const t=e.slice(0,e.length-1),s=JSON.stringify(t),a=n.get(s)??[];a.push(e[e.length-1]),n.set(s,a)}return n}getGeneratedNgrams(e,t){const s=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let s=0;s<e.length;++s){const n=t[s].data,a=this.calcBannedNgramTokens(e[s]);for(const e of a)n[e]=-1/0}return t}}class rr extends Qa{constructor(e){super(),this.penalty=e}_call(e,t){for(let s=0;s<e.length;++s){const n=t[s].data;for(const t of new Set(e[s])){const e=Number(t);n[e]<0?n[e]*=this.penalty:n[e]/=this.penalty}}return t}}class or extends Qa{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}return t}}class ir extends Qa{constructor(e,t,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,t){for(let s=0;s<e.length;++s){if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){const e=t[s].data;for(const t of this.eos_token_id)e[t]=-1/0}}return t}}class lr extends Qa{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s){const n=t[s].data,a=e[s];for(const e of this.bad_words_ids){if(a.length<e.length-1)continue;let t=!0;for(let s=1;s<=e.length-1;++s)if(e.at(-s-1)!=a.at(-s)){t=!1;break}t&&(n[e.at(-1)]=-1/0)}}return t}}class cr extends Qa{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const s=e.length,n=t.slice([0,s],null),a=t.slice([s,t.dims[0]],null);for(let e=0;e<a.data.length;++e)a.data[e]+=(n.data[e]-a.data[e])*this.guidance_scale;return a}}class dr extends Za{constructor(e){if(super(),"number"!=typeof e||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;0===e&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){const s=t.data;for(let e=0;e<s.length;++e)s[e]/=this.temperature;return t}}class ur extends Za{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=s}}class hr extends Za{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=t}}class _r{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,B(e,Object.getOwnPropertyNames(this)))}}var pr=n(836);let mr,fr,gr;const wr=x.IS_BROWSER_ENV||x.IS_WEBWORKER_ENV;if(wr)mr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},gr=self.createImageBitmap,fr=self.ImageData;else{if(!pr)throw new Error("Unable to load image processing library.");gr=async e=>{const t=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new br(new Uint8ClampedArray(s),n.width,n.height,n.channels);return void 0!==t&&t!==n.channels&&a.convert(t),a}}const yr={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},xr=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class br{constructor(e,t,s,n){this.data=e,this.width=t,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof br)return e;if("string"==typeof e||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error("Unsupported input type: "+typeof e)}static fromCanvas(e){if(!wr)throw new Error("fromCanvas() is only supported in browser environments.");const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new br(t,e.width,e.height,4)}static async fromURL(e){const t=await G(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const s=await t.blob();return this.fromBlob(s)}static async fromBlob(e){if(wr){const t=await gr(e),s=mr(t.width,t.height).getContext("2d");return s.drawImage(t,0,0),new this(s.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=pr(await e.arrayBuffer());return await gr(t)}}static fromTensor(e,t="CHW"){if(3!==e.dims.length)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if("CHW"===t)e=e.transpose(1,2,0);else if("HWC"!==t)throw new Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new br(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(1===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,s=0;t<this.data.length;t+=this.channels){const n=this.data[t],a=this.data[t+1],r=this.data[t+2];e[s++]=Math.round(.2989*n+.587*a+.114*r)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(3===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t];break;case 4:for(let t=0,s=0;t<this.data.length;t+=4)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(4===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=255;break;case 3:for(let t=0,s=0;t<this.data.length;t+=3)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(1!==e.channels)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);const t=this.data,s=e.data,n=this.width*this.height;if(3===this.channels){const e=new Uint8ClampedArray(4*n);for(let a=0,r=0,o=0;a<n;++a)e[o++]=t[r++],e[o++]=t[r++],e[o++]=t[r++],e[o++]=s[a];return this._update(e,this.width,this.height,4)}if(4===this.channels){for(let e=0;e<n;++e)t[4*e+3]=s[e];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,t,{resample:s=2}={}){if(this.width===e&&this.height===t)return this;let n=yr[s]??s;const a=F(e),r=F(t);if(a&&r)return this;if(a?e=t/this.height*this.width:r&&(t=e/this.width*this.height),wr){const s=this.channels,n=this.toCanvas(),a=mr(e,t).getContext("2d");a.drawImage(n,0,0,e,t);return new br(a.getImageData(0,0,e,t).data,e,t,4).convert(s)}{let s=this.toSharp();switch(n){case"box":case"hamming":"box"!==n&&"hamming"!==n||(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":s=s.affine([e/this.width,0,0,t/this.height],{interpolator:n});break;case"lanczos":s=s.resize({width:e,height:t,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await gr(s)}}async pad([e,t,s,n]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.max(s,0),n=Math.max(n,0),0===e&&0===t&&0===s&&0===n)return this;if(wr){const a=this.channels,r=this.toCanvas(),o=this.width+e+t,i=this.height+s+n,l=mr(o,i).getContext("2d");l.drawImage(r,0,0,this.width,this.height,e,s,this.width,this.height);return new br(l.getImageData(0,0,o,i).data,o,i,4).convert(a)}{const a=this.toSharp().extend({left:e,right:t,top:s,bottom:n});return await gr(a)}}async crop([e,t,s,n]){if(e=Math.max(e,0),t=Math.max(t,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),0===e&&0===t&&s===this.width-1&&n===this.height-1)return this;const a=s-e+1,r=n-t+1;if(wr){const s=this.channels,n=this.toCanvas(),o=mr(a,r).getContext("2d");o.drawImage(n,e,t,a,r,0,0,a,r);return new br(o.getImageData(0,0,a,r).data,a,r,4).convert(s)}{const s=this.toSharp().extract({left:e,top:t,width:a,height:r});return await gr(s)}}async center_crop(e,t){if(this.width===e&&this.height===t)return this;const s=(this.width-e)/2,n=(this.height-t)/2;if(wr){const a=this.channels,r=this.toCanvas(),o=mr(e,t).getContext("2d");let i=0,l=0,c=0,d=0;s>=0?i=s:c=-s,n>=0?l=n:d=-n,o.drawImage(r,i,l,e,t,c,d,e,t);return new br(o.getImageData(0,0,e,t).data,e,t,4).convert(a)}{let a=this.toSharp();if(s>=0&&n>=0)a=a.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:t});else if(s<=0&&n<=0){const r=Math.floor(-n),o=Math.floor(-s);a=a.extend({top:r,left:o,right:e-this.width-o,bottom:t-this.height-r})}else{let r=[0,0],o=0;n<0?(r[0]=Math.floor(-n),r[1]=t-this.height-r[0]):o=Math.floor(n);let i=[0,0],l=0;s<0?(i[0]=Math.floor(-s),i[1]=e-this.width-i[0]):l=Math.floor(s),a=a.extend({top:r[0],bottom:r[1],left:i[0],right:i[1]}).extract({left:l,top:o,width:e,height:t})}return await gr(a)}}async toBlob(e="image/png",t=1){if(!wr)throw new Error("toBlob() is only supported in browser environments.");const s=this.toCanvas();return await s.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new Ne("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if("HWC"===e);else{if("CHW"!==e)throw new Error(`Unsupported channel format: ${e}`);t=t.permute(2,0,1)}return t}toCanvas(){if(!wr)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=mr(e.width,e.height),s=new fr(e.data,e.width,e.height);return t.getContext("2d").putImageData(s,0,0),t}split(){const{data:e,width:t,height:s,channels:n}=this,a=e.constructor,r=e.length/n,o=Array.from({length:n},(()=>new a(r)));for(let t=0;t<r;++t){const s=n*t;for(let a=0;a<n;++a)o[a][t]=e[s+a]}return o.map((e=>new br(e,t,s,1)))}_update(e,t,s,n=null){return this.data=e,this.width=t,this.height=s,null!==n&&(this.channels=n),this}clone(){return new br(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(!wr){if(x.IS_FS_AVAILABLE){const t=this.toSharp();return await t.toFile(e)}throw new Error("Unable to save the image because filesystem is disabled in this environment.")}{if(x.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),s=xr.get(t)??"image/png";L(e,await this.toBlob(s))}}toSharp(){if(wr)throw new Error("toSharp() is only supported in server-side environments.");return pr(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const kr=br.read.bind(br);class vr extends C{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}}class Mr extends C{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof Mr?e=e.criteria:e instanceof vr&&(e=[e]),this.criteria.push(...e)}_call(e,t){const s=new Array(e.length).fill(!1);for(const n of this.criteria){const a=n(e,t);for(let e=0;e<s.length;++e)s[e]||=a[e]}return s}[Symbol.iterator](){return this.criteria.values()}}class Er extends vr{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map((e=>e.length>=this.max_length))}}class Ar extends vr{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map((e=>{const t=e.at(-1);return this.eos_token_id.some((e=>t==e))}))}}class Cr extends vr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}}class Tr extends C{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 s=e.dims.at(-1),n=e.data;if(-1===t)n=n.slice(-s);else{let e=t*s;n=n.slice(e,e+s)}return n}randomSelect(e){let t=0;for(let s=0;s<e.length;++s)t+=e[s];let s=Math.random()*t;for(let t=0;t<e.length;++t)if(s-=e[t],s<=0)return t;return 0}static getSampler(e){if(e.do_sample)return new Sr(e);if(e.num_beams>1)return new Pr(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 Fr(e)}}class Fr extends Tr{async sample(e){const t=re(e.data)[1];return[[BigInt(t),0]]}}class Sr extends Tr{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[s,n]=await qe(e,t),a=Y(s.data);return Array.from({length:this.generation_config.num_beams},(()=>{const e=this.randomSelect(a);return[n.data[e],Math.log(a[e])]}))}}class Pr extends Tr{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[s,n]=await qe(e,t),a=Y(s.data);return Array.from({length:this.generation_config.num_beams},((e,t)=>[n.data[t],Math.log(a[t])]))}}class zr extends _r{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}const Ir=0,Lr=1,Br=2,Or=3,$r=4,Nr=5,Dr=6,Vr=7,jr=8,Ur=9,Rr=10,qr=11,Gr=new Map,Wr=new Map,Xr=new Map;async function Hr(e,t,s){let n=s.config?.["transformers.js_config"]??{},a=s.device??n.device;a&&"string"!=typeof a&&(a.hasOwnProperty(t)?a=a[t]:(console.warn(`device not specified for "${t}". Using the default device.`),a=null));const r=a??(x.IS_NODE_ENV?"cpu":"wasm"),o=function(e=null){if(!e)return Ee;switch(e){case"auto":return Me;case"gpu":return Me.filter((e=>["webgpu","cuda","dml","webnn-gpu"].includes(e)))}if(Me.includes(e))return[ve[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Me.join(", ")}.`)}(r),i=n.device_config??{};i.hasOwnProperty(r)&&(n={...n,...i[r]});let l=s.dtype??n.dtype;if("string"!=typeof l&&(l&&l.hasOwnProperty(t)?l=l[t]:(l=Wa[r]??Ga.fp32,console.warn(`dtype not specified for "${t}". Using the default dtype (${l}) for this device (${r}).`))),l===Ga.auto){let e=n.dtype;"string"!=typeof e&&(e=e?.[t]),l=e&&e!==Ga.auto&&Ga.hasOwnProperty(e)?e:Wa[r]??Ga.fp32}const c=l;if(!Xa.hasOwnProperty(c))throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(Ga).join(", ")}`);if(c===Ga.fp16&&"webgpu"===r&&!await qa())throw new Error(`The device (${r}) does not support fp16.`);const d=n.kv_cache_dtype,u=d?"string"==typeof d?d:d[c]??"float32":void 0;if(u&&!["float32","float16"].includes(u))throw new Error(`Invalid kv_cache_dtype: ${u}. Should be one of: float32, float16`);const h={dtype:c,kv_cache_dtype:u,device:r},_=`${t}${Xa[c]}.onnx`,p=`${s.subfolder??""}/${_}`,m={...s.session_options};m.executionProviders??=o;const f=n.free_dimension_overrides;f?m.freeDimensionOverrides??=f:r.startsWith("webnn")&&!m.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${r}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const g=x.IS_NODE_ENV&&E.useFSCache,w=H(e,p,!0,s,g),y=s.use_external_data_format??n.use_external_data_format;let b=[];if(y){let n;n="object"==typeof y?y.hasOwnProperty(_)?y[_]:!!y.hasOwnProperty(t)&&y[t]:y;const a=+n;if(a>V)throw new Error(`The number of external data chunks (${a}) exceeds the maximum allowed value (${V}).`);for(let t=0;t<a;++t){const n=`${_}_data${0===t?"":"_"+t}`,a=`${s.subfolder??""}/${n}`;b.push(new Promise((async(t,r)=>{const o=await H(e,a,!0,s,g);t(o instanceof Uint8Array?{path:n,data:o}:n)})))}}else void 0!==m.externalData&&(b=m.externalData.map((async t=>{if("string"==typeof t.data){const n=await H(e,t.data,!0,s);return{...t,data:n}}return t})));if(b.length>0){const e=await Promise.all(b);x.IS_NODE_ENV||(m.externalData=e)}if("webgpu"===r){const e=Va(s.config,{prefix:"present"});if(Object.keys(e).length>0&&!Ie()){const t={};for(const s in e)t[s]="gpu-buffer";m.preferredOutputLocation=t}}return{buffer_or_path:await w,session_options:m,session_config:h}}async function Jr(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async n=>{const{buffer_or_path:a,session_options:r,session_config:o}=await Hr(e,t[n],s);return[n,await Se(a,r,o)]}))))}async function Kr(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map((async n=>[n,await J(e,t[n],!1,s)]))))}let Qr=Promise.resolve();async function Zr(e,t){const s=function(e,t){const s=Object.create(null),n=[];for(const a of e.inputNames){const e=t[a];e instanceof Ne?s[a]=Ie()?e.clone():e:n.push(a)}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const a=Object.keys(t).length,r=e.inputNames.length;if(a>r){let s=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${a} > ${r}). The following inputs will be ignored: "${s.join(", ")}".`)}return s}(e,t);try{const t=Object.fromEntries(Object.entries(s).map((([e,t])=>[e,t.ort_tensor]))),n=()=>e.run(t);return Yr(await(x.IS_BROWSER_ENV||x.IS_WEBWORKER_ENV?Qr=Qr.then(n):n()))}catch(e){const t=Object.fromEntries(Object.entries(s).map((([e,t])=>{const s={type:t.type,dims:t.dims,location:t.location};return"gpu-buffer"!==s.location&&(s.data=t.data),[e,s]})));throw console.error(`An error occurred during model execution: "${e}".`),console.error("Inputs given to model:",t),e}}function Yr(e){for(let t in e)Pe(e[t])?e[t]=new Ne(e[t]):"object"==typeof e[t]&&Yr(e[t]);return e}function eo(e){if(e instanceof Ne)return e;if(0===e.length)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 Ne("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new Ne("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}function to(e){return new Ne("bool",[e],[1])}async function so(e,t){let{encoder_outputs:s,input_ids:n,decoder_input_ids:a,...r}=t;if(!s){const n=B(t,e.sessions.model.inputNames);s=(await no(e,n)).last_hidden_state}r.input_ids=a,r.encoder_hidden_states=s,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(r.encoder_attention_mask=t.attention_mask);return await ro(e,r,!0)}async function no(e,t){const s=e.sessions.model,n=B(t,s.inputNames);if(s.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(s.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=ct(n.input_ids)}if(s.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 e=n.pixel_values.dims;n.pixel_mask=ot([e[0],e[2],e[3]])}return await Zr(s,n)}async function ao(e,t){const s=await e.encode(t);return await e.decode(s)}async function ro(e,t,s=!1){const n=e.sessions[s?"decoder_model_merged":"model"],{past_key_values:a,...r}=t;if(n.inputNames.includes("use_cache_branch")&&(r.use_cache_branch=to(!!a)),n.inputNames.includes("position_ids")&&r.attention_mask&&!r.position_ids){const t=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;r.position_ids=function(e,t=null,s=0){const{input_ids:n,inputs_embeds:a,attention_mask:r}=e,{data:o,dims:i}=ho(r,s);let l=new Ne("int64",o,i);if(t){const e=-(n??a).dims.at(1);l=l.slice(null,[e,null])}return l}(r,a,t)}e.addPastKeyValues(r,a);const o=B(r,n.inputNames);return await Zr(n,o)}function oo({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:a}){const r=n.tolist().map((t=>t.reduce(((t,s,n)=>(s==e&&t.push(n),t)),[]))),o=r.reduce(((e,t)=>e+t.length),0),i=s.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 e=0;e<r.length;++e){const n=r[e],a=t[e];for(let e=0;e<n.length;++e)a[n[e]].data.set(s[l++].data)}return{inputs_embeds:t,attention_mask:a}}function io({image_token_id:e,inputs_embeds:t,image_features:s,input_ids:n,attention_mask:a}){return oo({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:a})}async function lo(e,{encode_function:t,merge_function:s,modality_input_name:n,modality_output_name:a,input_ids:r=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:u=null,...h}){const _=h[n];if(!l)if(l=await e.encode_text({input_ids:r,...h}),_&&1!==r.dims[1]){const e=await t({[n]:_,...h});({inputs_embeds:l,attention_mask:o}=s({[a]:e,inputs_embeds:l,input_ids:r,attention_mask:o}))}else if(c&&_&&1===r.dims[1]){const e=r.dims[1],t=Object.values(c)[0].dims.at(-2);o=Ze([ot([r.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}if(!i&&"qwen2_vl"===e.config.model_type){const{image_grid_thw:t,video_grid_thw:s}=h;[i]=e.get_rope_index(r,t,s,o)}return await ro(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:u},!0)}async function co(e,t){return await lo(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 uo(e,t){return await lo(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 ho(e,t=0){const[s,n]=e.dims,a=e.data,r=new BigInt64Array(a.length);for(let e=0;e<s;++e){const s=e*n;let o=BigInt(t);for(let e=0;e<n;++e){const t=s+e;0n===a[t]?r[t]=BigInt(1):(r[t]=o,o+=a[t])}}return{data:r,dims:e.dims}}function _o(e,t,s,n){if(s.past_key_values){const t=Object.values(s.past_key_values)[0].dims.at(-2),{input_ids:n,attention_mask:a}=s;if(a&&a.dims[1]>n.dims[1]);else if(t<n.dims[1])s.input_ids=n.slice(null,[t,null]);else if(null!=e.config.image_token_index&&n.data.some((t=>t==e.config.image_token_index))){const a=e.config.num_image_tokens;if(!a)throw new Error("`num_image_tokens` is missing in the model configuration.");const r=n.dims[1]-(t-a);s.input_ids=n.slice(null,[-r,null]),s.attention_mask=ot([1,t+r])}}return s}function po(e,t,s,n){return s.past_key_values&&(t=t.map((e=>[e.at(-1)]))),{...s,decoder_input_ids:eo(t)}}function mo(e,...t){return e.config.is_encoder_decoder?po(e,...t):_o(e,...t)}function fo(e,t,s,n){const a=!!s.past_key_values;if(null!==n.guidance_scale&&n.guidance_scale>1&&(a?s.input_ids=Ze([s.input_ids,s.input_ids],0):(s.input_ids=Ze([s.input_ids,rt(s.input_ids,BigInt(n.pad_token_id))],0),s.attention_mask=Ze([s.attention_mask,rt(s.attention_mask,0n)],0))),!a&&s.pixel_values||(s.pixel_values=at([0,0,3,384,384],1)),a){const e=0,t=1,n=e>0?1:0,a=1;s.images_seq_mask=new Ne("bool",new Array(e+t).fill(!0).fill(!1,0,t),[a,e+t]),s.images_emb_mask=new Ne("bool",new Array(e).fill(!!n),[a,1,e])}return s}class go extends C{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t,s){super(),this.config=e,this.sessions=t,this.configs=s;const n=Xr.get(this.constructor),a=Gr.get(n);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,a){case $r:this.can_generate=!0,this._forward=ro,this._prepare_inputs_for_generation=_o;break;case Br:case Or:case Vr:this.can_generate=!0,this._forward=so,this._prepare_inputs_for_generation=po;break;case Lr:this._forward=so;break;case Dr:this.can_generate=!0,this._forward=uo,this._prepare_inputs_for_generation=mo;break;case Rr:this.can_generate=!0,this._forward=co,this._prepare_inputs_for_generation=mo;break;case Ur:this.can_generate=!0,this._prepare_inputs_for_generation=mo;break;case jr:this.can_generate=!0,this._prepare_inputs_for_generation=fo;break;case qr:this._forward=ao;break;default:this._forward=no}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:r="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:u={}}={}){let h={progress_callback:t,config:s,cache_dir:n,local_files_only:a,revision:r,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:u};const _=Xr.get(this),p=Gr.get(_);let m;if(s=h.config=await Ua.from_pretrained(e,h),p===$r)m=await Promise.all([Jr(e,{model:h.model_file_name??"model"},h),Kr(e,{generation_config:"generation_config.json"},h)]);else if(p===Br||p===Or)m=await Promise.all([Jr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h),Kr(e,{generation_config:"generation_config.json"},h)]);else if(p===Nr)m=await Promise.all([Jr(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]);else if(p===Lr)m=await Promise.all([Jr(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h)]);else if(p===Dr){const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(t.model="encoder_model"),m=await Promise.all([Jr(e,t,h),Kr(e,{generation_config:"generation_config.json"},h)])}else if(p===Rr){const t={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};m=await Promise.all([Jr(e,t,h),Kr(e,{generation_config:"generation_config.json"},h)])}else if(p===Vr)m=await Promise.all([Jr(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h),Kr(e,{generation_config:"generation_config.json"},h)]);else if(p===jr)m=await Promise.all([Jr(e,{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"},h),Kr(e,{generation_config:"generation_config.json"},h)]);else if(p===Ur)m=await Promise.all([Jr(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},h),Kr(e,{generation_config:"generation_config.json"},h)]);else if(p===qr)m=await Promise.all([Jr(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},h)]);else{if(p!==Ir){const e=_??s?.model_type;"custom"!==e&&console.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${Ha}.`)}m=await Promise.all([Jr(e,{model:h.model_file_name??"model"},h)])}return new this(s,...m)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(e){const t=new Ya;return null!==e.temperature&&1!==e.temperature&&t.push(new dr(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new hr(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new ur(e.top_p)),t}_get_logits_processor(e,t,s=null){const n=new Ya;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&n.push(new rr(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&n.push(new ar(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&n.push(new lr(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&n.push(new or(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&n.push(new ir(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&n.push(new er(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&n.push(new tr(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){const s=t>1||null===e.forced_bos_token_id?t:t+1;n.push(new sr(e.begin_suppress_tokens,s))}return null!==e.guidance_scale&&e.guidance_scale>1&&n.push(new cr(e.guidance_scale)),null!==s&&n.extend(s),n}_prepare_generation_config(e,t,s=_r){const n={...this.config};for(const e of["decoder","generator","text_config"])e in n&&Object.assign(n,n[e]);const a=new s(n);return Object.assign(a,this.generation_config??{}),e&&Object.assign(a,e),t&&Object.assign(a,B(t,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(e,t=null){const s=new Mr;return null!==e.max_length&&s.push(new Er(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&s.push(new Ar(e.eos_token_id)),t&&s.extend(t),s}_validate_model_class(){if(!this.can_generate){const e=[jm,Gm,Vm,Bm],t=Xr.get(this.constructor),s=new Set,n=this.config.model_type;for(const t of e){const e=t.get(n);e&&s.add(e[0])}let a=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(a+=` Please use the following class instead: ${[...s].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(t,s.past_key_values),s.input_ids=new Ne("int64",e.flat(),[e.length,1]),n||(s.attention_mask=Ze([s.attention_mask,ot([s.attention_mask.dims[0],1])],1)),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:s}){const n=B(s,this.forward_params),a=this.main_input_name;if(a in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[a]=e;return{inputs_tensor:n[a],model_inputs:n,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:e,pixel_values:s,attention_mask:n,...a}=t;t={...a,...B(await this._prepare_inputs_embeds(t),["inputs_embeds","attention_mask"])}}let{last_hidden_state:a}=await no(this,t);if(null!==n.guidance_scale&&n.guidance_scale>1)a=Ze([a,rt(a,0)],0),"attention_mask"in t&&(t.attention_mask=Ze([t.attention_mask,ct(t.attention_mask)],0));else if(t.decoder_input_ids){const e=eo(t.decoder_input_ids).dims[0];if(e!==a.dims[0]){if(1!==a.dims[0])throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${e}).`);a=Ze(Array.from({length:e},(()=>a)),0)}}return t.encoder_outputs=a,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:s,decoder_start_token_id:n,bos_token_id:a,generation_config:r}){let{decoder_input_ids:o,...i}=s;if(!(o instanceof Ne)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},(()=>o)));else if(n??=a,"musicgen"===this.config.model_type)o=Array.from({length:e*this.config.decoder.num_codebooks},(()=>[n]));else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);o=n}else o=Array.from({length:e},(()=>[n]));o=eo(o)}return s.decoder_attention_mask=it(o),{input_ids:o,model_inputs:i}}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:n=null,streamer:a=null,...r}){this._validate_model_class(),t=this._prepare_generation_config(t,r);let{inputs_tensor:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:r});const c=this.config.is_encoder_decoder;let d;c&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:i,model_input_name:l,generation_config:t}))),c?({input_ids:d,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[l].dims.at(0),model_input_name:l,model_kwargs:i,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t})):d=i[l];let u=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=u+t.max_new_tokens);const h=this._get_logits_processor(t,u,s),_=this._get_stopping_criteria(t,n),p=i[l].dims.at(0),m=Tr.getSampler(t),f=new Array(p).fill(0),g=d.tolist();let w;a&&a.put(g);let y={};for(;;){if(i=this.prepare_inputs_for_generation(g,i,t),w=await this.forward(i),t.output_attentions&&t.return_dict_in_generate){const e=this.getAttentions(w);for(const t in e)t in y||(y[t]=[]),y[t].push(e[t])}const e=h(g,w.logits.slice(null,-1,null)),s=[];for(let t=0;t<e.dims.at(0);++t){const n=e[t],a=await m(n);for(const[e,n]of a){const a=BigInt(e);f[t]+=n,g[t].push(a),s.push([a]);break}}a&&a.put(s);if(_(g).every((e=>e)))break;i=this._update_model_kwargs_for_generation({generated_input_ids:s,outputs:w,model_inputs:i,is_encoder_decoder:c})}a&&a.end();const x=this.getPastKeyValues(w,i.past_key_values,!0),b=new Ne("int64",g.flat(),[g.length,g[0].length]);if(t.return_dict_in_generate)return{sequences:b,past_key_values:x,...y};for(const e of Object.values(w))"gpu-buffer"===e.location&&e.dispose();return b}getPastKeyValues(e,t,s=!1){const n=Object.create(null);for(const a in e)if(a.startsWith("present")){const r=a.replace("present","past_key_values"),o=a.includes("encoder");if(n[r]=o&&t?t[r]:e[a],t&&(!o||s)){const e=t[r];"gpu-buffer"===e.location&&e.dispose()}}return n}getAttentions(e){const t={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const n in e)n.startsWith(s)&&(s in t||(t[s]=[]),t[s].push(e[n]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=this.sessions.decoder_model_merged??this.sessions.model,s=t?.config?.kv_cache_dtype??"float32",n="float16"===s?new $e.float16:[],a=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,r=Va(this.config,{batch_size:a});for(const t in r)e[t]=new Ne(s,n,r[t])}}async encode_image({pixel_values:e}){const t=(await Zr(this.sessions.vision_encoder,{pixel_values:e})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${t.dims[1]}).`),this.config.num_image_tokens=t.dims[1]),t}async encode_text({input_ids:e}){return(await Zr(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await Zr(this.sessions.audio_encoder,{audio_values:e})).audio_features}}class wo{}class yo extends wo{constructor({last_hidden_state:e,hidden_states:t=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=s}}class xo extends go{}class bo extends xo{}class ko extends xo{async _call(e){return new Zf(await super._call(e))}}class vo extends xo{async _call(e){return new Jf(await super._call(e))}}class Mo extends xo{async _call(e){return new Qf(await super._call(e))}}class Eo extends xo{async _call(e){return new Yf(await super._call(e))}}class Ao extends go{}class Co extends Ao{}class To extends Ao{async _call(e){return new Zf(await super._call(e))}}class Fo extends Ao{async _call(e){return new Jf(await super._call(e))}}class So extends Ao{async _call(e){return new Qf(await super._call(e))}}class Po extends go{}class zo extends Po{}class Io extends go{}class Lo extends Io{}class Bo extends Io{async _call(e){return new Zf(await super._call(e))}}class Oo extends Io{async _call(e){return new Jf(await super._call(e))}}class $o extends Io{async _call(e){return new Qf(await super._call(e))}}class No extends Io{async _call(e){return new Yf(await super._call(e))}}class Do extends go{}class Vo extends Do{}class jo extends Do{async _call(e){return new Zf(await super._call(e))}}class Uo extends Do{async _call(e){return new Jf(await super._call(e))}}class Ro extends Do{async _call(e){return new Qf(await super._call(e))}}class qo extends Do{async _call(e){return new Yf(await super._call(e))}}class Go extends go{}class Wo extends Go{}class Xo extends Go{async _call(e){return new Zf(await super._call(e))}}class Ho extends Go{async _call(e){return new Jf(await super._call(e))}}class Jo extends Go{async _call(e){return new Qf(await super._call(e))}}class Ko extends Go{async _call(e){return new Yf(await super._call(e))}}class Qo extends go{}class Zo extends Qo{}class Yo extends Qo{async _call(e){return new Zf(await super._call(e))}}class ei extends Qo{async _call(e){return new Jf(await super._call(e))}}class ti extends Qo{async _call(e){return new Qf(await super._call(e))}}class si extends Qo{async _call(e){return new Yf(await super._call(e))}}class ni extends go{}class ai extends ni{}class ri extends ni{async _call(e){return new Zf(await super._call(e))}}class oi extends ni{async _call(e){return new Jf(await super._call(e))}}class ii extends ni{async _call(e){return new Qf(await super._call(e))}}class li extends ni{async _call(e){return new Yf(await super._call(e))}}class ci extends go{}class di extends ci{}class ui extends ci{async _call(e){return new Zf(await super._call(e))}}class hi extends ci{async _call(e){return new Jf(await super._call(e))}}class _i extends ci{async _call(e){return new Qf(await super._call(e))}}class pi extends ci{async _call(e){return new Yf(await super._call(e))}}class mi extends go{}class fi extends mi{}class gi extends mi{async _call(e){return new Jf(await super._call(e))}}class wi extends mi{async _call(e){return new Qf(await super._call(e))}}class yi extends mi{async _call(e){return new Yf(await super._call(e))}}class xi extends mi{async _call(e){return new Zf(await super._call(e))}}class bi extends go{}class ki extends bi{}class vi extends bi{async _call(e){return new Zf(await super._call(e))}}class Mi extends bi{async _call(e){return new Jf(await super._call(e))}}class Ei extends bi{async _call(e){return new Qf(await super._call(e))}}class Ai extends go{}class Ci extends Ai{}class Ti extends Ai{async _call(e){return new Zf(await super._call(e))}}class Fi extends Ai{async _call(e){return new Jf(await super._call(e))}}class Si extends Ai{async _call(e){return new Yf(await super._call(e))}}class Pi extends go{}class zi extends Pi{}class Ii extends Pi{async _call(e){return new Zf(await super._call(e))}}class Li extends Pi{async _call(e){return new Jf(await super._call(e))}}class Bi extends Pi{async _call(e){return new Qf(await super._call(e))}}class Oi extends Pi{async _call(e){return new Yf(await super._call(e))}}class $i extends go{}class Ni extends $i{}class Di extends $i{async _call(e){return new Zf(await super._call(e))}}class Vi extends $i{async _call(e){return new Jf(await super._call(e))}}class ji extends $i{async _call(e){return new Yf(await super._call(e))}}class Ui extends go{}class Ri extends Ui{}class qi extends Ui{async _call(e){return new Jf(await super._call(e))}}class Gi extends Ui{async _call(e){return new Yf(await super._call(e))}}class Wi extends Ui{async _call(e){return new Zf(await super._call(e))}}class Xi extends go{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Hi extends Xi{}class Ji extends Xi{}class Ki extends go{}class Qi extends Ki{}class Zi extends Ki{}class Yi extends go{}class el extends Yi{}class tl extends Yi{}class sl extends go{}class nl extends sl{}class al extends sl{}class rl extends sl{async _call(e){return new Jf(await super._call(e))}}class ol extends go{}class il extends ol{}class ll extends ol{}class cl extends ol{async _call(e){return new Jf(await super._call(e))}}class dl extends ol{}class ul extends go{}class hl extends ul{}class _l extends ul{}class pl extends go{}class ml extends pl{}class fl extends pl{}class gl extends go{}class wl extends gl{}class yl extends gl{async _call(e){return new Zf(await super._call(e))}}class xl extends gl{async _call(e){return new Jf(await super._call(e))}}class bl extends gl{async _call(e){return new Qf(await super._call(e))}}class kl extends gl{async _call(e){return new Yf(await super._call(e))}}class vl extends go{}class Ml extends vl{}class El extends vl{async _call(e){return new Zf(await super._call(e))}}class Al extends vl{async _call(e){return new Jf(await super._call(e))}}class Cl extends vl{async _call(e){return new Qf(await super._call(e))}}class Tl extends vl{async _call(e){return new Yf(await super._call(e))}}class Fl extends go{}class Sl extends Fl{}class Pl extends Fl{async _call(e){return new Zf(await super._call(e))}}class zl extends Fl{async _call(e){return new Jf(await super._call(e))}}class Il extends Fl{async _call(e){return new Qf(await super._call(e))}}class Ll extends Fl{async _call(e){return new Yf(await super._call(e))}}class Bl extends go{}class Ol extends Bl{}class $l extends Bl{}class Nl extends go{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Dl extends Nl{}class Vl extends Nl{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,zr)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let s=e.language;const n=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");const a=function(e){e=e.toLowerCase();let t=Ss.get(e);if(void 0===t){const s=e.match(/^<\|([a-z]{2})\|>$/);if(s&&(e=s[1]),!Fs.has(e)){const t=2===e.length?Fs.keys():Fs.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}t=e}return t}(s),r=`<|${a}|>`;t.push(e.lang_to_id[r]),t.push(e.task_to_id[n??"transcribe"])}else if(s||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&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter((e=>null!=e))}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:n=null,...a}){t=this._prepare_generation_config(t,a);const r=a.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(s??=new Ya,s.push(new nr(t,r))),t.begin_suppress_tokens&&(s??=new Ya,s.push(new sr(t.begin_suppress_tokens,r.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.");"translate"===t.task&&console.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:s,decoder_input_ids:r,...a});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,s=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`.");null==s&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;void 0===a&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);const r=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},((e,t)=>Ze(r.map((e=>e[t])),2))),i=Ye(t.map((([e,t])=>{if(e>=o.length)throw new Error(`Layer index ${e} is out of bounds for cross attentions (length ${o.length}).`);return s?o[e].slice(null,t,null,[0,s]):o[e].slice(null,t)}))).transpose(1,0,2,3),[l,c]=tt(i,-2,0,!0),d=i.clone();for(let e=0;e<d.dims[0];++e){const t=d[e];for(let s=0;s<t.dims[0];++s){const n=t[s],r=l[e][s][0].data,o=c[e][s][0].data;for(let e=0;e<n.dims[0];++e){let t=n[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-o[e])/r[e];t.set(de(t,a))}}}const u=[st(d,1)],h=e.sequences.dims,_=new Ne("float32",new Float32Array(h[0]*h[1]),h);for(let e=0;e<h[0];++e){const t=u[e].neg().squeeze_(0),[s,a]=_e(t.tolist()),r=P([1],Array.from({length:s.length-1},((e,t)=>s[t+1]-s[t]))).map((e=>!!e)),o=[];for(let e=0;e<r.length;++e)r[e]&&o.push(a[e]*n);_[e].data.set(o,1)}return _}}class jl extends Vl{}class Ul extends go{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]}class Rl extends Ul{}class ql extends Ul{}class Gl extends go{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]}class Wl extends go{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]}class Xl extends Wl{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:n}){const a=this.config.image_token_index,r=s.tolist().map((e=>e.findIndex((e=>e==a)))),o=r.every((e=>-1===e)),i=r.every((e=>-1!==e));if(!o&&!i)throw new Error("Every input should contain either 0 or 1 image token.");if(o)return{inputs_embeds:e,attention_mask:n};const l=[],c=[];for(let s=0;s<r.length;++s){const a=r[s],o=e[s],i=t[s],d=n[s];l.push(Ze([o.slice([0,a]),i,o.slice([a+1,o.dims[0]])],0)),c.push(Ze([d.slice([0,a]),ot([i.dims[0]]),d.slice([a+1,d.dims[0]])],0))}return{inputs_embeds:Ye(l,0),attention_mask:Ye(c,0)}}}class Hl extends Xl{}class Jl extends Xl{}class Kl extends go{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"}class Ql extends Kl{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:n}){return{inputs_embeds:Ze([t,e],1),attention_mask:Ze([ot(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let a,r;return e&&(a=await this.encode_text({input_ids:e})),t&&(r=await this.encode_image({pixel_values:t})),a&&r?({inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:a,image_features:r,input_ids:e,attention_mask:n})):s=a||r,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:a,encoder_outputs:r,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:s})),!r){let{last_hidden_state:e}=await no(this,{inputs_embeds:i,attention_mask:s});r=e}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})}const c={inputs_embeds:l,attention_mask:a,encoder_attention_mask:s,encoder_hidden_states:r,past_key_values:o};return await ro(this,c,!0)}}class Zl extends go{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]}class Yl extends Zl{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return io({image_token_id:this.config.image_token_index,...e,image_features:s})}}class ec extends go{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]}class tc extends ec{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await Zr(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),s=e.image_features.view(-1,t);return io({image_token_id:this.config.image_token_id,...e,image_features:s})}}class sc extends tc{}class nc extends go{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]}class ac extends nc{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,image_sizes:n=null,position_ids:a=null,inputs_embeds:r=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!r){let t;if(s&&1!==e.dims[1]){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await Zr(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{const e=this.config.normalized_config.hidden_size;t=new Ne("float32",[],[0,e])}({inputs_embeds:r}=await Zr(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await ro(this,{inputs_embeds:r,past_key_values:o,attention_mask:t,position_ids:a,generation_config:i,logits_processor:l},!1)}}class rc extends go{}class oc extends rc{}class ic extends rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}}class lc extends rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}}class cc extends rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}}class dc extends rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}}class uc extends go{}class hc extends uc{}class _c extends uc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}}class pc extends rc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}}class mc extends go{}class fc extends mc{}class gc extends go{}class wc extends gc{async forward(e){const t=!e.input_ids,s=!e.pixel_values;if(t&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=ot([e.pixel_values.dims[0],1])),s){const{image_size:t}=this.config.vision_config;e.pixel_values=at([0,3,t,t],0)}const{text_embeddings:n,image_embeddings:a,l2norm_text_embeddings:r,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=n,i.l2norm_text_embeddings=r),s||(i.image_embeddings=a,i.l2norm_image_embeddings=o),i}}class yc extends gc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}}class xc extends gc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}}class bc extends go{}class kc extends bc{}class vc extends bc{}class Mc extends go{}class Ec extends Mc{}class Ac extends Mc{}class Cc extends go{}class Tc extends Cc{}class Fc extends Cc{}class Sc extends go{}class Pc extends Sc{}class zc extends Sc{}class Ic extends go{}class Lc extends Ic{}class Bc extends Ic{}class Oc extends go{}class $c extends Oc{}class Nc extends Oc{}class Dc extends go{}class Vc extends Dc{}class jc extends Dc{}class Uc extends go{}class Rc extends Uc{}class qc extends Uc{}class Gc extends go{}class Wc extends Gc{}class Xc extends Gc{}class Hc extends go{}class Jc extends Hc{}class Kc extends Hc{}class Qc extends go{}class Zc extends Qc{}class Yc extends Qc{}class ed extends go{}class td extends ed{}class sd extends ed{}class nd extends go{}class ad extends nd{}class rd extends nd{}class od extends go{}class id extends od{}class ld extends od{}class cd extends go{}class dd extends cd{}class ud extends cd{}class hd extends go{}class _d extends hd{}class pd extends hd{}class md extends go{}class fd extends md{}class gd extends md{}class wd extends go{}class yd extends wd{}class xd extends wd{}class bd extends go{}class kd extends bd{}class vd extends bd{}class Md extends go{}class Ed extends Md{}class Ad extends Md{}class Cd extends go{}class Td extends Cd{}class Fd extends Cd{}class Sd extends go{}class Pd extends Sd{}class zd extends Sd{}class Id extends go{}class Ld extends Id{}class Bd extends Id{}class Od extends go{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]}class $d extends Od{get_rope_index(e,t,s,n){const{vision_config:a,image_token_id:r,video_token_id:o,vision_start_token_id:i}=this.config,l=a.spatial_merge_size??2,c=[];if(t||s){let a=e.tolist();n||(n=it(e));const d=n.tolist(),u=Array.from({length:3},(t=>Array.from({length:e.dims[0]},(t=>Array.from({length:e.dims[1]},(e=>1)))))),h=t?t.tolist():[],_=s?s.tolist():[];let p=0,m=0;for(let e=0;e<a.length;++e){const t=a[e].filter(((t,s)=>1==d[e][s])),s=t.reduce(((e,t,s)=>(t==i&&e.push(s),e)),[]).map((e=>t[e+1])),n=s.filter((e=>e==r)).length,f=s.filter((e=>e==o)).length;let g=[],w=0,y=n,x=f;for(let e=0;e<s.length;++e){const e=t.findIndex(((e,t)=>t>w&&e==r)),s=t.findIndex(((e,t)=>t>w&&e==o)),n=y>0&&-1!==e?e:t.length+1,a=x>0&&-1!==s?s:t.length+1;let i,c,d,u;n<a?([c,d,u]=h[p],++p,--y,i=n):([c,d,u]=_[m],++m,--x,i=a);const[f,b,k]=[Number(c),Math.floor(Number(d)/l),Math.floor(Number(u)/l)],v=i-w,M=g.length>0?re(g.at(-1))[0]+1:0;g.push(Array.from({length:3*v},((e,t)=>M+t%v)));const E=v+M,A=f*b*k,C=Array.from({length:A},((e,t)=>E+Math.floor(t/(b*k)))),T=Array.from({length:A},((e,t)=>E+Math.floor(t/k)%b)),F=Array.from({length:A},((e,t)=>E+t%k));g.push([C,T,F].flat()),w=i+A}if(w<t.length){const e=g.length>0?re(g.at(-1))[0]+1:0,s=t.length-w;g.push(Array.from({length:3*s},((t,n)=>e+n%s)))}const b=g.reduce(((e,t)=>e+t.length),0),k=new Array(b);let v=0;for(let e=0;e<3;++e)for(let t=0;t<g.length;++t){const s=g[t],n=s.length/3;for(let t=e*n;t<(e+1)*n;++t)k[v++]=s[t]}let M=0;const E=d[e];for(let t=0;t<E.length;++t)if(1==E[t]){for(let s=0;s<3;++s)u[s][e][t]=k[s*b/3+M];++M}const A=re(k)[0];c.push(A+1-a[e].length)}return[new Ne("int64",u.flat(1/0),[3,e.dims[0],e.dims[1]]),new Ne("int64",c,[c.length,1])]}if(n){const{data:e,dims:t}=ho(n),s=BigInt64Array.from({length:3*e.length},((t,s)=>e[s%e.length])),a=Array.from({length:t[0]},((s,n)=>re(e.subarray(t[1]*n,t[1]*(n+1)))[0]+1n+BigInt(t[1])));return[new Ne("int64",s,[3,...t]),new Ne("int64",a,[a.length,1])]}{const[t,s]=e.dims,n=BigInt64Array.from({length:3*t*s},((e,n)=>BigInt(Math.floor(n%s/t))));return[new Ne("int64",n,[3,...e.dims]),lt([t,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await Zr(this.sessions.vision_encoder,{pixel_values:e,grid_thw:t})).image_features}_merge_input_ids_with_image_features(e){return io({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,s){if(t.attention_mask&&!t.position_ids)if(t.past_key_values){t.pixel_values=null;const e=BigInt(Object.values(t.past_key_values)[0].dims.at(-2)),s=t.rope_deltas.map((t=>e+t));t.position_ids=Ye([s,s,s],0)}else[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);return t}}class Nd extends go{}class Dd extends Nd{}class Vd extends Nd{}class jd extends go{}class Ud extends jd{}class Rd extends jd{}class qd extends go{}class Gd extends qd{}class Wd extends qd{}class Xd extends go{}class Hd extends Xd{}class Jd extends Xd{}class Kd extends go{}class Qd extends Kd{}class Zd extends Kd{}class Yd extends go{}class eu extends Yd{}class tu extends Yd{async _call(e){return new Jf(await super._call(e))}}class su extends go{}class nu extends su{}class au extends su{async _call(e){return new Jf(await super._call(e))}}class ru extends go{}class ou extends ru{}class iu extends go{}class lu extends iu{}class cu extends iu{async _call(e){return new Jf(await super._call(e))}}class du extends go{}class uu extends du{}class hu extends go{}class _u extends hu{}class pu extends hu{async _call(e){return new Jf(await super._call(e))}}class mu extends go{}class fu extends mu{}class gu extends go{}class wu extends gu{}class yu extends gu{async _call(e){return new Jf(await super._call(e))}}class xu extends go{}class bu extends xu{async _call(e){return new sg(await super._call(e))}}class ku extends go{}class vu extends ku{}class Mu extends ku{async _call(e){return new Jf(await super._call(e))}}class Eu extends go{}class Au extends Eu{}class Cu extends Eu{async _call(e){return new Jf(await super._call(e))}}class Tu extends go{}class Fu extends Tu{}class Su extends Tu{}class Pu extends go{}class zu extends Pu{}class Iu extends Pu{}class Lu extends go{}class Bu extends Lu{}class Ou extends Lu{async _call(e){return new Jf(await super._call(e))}}class $u extends go{}class Nu extends $u{}class Du extends $u{async _call(e){return new ju(await super._call(e))}}class Vu extends $u{async _call(e){return new Uu(await super._call(e))}}class ju extends wo{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class Uu extends wo{constructor({logits:e,pred_boxes:t,pred_masks:s}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=s}}class Ru extends go{}class qu extends Ru{}class Gu extends Ru{async _call(e){return new Wu(await super._call(e))}}class Wu extends wo{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class Xu extends go{}class Hu extends Xu{}class Ju extends Xu{async _call(e){return new Ku(await super._call(e))}}class Ku extends Wu{}class Qu extends go{}class Zu extends Qu{}class Yu extends Qu{async _call(e){return new eh(await super._call(e))}}class eh extends Wu{}class th extends go{}class sh extends th{}class nh extends th{async _call(e){return new Wu(await super._call(e))}}class ah extends go{}class rh extends ah{}class oh extends ah{async _call(e){return new ih(await super._call(e))}}class ih extends ju{}class lh extends go{}class ch extends lh{}class dh extends lh{async _call(e){return new Jf(await super._call(e))}}class uh extends go{}class hh extends uh{}class _h extends uh{async _call(e){return new Jf(await super._call(e))}}class ph extends go{}class mh extends ph{}class fh extends ph{async _call(e){return new Jf(await super._call(e))}}class gh extends go{}class wh extends gh{}class yh extends gh{async _call(e){return new Jf(await super._call(e))}}class xh extends gh{}class bh extends go{}class kh extends bh{}class vh extends bh{}class Mh extends go{}class Eh extends Mh{}class Ah extends Mh{}class Ch extends go{}class Th extends Ch{}class Fh extends go{}class Sh extends Fh{}class Ph extends Fh{}class zh extends Fh{}class Ih extends go{}class Lh extends Ih{}class Bh extends go{}class Oh extends Bh{}class $h extends go{}class Nh extends $h{}class Dh extends go{}class Vh extends Dh{}class jh extends Dh{}class Uh extends go{}class Rh extends Uh{}class qh extends Uh{}class Gh extends go{}class Wh extends Gh{}class Xh extends go{}class Hh extends Xh{}class Jh extends Xh{async _call(e){return new Jf(await super._call(e))}}class Kh extends go{}class Qh extends Kh{}class Zh extends Kh{async _call(e){return new Jf(await super._call(e))}}class Yh extends go{}class e_ extends Yh{}class t_ extends Yh{async _call(e){return new Jf(await super._call(e))}}class s_ extends go{}class n_ extends s_{}class a_ extends s_{async _call(e){return new Jf(await super._call(e))}}class r_ extends go{}class o_ extends r_{}class i_ extends go{}class l_ extends i_{}class c_ extends i_{async _call(e){return new d_(await super._call(e))}}class d_ extends wo{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}}class u_ extends go{}class h_ extends u_{async get_image_embeddings({pixel_values:e}){return await no(this,{pixel_values:e})}async forward(e){if(e.image_embeddings&&e.image_positional_embeddings||(e={...e,...await this.get_image_embeddings(e)}),!e.input_labels&&e.input_points){const t=e.input_points.dims.slice(0,-1),s=t.reduce(((e,t)=>e*t),1);e.input_labels=new Ne("int64",new BigInt64Array(s).fill(1n),t)}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 Zr(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new __(await super._call(e))}}class __ extends wo{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class p_ extends go{}class m_ extends p_{}class f_ extends p_{}class g_ extends go{}class w_ extends g_{}class y_ extends g_{}class x_ extends go{}class b_ extends x_{}class k_ extends x_{async _call(e){return new eg(await super._call(e))}}class v_ extends x_{async _call(e){return new Jf(await super._call(e))}}class M_ extends x_{async _call(e){return new Qf(await super._call(e))}}class E_ extends go{}class A_ extends E_{}class C_ extends E_{async _call(e){return new Qf(await super._call(e))}}class T_ extends go{}class F_ extends T_{}class S_ extends go{}class P_ extends S_{}class z_ extends S_{async _call(e){return new eg(await super._call(e))}}class I_ extends S_{async _call(e){return new Jf(await super._call(e))}}class L_ extends go{}class B_ extends L_{}class O_ extends L_{async _call(e){return new eg(await super._call(e))}}class $_ extends L_{async _call(e){return new Jf(await super._call(e))}}class N_ extends L_{async _call(e){return new Qf(await super._call(e))}}class D_ extends go{}class V_ extends D_{}class j_ extends D_{async _call(e){return new eg(await super._call(e))}}class U_ extends D_{async _call(e){return new Jf(await super._call(e))}}class R_ extends go{}class q_ extends x_{}class G_ extends x_{async _call(e){return new eg(await super._call(e))}}class W_ extends x_{async _call(e){return new Jf(await super._call(e))}}class X_ extends go{}class H_ extends X_{}class J_ extends X_{async _call(e){return new eg(await super._call(e))}}class K_ extends X_{async _call(e){return new Jf(await super._call(e))}}class Q_ extends X_{async _call(e){return new Kf(await super._call(e))}}class Z_ extends X_{async _call(e){return new Qf(await super._call(e))}}class Y_ extends go{}class ep extends Y_{}class tp extends go{}class sp extends tp{}class np extends tp{}class ap extends tp{async generate_speech(e,t,{threshold:s=.5,minlenratio:n=0,maxlenratio:a=20,vocoder:r=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await no(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*a),u=Math.floor(c*n),h=this.config.num_mel_bins;let _=[],p=null,m=null,f=0;for(;;){++f;const e=to(!!m);let n;n=m?m.output_sequence_out:new Ne("float32",new Float32Array(h),[1,1,h]);let a={use_cache_branch:e,output_sequence:n,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};this.addPastKeyValues(a,p),m=await Zr(this.sessions.decoder_model_merged,a),p=this.getPastKeyValues(m,p);const{prob:r,spectrum:o}=m;if(_.push(o),f>=u&&(Array.from(r.data).filter((e=>e>=s)).length>0||f>=d))break}const g=Ze(_),{waveform:w}=await Zr(r.sessions.model,{spectrogram:g});return{spectrogram:g,waveform:w}}}class rp extends go{main_input_name="spectrogram"}class op extends go{}class ip extends op{}class lp extends go{}class cp extends lp{}class dp extends lp{}class up extends go{}class hp extends up{}class _p extends up{}class pp extends go{}class mp extends pp{}class fp extends pp{}class gp extends go{}class wp extends gp{}class yp extends gp{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}}class xp extends gp{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}}class bp extends go{}class kp extends bp{async _call(e){return new ng(await super._call(e))}}class vp extends go{}class Mp extends vp{}class Ep extends vp{}class Ap extends vp{}class Cp extends go{}class Tp extends Cp{}class Fp extends Cp{}class Sp extends go{}class Pp extends Sp{}class zp extends Sp{async _call(e){return new Jf(await super._call(e))}}class Ip extends go{}class Lp extends Ip{}class Bp extends Ip{}class Op extends go{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,s]=e.dims,n=this.config.decoder.num_codebooks,a=s-n;let r=0;for(let t=0;t<e.size;++t){if(e.data[t]===this.config.decoder.pad_token_id)continue;const o=t%s-Math.floor(t/s)%n;o>0&&o<=a&&(e.data[r++]=e.data[t])}const o=Math.floor(t/n),i=r/(o*n);return new Ne(e.type,e.data.slice(0,r),[o,n,i])}prepare_inputs_for_generation(e,t,s){let n=structuredClone(e);for(let e=0;e<n.length;++e)for(let t=0;t<n[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(n[e][t]=BigInt(this.config.decoder.pad_token_id));null!==s.guidance_scale&&s.guidance_scale>1&&(n=n.concat(n));return super.prepare_inputs_for_generation(n,t,s)}async generate(e){const t=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:n}=await Zr(this.sessions.encodec_decode,{audio_codes:s});return n}}class $p extends go{}class Np extends $p{}class Dp extends $p{async _call(e){return new Jf(await super._call(e))}}class Vp extends $p{}class jp extends go{}class Up extends jp{}class Rp extends jp{async _call(e){return new Jf(await super._call(e))}}class qp extends jp{}class Gp extends go{}class Wp extends Gp{}class Xp extends Gp{async _call(e){return new Jf(await super._call(e))}}class Hp extends Gp{}class Jp extends go{}class Kp extends Jp{}class Qp extends Jp{async _call(e){return new Jf(await super._call(e))}}class Zp extends Jp{}class Yp extends go{}class em extends Yp{}class tm extends go{}class sm extends tm{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let s;if("text"!==t&&e.past_key_values){const t=this.sessions.gen_img_embeds,n=B({image_ids:e.input_ids},t.inputNames);s=await Zr(t,n)}else{const t=this.sessions.prepare_inputs_embeds,n=B(e,t.inputNames);s=await Zr(t,n)}const n={...e,...s},a=await ro(this,n),r=this.sessions["text"===t?"lm_head":"gen_head"];if(!r)throw new Error(`Unable to find "${r}" generation head`);const o=await Zr(r,B(a,r.inputNames));return{...s,...a,...o}}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),n=this.sessions.image_decode,{decoded_image:a}=await Zr(n,{generated_tokens:s}),r=a.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),o=[];for(const e of r){const t=br.fromTensor(e);o.push(t)}return o}}class nm extends wo{constructor({char_logits:e,bpe_logits:t,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class am extends go{}class rm extends am{async _call(e){return new nm(await super._call(e))}}class om extends go{}class im extends om{}class lm extends om{}class cm extends go{}class dm extends cm{}class um extends cm{}class hm extends go{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class _m extends hm{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,t);return function({audio_token_id:e,inputs_embeds:t,audio_features:s,input_ids:n,attention_mask:a}){return oo({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:a})}({audio_token_id:this.config.ignore_index,...e,audio_features:s})}}class pm extends go{main_input_name="input_values";forward_params=["input_values"]}class mm extends wo{constructor({audio_codes:e}){super(),this.audio_codes=e}}class fm extends wo{constructor({audio_values:e}){super(),this.audio_values=e}}class gm extends pm{async encode(e){return new mm(await Zr(this.sessions.encoder_model,e))}async decode(e){return new fm(await Zr(this.sessions.decoder_model,e))}}class wm extends pm{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}}class ym extends pm{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}}class xm extends go{main_input_name="input_values";forward_params=["input_values"]}class bm extends wo{constructor({audio_codes:e}){super(),this.audio_codes=e}}class km extends wo{constructor({audio_values:e}){super(),this.audio_values=e}}class vm extends xm{async encode(e){return new bm(await Zr(this.sessions.encoder_model,e))}async decode(e){return new km(await Zr(this.sessions.decoder_model,e))}}class Mm extends xm{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}}class Em extends xm{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}}class Am extends go{main_input_name="input_values";forward_params=["input_values"]}class Cm extends Am{async encode(e){return await Zr(this.sessions.encoder_model,e)}async decode(e){return await Zr(this.sessions.decoder_model,e)}}class Tm extends Am{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}}class Fm extends Am{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}}class Sm{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:a=!1,revision:r="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:u={}}={}){const h={progress_callback:t,config:s,cache_dir:n,local_files_only:a,revision:r,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:u};if(h.config=await Ua.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const _=h.config.model_type;for(const t of this.MODEL_CLASS_MAPPINGS){let s=t.get(_);if(!s){for(const e of t.values())if(e[0]===_){s=e;break}if(!s)continue}return await s[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return ff.has(_)||console.warn(`Unknown model class "${_}", attempting to construct from base class.`),await go.from_pretrained(e,h);throw Error(`Unsupported model type: ${_}`)}}const Pm=new Map([["bert",["BertModel",bo]],["modernbert",["ModernBertModel",Co]],["nomic_bert",["NomicBertModel",zo]],["roformer",["RoFormerModel",Lo]],["electra",["ElectraModel",Wo]],["esm",["EsmModel",ki]],["convbert",["ConvBertModel",Vo]],["camembert",["CamembertModel",Zo]],["deberta",["DebertaModel",ai]],["deberta-v2",["DebertaV2Model",di]],["mpnet",["MPNetModel",zi]],["albert",["AlbertModel",Ri]],["distilbert",["DistilBertModel",fi]],["roberta",["RobertaModel",wl]],["xlm",["XLMModel",Ml]],["xlm-roberta",["XLMRobertaModel",Sl]],["clap",["ClapModel",wp]],["clip",["CLIPModel",oc]],["clipseg",["CLIPSegModel",kc]],["chinese_clip",["ChineseCLIPModel",fc]],["siglip",["SiglipModel",hc]],["jina_clip",["JinaCLIPModel",wc]],["mobilebert",["MobileBertModel",Ci]],["squeezebert",["SqueezeBertModel",Ni]],["wav2vec2",["Wav2Vec2Model",b_]],["wav2vec2-bert",["Wav2Vec2BertModel",V_]],["unispeech",["UniSpeechModel",P_]],["unispeech-sat",["UniSpeechSatModel",B_]],["hubert",["HubertModel",q_]],["wavlm",["WavLMModel",H_]],["audio-spectrogram-transformer",["ASTModel",Ol]],["vits",["VitsModel",kp]],["pyannote",["PyAnnoteModel",A_]],["wespeaker-resnet",["WeSpeakerResNetModel",F_]],["detr",["DetrModel",Nu]],["rt_detr",["RTDetrModel",qu]],["rt_detr_v2",["RTDetrV2Model",Hu]],["rf_detr",["RFDetrModel",Zu]],["d_fine",["DFineModel",sh]],["table-transformer",["TableTransformerModel",rh]],["vit",["ViTModel",eu]],["ijepa",["IJepaModel",nu]],["pvt",["PvtModel",lu]],["vit_msn",["ViTMSNModel",_u]],["vit_mae",["ViTMAEModel",uu]],["groupvit",["GroupViTModel",fu]],["fastvit",["FastViTModel",wu]],["mobilevit",["MobileViTModel",vu]],["mobilevitv2",["MobileViTV2Model",Au]],["owlvit",["OwlViTModel",Fu]],["owlv2",["Owlv2Model",zu]],["beit",["BeitModel",Bu]],["deit",["DeiTModel",ch]],["hiera",["HieraModel",hh]],["convnext",["ConvNextModel",Hh]],["convnextv2",["ConvNextV2Model",Qh]],["dinov2",["Dinov2Model",e_]],["dinov2_with_registers",["Dinov2WithRegistersModel",n_]],["resnet",["ResNetModel",mh]],["swin",["SwinModel",wh]],["swin2sr",["Swin2SRModel",kh]],["donut-swin",["DonutSwinModel",Wh]],["yolos",["YolosModel",l_]],["dpt",["DPTModel",Eh]],["glpn",["GLPNModel",Rh]],["hifigan",["SpeechT5HifiGan",rp]],["efficientnet",["EfficientNetModel",Pp]],["decision_transformer",["DecisionTransformerModel",em]],["patchtst",["PatchTSTForPrediction",im]],["patchtsmixer",["PatchTSMixerForPrediction",dm]],["mobilenet_v1",["MobileNetV1Model",Np]],["mobilenet_v2",["MobileNetV2Model",Up]],["mobilenet_v3",["MobileNetV3Model",Wp]],["mobilenet_v4",["MobileNetV4Model",Kp]],["maskformer",["MaskFormerModel",Vh]],["mgp-str",["MgpstrForSceneTextRecognition",rm]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ep]]]),zm=new Map([["t5",["T5Model",Hi]],["longt5",["LongT5Model",Qi]],["mt5",["MT5Model",el]],["bart",["BartModel",nl]],["mbart",["MBartModel",il]],["marian",["MarianModel",m_]],["whisper",["WhisperModel",Dl]],["m2m_100",["M2M100Model",w_]],["blenderbot",["BlenderbotModel",hl]],["blenderbot-small",["BlenderbotSmallModel",ml]]]),Im=new Map([["mimi",["MimiModel",gm]],["dac",["DacModel",vm]],["snac",["SnacModel",Cm]]]),Lm=new Map([["bloom",["BloomModel",Gd]],["jais",["JAISModel",Tc]],["gpt2",["GPT2Model",Ec]],["gptj",["GPTJModel",$c]],["gpt_bigcode",["GPTBigCodeModel",Vc]],["gpt_neo",["GPTNeoModel",Pc]],["gpt_neox",["GPTNeoXModel",Lc]],["codegen",["CodeGenModel",Rc]],["llama",["LlamaModel",Wc]],["exaone",["ExaoneModel",td]],["olmo",["OlmoModel",id]],["olmo2",["Olmo2Model",dd]],["mobilellm",["MobileLLMModel",ad]],["granite",["GraniteModel",_d]],["cohere",["CohereModel",fd]],["gemma",["GemmaModel",yd]],["gemma2",["Gemma2Model",kd]],["gemma3_text",["Gemma3Model",Ed]],["helium",["HeliumModel",Jc]],["glm",["GlmModel",Zc]],["openelm",["OpenELMModel",Td]],["qwen2",["Qwen2Model",Pd]],["qwen3",["Qwen3Model",Ld]],["phi",["PhiModel",Dd]],["phi3",["Phi3Model",Ud]],["mpt",["MptModel",Hd]],["opt",["OPTModel",Qd]],["mistral",["MistralModel",cp]],["starcoder2",["Starcoder2Model",hp]],["falcon",["FalconModel",mp]],["stablelm",["StableLmModel",Tp]]]),Bm=new Map([["speecht5",["SpeechT5ForSpeechToText",np]],["whisper",["WhisperForConditionalGeneration",Vl]],["lite-whisper",["LiteWhisperForConditionalGeneration",jl]],["moonshine",["MoonshineForConditionalGeneration",ql]]]),Om=new Map([["speecht5",["SpeechT5ForTextToSpeech",ap]]]),$m=new Map([["vits",["VitsModel",kp]],["musicgen",["MusicgenForConditionalGeneration",Op]]]),Nm=new Map([["bert",["BertForSequenceClassification",vo]],["modernbert",["ModernBertForSequenceClassification",Fo]],["roformer",["RoFormerForSequenceClassification",Oo]],["electra",["ElectraForSequenceClassification",Ho]],["esm",["EsmForSequenceClassification",Mi]],["convbert",["ConvBertForSequenceClassification",Uo]],["camembert",["CamembertForSequenceClassification",ei]],["deberta",["DebertaForSequenceClassification",oi]],["deberta-v2",["DebertaV2ForSequenceClassification",hi]],["mpnet",["MPNetForSequenceClassification",Li]],["albert",["AlbertForSequenceClassification",qi]],["distilbert",["DistilBertForSequenceClassification",gi]],["roberta",["RobertaForSequenceClassification",xl]],["xlm",["XLMForSequenceClassification",Al]],["xlm-roberta",["XLMRobertaForSequenceClassification",zl]],["bart",["BartForSequenceClassification",rl]],["mbart",["MBartForSequenceClassification",cl]],["mobilebert",["MobileBertForSequenceClassification",Fi]],["squeezebert",["SqueezeBertForSequenceClassification",Vi]]]),Dm=new Map([["bert",["BertForTokenClassification",Mo]],["modernbert",["ModernBertForTokenClassification",So]],["roformer",["RoFormerForTokenClassification",$o]],["electra",["ElectraForTokenClassification",Jo]],["esm",["EsmForTokenClassification",Ei]],["convbert",["ConvBertForTokenClassification",Ro]],["camembert",["CamembertForTokenClassification",ti]],["deberta",["DebertaForTokenClassification",ii]],["deberta-v2",["DebertaV2ForTokenClassification",_i]],["mpnet",["MPNetForTokenClassification",Bi]],["distilbert",["DistilBertForTokenClassification",wi]],["roberta",["RobertaForTokenClassification",bl]],["xlm",["XLMForTokenClassification",Cl]],["xlm-roberta",["XLMRobertaForTokenClassification",Il]]]),Vm=new Map([["t5",["T5ForConditionalGeneration",Ji]],["longt5",["LongT5ForConditionalGeneration",Zi]],["mt5",["MT5ForConditionalGeneration",tl]],["bart",["BartForConditionalGeneration",al]],["mbart",["MBartForConditionalGeneration",ll]],["marian",["MarianMTModel",f_]],["m2m_100",["M2M100ForConditionalGeneration",y_]],["blenderbot",["BlenderbotForConditionalGeneration",_l]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",fl]]]),jm=new Map([["bloom",["BloomForCausalLM",Wd]],["gpt2",["GPT2LMHeadModel",Ac]],["jais",["JAISLMHeadModel",Fc]],["gptj",["GPTJForCausalLM",Nc]],["gpt_bigcode",["GPTBigCodeForCausalLM",jc]],["gpt_neo",["GPTNeoForCausalLM",zc]],["gpt_neox",["GPTNeoXForCausalLM",Bc]],["codegen",["CodeGenForCausalLM",qc]],["llama",["LlamaForCausalLM",Xc]],["exaone",["ExaoneForCausalLM",sd]],["olmo",["OlmoForCausalLM",ld]],["olmo2",["Olmo2ForCausalLM",ud]],["mobilellm",["MobileLLMForCausalLM",rd]],["granite",["GraniteForCausalLM",pd]],["cohere",["CohereForCausalLM",gd]],["gemma",["GemmaForCausalLM",xd]],["gemma2",["Gemma2ForCausalLM",vd]],["gemma3_text",["Gemma3ForCausalLM",Ad]],["helium",["HeliumForCausalLM",Kc]],["glm",["GlmForCausalLM",Yc]],["openelm",["OpenELMForCausalLM",Fd]],["qwen2",["Qwen2ForCausalLM",zd]],["qwen3",["Qwen3ForCausalLM",Bd]],["phi",["PhiForCausalLM",Vd]],["phi3",["Phi3ForCausalLM",Rd]],["mpt",["MptForCausalLM",Jd]],["opt",["OPTForCausalLM",Zd]],["mbart",["MBartForCausalLM",dl]],["mistral",["MistralForCausalLM",dp]],["starcoder2",["Starcoder2ForCausalLM",_p]],["falcon",["FalconForCausalLM",fp]],["trocr",["TrOCRForCausalLM",ip]],["stablelm",["StableLmForCausalLM",Fp]],["phi3_v",["Phi3VForCausalLM",ac]]]),Um=new Map([["multi_modality",["MultiModalityCausalLM",sm]]]),Rm=new Map([["bert",["BertForMaskedLM",ko]],["modernbert",["ModernBertForMaskedLM",To]],["roformer",["RoFormerForMaskedLM",Bo]],["electra",["ElectraForMaskedLM",Xo]],["esm",["EsmForMaskedLM",vi]],["convbert",["ConvBertForMaskedLM",jo]],["camembert",["CamembertForMaskedLM",Yo]],["deberta",["DebertaForMaskedLM",ri]],["deberta-v2",["DebertaV2ForMaskedLM",ui]],["mpnet",["MPNetForMaskedLM",Ii]],["albert",["AlbertForMaskedLM",Wi]],["distilbert",["DistilBertForMaskedLM",xi]],["roberta",["RobertaForMaskedLM",yl]],["xlm",["XLMWithLMHeadModel",El]],["xlm-roberta",["XLMRobertaForMaskedLM",Pl]],["mobilebert",["MobileBertForMaskedLM",Ti]],["squeezebert",["SqueezeBertForMaskedLM",Di]]]),qm=new Map([["bert",["BertForQuestionAnswering",Eo]],["roformer",["RoFormerForQuestionAnswering",No]],["electra",["ElectraForQuestionAnswering",Ko]],["convbert",["ConvBertForQuestionAnswering",qo]],["camembert",["CamembertForQuestionAnswering",si]],["deberta",["DebertaForQuestionAnswering",li]],["deberta-v2",["DebertaV2ForQuestionAnswering",pi]],["mpnet",["MPNetForQuestionAnswering",Oi]],["albert",["AlbertForQuestionAnswering",Gi]],["distilbert",["DistilBertForQuestionAnswering",yi]],["roberta",["RobertaForQuestionAnswering",kl]],["xlm",["XLMForQuestionAnswering",Tl]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ll]],["mobilebert",["MobileBertForQuestionAnswering",Si]],["squeezebert",["SqueezeBertForQuestionAnswering",ji]]]),Gm=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Gl]],["idefics3",["Idefics3ForConditionalGeneration",tc]],["smolvlm",["SmolVLMForConditionalGeneration",sc]]]),Wm=new Map([["llava",["LlavaForConditionalGeneration",Xl]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Hl]],["moondream1",["Moondream1ForConditionalGeneration",Jl]],["florence2",["Florence2ForConditionalGeneration",Ql]],["qwen2-vl",["Qwen2VLForConditionalGeneration",$d]],["idefics3",["Idefics3ForConditionalGeneration",tc]],["smolvlm",["SmolVLMForConditionalGeneration",sc]],["paligemma",["PaliGemmaForConditionalGeneration",Yl]]]),Xm=new Map([["ultravox",["UltravoxModel",_m]]]),Hm=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Gl]]]),Jm=new Map([["vit",["ViTForImageClassification",tu]],["ijepa",["IJepaForImageClassification",au]],["pvt",["PvtForImageClassification",cu]],["vit_msn",["ViTMSNForImageClassification",pu]],["fastvit",["FastViTForImageClassification",yu]],["mobilevit",["MobileViTForImageClassification",Mu]],["mobilevitv2",["MobileViTV2ForImageClassification",Cu]],["beit",["BeitForImageClassification",Ou]],["deit",["DeiTForImageClassification",dh]],["hiera",["HieraForImageClassification",_h]],["convnext",["ConvNextForImageClassification",Jh]],["convnextv2",["ConvNextV2ForImageClassification",Zh]],["dinov2",["Dinov2ForImageClassification",t_]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",a_]],["resnet",["ResNetForImageClassification",fh]],["swin",["SwinForImageClassification",yh]],["segformer",["SegformerForImageClassification",Ep]],["efficientnet",["EfficientNetForImageClassification",zp]],["mobilenet_v1",["MobileNetV1ForImageClassification",Dp]],["mobilenet_v2",["MobileNetV2ForImageClassification",Rp]],["mobilenet_v3",["MobileNetV3ForImageClassification",Xp]],["mobilenet_v4",["MobileNetV4ForImageClassification",Qp]]]),Km=new Map([["detr",["DetrForObjectDetection",Du]],["rt_detr",["RTDetrForObjectDetection",Gu]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Ju]],["rf_detr",["RFDetrForObjectDetection",Yu]],["d_fine",["DFineForObjectDetection",nh]],["table-transformer",["TableTransformerForObjectDetection",oh]],["yolos",["YolosForObjectDetection",c_]]]),Qm=new Map([["owlvit",["OwlViTForObjectDetection",Su]],["owlv2",["Owlv2ForObjectDetection",Iu]],["grounding-dino",["GroundingDinoForObjectDetection",o_]]]),Zm=new Map([["detr",["DetrForSegmentation",Vu]],["clipseg",["CLIPSegForImageSegmentation",vc]]]),Ym=new Map([["segformer",["SegformerForSemanticSegmentation",Ap]],["sapiens",["SapiensForSemanticSegmentation",Sh]],["swin",["SwinForSemanticSegmentation",xh]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Vp]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",qp]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Hp]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Zp]]]),ef=new Map([["detr",["DetrForSegmentation",Vu]],["maskformer",["MaskFormerForInstanceSegmentation",jh]]]),tf=new Map([["sam",["SamModel",h_]]]),sf=new Map([["wav2vec2",["Wav2Vec2ForCTC",k_]],["wav2vec2-bert",["Wav2Vec2BertForCTC",j_]],["unispeech",["UniSpeechForCTC",z_]],["unispeech-sat",["UniSpeechSatForCTC",O_]],["wavlm",["WavLMForCTC",J_]],["hubert",["HubertForCTC",G_]]]),nf=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",v_]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",U_]],["unispeech",["UniSpeechForSequenceClassification",I_]],["unispeech-sat",["UniSpeechSatForSequenceClassification",$_]],["wavlm",["WavLMForSequenceClassification",K_]],["hubert",["HubertForSequenceClassification",W_]],["audio-spectrogram-transformer",["ASTForAudioClassification",$l]]]),af=new Map([["wavlm",["WavLMForXVector",Q_]]]),rf=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",N_]],["wavlm",["WavLMForAudioFrameClassification",Z_]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",M_]],["pyannote",["PyAnnoteForAudioFrameClassification",C_]]]),of=new Map([["vitmatte",["VitMatteForImageMatting",bu]]]),lf=new Map([["patchtst",["PatchTSTForPrediction",lm]],["patchtsmixer",["PatchTSMixerForPrediction",um]]]),cf=new Map([["swin2sr",["Swin2SRForImageSuperResolution",vh]]]),df=new Map([["dpt",["DPTForDepthEstimation",Ah]],["depth_anything",["DepthAnythingForDepthEstimation",Th]],["glpn",["GLPNForDepthEstimation",qh]],["sapiens",["SapiensForDepthEstimation",Ph]],["depth_pro",["DepthProForDepthEstimation",Lh]],["metric3d",["Metric3DForDepthEstimation",Oh]],["metric3dv2",["Metric3Dv2ForDepthEstimation",Nh]]]),uf=new Map([["sapiens",["SapiensForNormalEstimation",zh]]]),hf=new Map([["vitpose",["VitPoseForPoseEstimation",ou]]]),_f=new Map([["clip",["CLIPVisionModelWithProjection",dc]],["siglip",["SiglipVisionModel",pc]],["jina_clip",["JinaCLIPVisionModel",xc]]]),pf=[[Pm,Ir],[zm,Lr],[Lm,$r],[Im,qr],[Nm,Ir],[Dm,Ir],[Vm,Br],[Bm,Br],[jm,$r],[Um,jr],[Rm,Ir],[qm,Ir],[Gm,Or],[Wm,Dr],[Xm,Rr],[Jm,Ir],[Zm,Ir],[ef,Ir],[Ym,Ir],[of,Ir],[lf,Ir],[cf,Ir],[df,Ir],[uf,Ir],[hf,Ir],[Km,Ir],[Qm,Ir],[tf,Nr],[sf,Ir],[nf,Ir],[Om,Br],[$m,Ir],[af,Ir],[rf,Ir],[_f,Ir]];for(const[e,t]of pf)for(const[s,n]of e.values())Gr.set(s,t),Xr.set(n,s),Wr.set(s,n);const mf=[["MusicgenForConditionalGeneration",Op,Vr],["Phi3VForCausalLM",ac,Ur],["CLIPTextModelWithProjection",lc,Ir],["SiglipTextModel",_c,Ir],["JinaCLIPTextModel",yc,Ir],["ClapTextModelWithProjection",yp,Ir],["ClapAudioModelWithProjection",xp,Ir],["DacEncoderModel",Mm,Ir],["DacDecoderModel",Em,Ir],["MimiEncoderModel",wm,Ir],["MimiDecoderModel",ym,Ir],["SnacEncoderModel",Tm,Ir],["SnacDecoderModel",Fm,Ir]];for(const[e,t,s]of mf)Gr.set(e,s),Xr.set(t,e),Wr.set(e,t);const ff=new Map([["modnet",Zm],["birefnet",Zm],["isnet",Zm],["ben",Zm]]);for(const[e,t]of ff.entries())t.set(e,["PreTrainedModel",go]),Gr.set(e,Ir),Xr.set(go,e),Wr.set(e,go);class gf extends Sm{static MODEL_CLASS_MAPPINGS=pf.map((e=>e[0]));static BASE_IF_FAIL=!0}class wf extends Sm{static MODEL_CLASS_MAPPINGS=[Nm]}class yf extends Sm{static MODEL_CLASS_MAPPINGS=[Dm]}class xf extends Sm{static MODEL_CLASS_MAPPINGS=[Vm]}class bf extends Sm{static MODEL_CLASS_MAPPINGS=[Bm]}class kf extends Sm{static MODEL_CLASS_MAPPINGS=[Om]}class vf extends Sm{static MODEL_CLASS_MAPPINGS=[$m]}class Mf extends Sm{static MODEL_CLASS_MAPPINGS=[jm]}class Ef extends Sm{static MODEL_CLASS_MAPPINGS=[Rm]}class Af extends Sm{static MODEL_CLASS_MAPPINGS=[qm]}class Cf extends Sm{static MODEL_CLASS_MAPPINGS=[Gm]}class Tf extends Sm{static MODEL_CLASS_MAPPINGS=[Jm]}class Ff extends Sm{static MODEL_CLASS_MAPPINGS=[Zm]}class Sf extends Sm{static MODEL_CLASS_MAPPINGS=[Ym]}class Pf extends Sm{static MODEL_CLASS_MAPPINGS=[ef]}class zf extends Sm{static MODEL_CLASS_MAPPINGS=[Km]}class If extends Sm{static MODEL_CLASS_MAPPINGS=[Qm]}class Lf extends Sm{static MODEL_CLASS_MAPPINGS=[tf]}class Bf extends Sm{static MODEL_CLASS_MAPPINGS=[sf]}class Of extends Sm{static MODEL_CLASS_MAPPINGS=[nf]}class $f extends Sm{static MODEL_CLASS_MAPPINGS=[af]}class Nf extends Sm{static MODEL_CLASS_MAPPINGS=[rf]}class Df extends Sm{static MODEL_CLASS_MAPPINGS=[Hm]}class Vf extends Sm{static MODEL_CLASS_MAPPINGS=[of]}class jf extends Sm{static MODEL_CLASS_MAPPINGS=[cf]}class Uf extends Sm{static MODEL_CLASS_MAPPINGS=[df]}class Rf extends Sm{static MODEL_CLASS_MAPPINGS=[uf]}class qf extends Sm{static MODEL_CLASS_MAPPINGS=[hf]}class Gf extends Sm{static MODEL_CLASS_MAPPINGS=[_f]}class Wf extends Sm{static MODEL_CLASS_MAPPINGS=[Wm]}class Xf extends Sm{static MODEL_CLASS_MAPPINGS=[Xm]}class Hf extends wo{constructor({logits:e,past_key_values:t,encoder_outputs:s,decoder_attentions:n=null,cross_attentions:a=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=s,this.decoder_attentions=n,this.cross_attentions=a}}class Jf extends wo{constructor({logits:e,...t}){super(),this.logits=e;const s=Object.values(t);s.length>0&&(this.attentions=s)}}class Kf extends wo{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class Qf extends wo{constructor({logits:e}){super(),this.logits=e}}class Zf extends wo{constructor({logits:e}){super(),this.logits=e}}class Yf extends wo{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class eg extends wo{constructor({logits:e}){super(),this.logits=e}}class tg extends wo{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class sg extends wo{constructor({alphas:e}){super(),this.alphas=e}}class ng extends wo{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}class ag extends C{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(e,t){super(),this.config=e,this.components=t}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,...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 s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t){const[s,n]=await Promise.all([this.uses_processor_config?J(e,"processor_config.json",!0,t):{},Promise.all(this.classes.filter((e=>e in this)).map((async s=>{const n=await this[s].from_pretrained(e,t);return[s.replace(/_class$/,""),n]}))).then(Object.fromEntries)]);return new this(s,n)}}function rg(e,t,s=0,n=null){const a=e/t;let r=he(a)*t;return null!==n&&r>n&&(r=Math.floor(a)*t),r<s&&(r=Math.ceil(a)*t),r}function og([e,t],s){return[Math.max(Math.floor(e/s),1)*s,Math.max(Math.floor(t/s),1)*s]}function ig([e,t,s,n]){return[e-s/2,t-n/2,e+s/2,t+n/2]}function lg(e,t=.5,s=null,n=!1){const a=e.logits,r=e.pred_boxes,[o,i,l]=a.dims;if(null!==s&&s.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let e=0;e<o;++e){let o=null!==s?s[e]:null,d={boxes:[],classes:[],scores:[]},u=a[e],h=r[e];for(let e=0;e<i;++e){let s,a=u[e],r=[];if(n){s=a.sigmoid().data;for(let e=0;e<s.length;++e)s[e]>t&&r.push(e)}else{let e=re(a.data)[1];if(e===l-1)continue;if(s=Y(a.data),s[e]<t)continue;r.push(e)}for(const t of r){let n=h[e].data;n=ig(n),null!==o&&(n=n.map(((e,t)=>e*o[(t+1)%2]))),d.boxes.push(n),d.classes.push(t),d.scores.push(s[t])}}c.push(d)}return c}function cg(e,t,s,n){const a=[],r=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=re(l.data)[1];if(d===n)continue;const u=Y(l.data)[d];u>s&&(a.push(c),r.push(u),o.push(d))}return[a,r,o]}function dg(e,t,s,n=.5,a=.8){const r=[];let o=0,i=0;const l=t[s].data;for(let t=0;t<e.length;++t)e[t]===s&&(r.push(t),++o),l[t]>=n&&++i;let c=o>0&&i>0;if(c){c=o/i>a}return[c,r]}function ug(e,t,s,n,a,r=null,o=null){const[i,l]=o??e[0].dims,c=new Ne("int32",new Int32Array(i*l),[i,l]),d=[];if(null!==o)for(let t=0;t<e.length;++t)e[t]=Ve(e[t],o,"bilinear",!1);const u=new Int32Array(e[0].data.length),h=new Float32Array(e[0].data.length);for(let s=0;s<e.length;++s){let n=t[s];const a=e[s].data;for(let e=0;e<a.length;++e)a[e]*=n,a[e]>h[e]&&(u[e]=s,h[e]=a[e])}let _=0;const p=c.data;for(let r=0;r<s.length;++r){const o=s[r],[i,l]=dg(u,e,r,n,a);if(i){++_;for(const e of l)p[e]=_;d.push({id:_,label_id:o,score:t[r]})}}return[c,d]}function hg(e,t=.5,s=.5,n=.8,a=null,r=null){null===a&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),a=new Set);const o=e.class_queries_logits??e.logits,i=(e.masks_queries_logits??e.pred_masks).sigmoid();let[l,c,d]=o.dims;if(d-=1,null!==r&&r.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let e=0;e<l;++e){let l=null!==r?r[e]:null,c=o[e],h=i[e],[_,p,m]=cg(c,h,t,d);if(0===m.length){let[e,t]=l??h.dims.slice(-2),s=new Ne("int32",new Int32Array(e*t).fill(-1),[e,t]);u.push({segmentation:s,segments_info:[]});continue}let[f,g]=ug(_,p,m,s,n,a,l);u.push({segmentation:f,segments_info:g})}return u}function _g(e,t=.5,s=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}class pg extends C{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??void 0!==this.size,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&void 0!==this.size.width&&void 0!==this.size.height&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,s=2){const n=e.height,a=e.width,r=t.height,o=t.width;let i=Math.min(n,r),l=Math.min(a,o);return i===n&&l===a?e:(n>a?l=Math.floor(a*i/n):a>n&&(i=Math.floor(n*l/a)),await e.resize(l,i,{resample:s}))}async crop_margin(e,t=200){const s=e.clone().grayscale(),n=ae(s.data)[0],a=re(s.data)[0]-n;if(0===a)return e;const r=t/255;let o=s.width,i=s.height,l=0,c=0;const d=s.data;for(let e=0;e<s.height;++e){const t=e*s.width;for(let u=0;u<s.width;++u)(d[t+u]-n)/a<r&&(o=Math.min(o,u),i=Math.min(i,e),l=Math.max(l,u),c=Math.max(c,e))}return e=await e.crop([o,i,l,c])}pad_image(e,t,s,{mode:n="constant",center:a=!1,constant_values:r=0}={}){const[o,i,l]=t;let c,d;if("number"==typeof s?(c=s,d=s):"square"===s?c=d=Math.max(o,i):(c=s.width,d=s.height),c!==i||d!==o){const s=new Float32Array(c*d*l);if(Array.isArray(r))for(let e=0;e<s.length;++e)s[e]=r[e%l];else 0!==r&&s.fill(r);const[u,h]=a?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let t=0;t<o;++t){const n=(t+h)*c,a=t*i;for(let t=0;t<i;++t){const r=(n+t+u)*l,o=(a+t)*l;for(let t=0;t<l;++t)s[r+t]=e[o+t]}}if("symmetric"===n){if(a)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const t=o-1,n=i-1;for(let a=0;a<d;++a){const r=a*c,d=I(a,t)*i;for(let t=0;t<c;++t){if(a<o&&t<i)continue;const c=(r+t)*l,u=(d+I(t,n))*l;for(let t=0;t<l;++t)s[c+t]=e[u+t]}}}e=s,t=[d,c,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[s,n]=e.size;let a,r;if(this.do_thumbnail){const{height:e,width:s}=t;a=Math.min(e,s)}else Number.isInteger(t)?(a=t,r=this.config.max_size??a):void 0!==t&&(a=t.shortest_edge,r=t.longest_edge);if(void 0!==a||void 0!==r){const e=void 0===a?1:Math.max(a/s,a/n),t=s*e,o=n*e,i=void 0===r?1:Math.min(r/t,r/o);let l=Math.floor(Number((t*i).toFixed(2))),c=Math.floor(Number((o*i).toFixed(2)));return void 0!==this.size_divisibility&&([l,c]=og([l,c],this.size_divisibility)),[l,c]}if(void 0!==t&&void 0!==t.width&&void 0!==t.height){let e=t.width,a=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=a/n,r=e/s;Math.abs(1-r)<Math.abs(1-t)?t=r:r=t,a=rg(t*n,this.config.ensure_multiple_of),e=rg(r*s,this.config.ensure_multiple_of)}return[e,a]}if(void 0!==this.size_divisibility)return og([s,n],this.size_divisibility);if(void 0!==this.min_pixels&&void 0!==this.max_pixels){return function(e,t,s=28,n=3136,a=1003520){if(e<s||t<s)throw new Error(`height:${e} or width:${t} must be larger than factor:${s}`);if(Math.max(e,t)/Math.min(e,t)>200)throw new Error("absolute aspect ratio must be smaller than 200, got "+Math.max(e,t)/Math.min(e,t));let r=Math.round(e/s)*s,o=Math.round(t/s)*s;if(r*o>a){const n=Math.sqrt(e*t/a);r=Math.floor(e/n/s)*s,o=Math.floor(t/n/s)*s}else if(r*o<n){const a=Math.sqrt(n/(e*t));r=Math.ceil(e*a/s)*s,o=Math.ceil(t*a/s)*s}return[r,o]}(n,s,this.config.patch_size*this.config.merge_size,this.min_pixels,this.max_pixels)}throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}async resize(e){const[t,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,s,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:a=null,do_flip_channel_order:r=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(n??this.do_convert_rgb?e=e.rgb():a&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let t,s;Number.isInteger(this.crop_size)?(t=this.crop_size,s=this.crop_size):(t=this.crop_size.width,s=this.crop_size.height),e=await e.center_crop(t,s)}const l=[e.height,e.width];let c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=new Array(e.channels).fill(t));let s=this.image_std;if(Array.isArray(this.image_std)||(s=new Array(e.channels).fill(t)),t.length!==e.channels||s.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${t.length}) and \`image_std\` (${s.length}) must match the number of channels in the image (${e.channels}).`);for(let n=0;n<c.length;n+=e.channels)for(let a=0;a<e.channels;++a)c[n+a]=(c[n+a]-t[a])/s[a]}if(s??this.do_pad)if(this.pad_size){const t=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);[c,d]=t}else if(this.size_divisibility){const[e,t]=og([d[1],d[0]],this.size_divisibility);[c,d]=this.pad_image(c,d,{width:e,height:t})}if(r??this.do_flip_channel_order){if(3!==d[2])throw new Error("Flipping channel order is only supported for RGB images.");for(let e=0;e<c.length;e+=3){const t=c[e];c[e]=c[e+2],c[e+2]=t}}return{original_size:[i,o],reshaped_input_size:l,pixel_values:new Ne("float32",c,d).permute(2,0,1)}}async _call(e,...t){Array.isArray(e)||(e=[e]);const s=await Promise.all(e.map((e=>this.preprocess(e))));return{pixel_values:Ye(s.map((e=>e.pixel_values)),0),original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}static async from_pretrained(e,t){return new this(await J(e,Ka,!0,t))}}class mg extends pg{}class fg extends pg{}class gg extends pg{}class wg extends pg{}class yg extends wg{}class xg extends pg{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){const t=this.size?.shortest_edge;if(void 0===t)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const s=Math.floor(t/this.crop_pct),[n,a]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,a,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class bg extends xg{}class kg extends pg{}class vg extends kg{}class Mg extends pg{async _call(e){const t=await super._call(e),s=at([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return lg(...e)}post_process_panoptic_segmentation(...e){return hg(...e)}post_process_instance_segmentation(...e){return _g(...e)}}class Eg extends Mg{}class Ag extends pg{pad_image(e,t,s,n={}){const[a,r,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const c=i.map(((e,t)=>-e/l[t]));return super.pad_image(e,t,s,{center:!0,constant_values:c,...n})}}class Cg extends Ag{}class Tg extends pg{}class Fg extends Tg{}class Sg extends pg{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map((e=>e*e)))}}class Pg extends pg{}class zg extends pg{async _call(e){const t=await super._call(e),s=t.pixel_values.dims,n=ot([s[0],s[2],s[3]]);return{...t,pixel_mask:n}}}class Ig extends pg{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[s,n]=e.dims.slice(-2);const a=n/s;return n>=s?(n=Math.ceil(n/t)*t,s=Math.floor(n/a),s=Math.ceil(s/t)*t):(s=Math.ceil(s/t)*t,n=Math.floor(s*a),n=Math.ceil(n/t)*t),{height:s,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:s=!1}={}){let n;if(Array.isArray(e)){if(0===e.length||!e[0])throw new Error("No images provided.");n=Array.isArray(e[0])?e:[e]}else n=[[e]];let a=[],r=[],o=[];const i=[],l=[];for(const e of n){let s=await Promise.all(e.map((e=>this.preprocess(e))));i.push(...s.map((e=>e.original_size))),l.push(...s.map((e=>e.reshaped_input_size))),s.forEach((e=>e.pixel_values.unsqueeze_(0)));const{longest_edge:n}=this.max_image_size;let c;if(t??this.do_image_splitting){let e=new Array(s.length),t=new Array(s.length);c=await Promise.all(s.map((async(s,a)=>{const r=this.get_resize_for_vision_encoder(s.pixel_values,n),o=await je(s.pixel_values,{size:[r.height,r.width]}),{frames:i,num_splits_h:l,num_splits_w:c}=await this.split_image(o,this.max_image_size);return e[a]=l,t[a]=c,Ze(i,0)}))),r.push(e),o.push(t)}else{const e=[n,n];c=await Promise.all(s.map((t=>je(t.pixel_values,{size:e})))),r.push(new Array(s.length).fill(0)),o.push(new Array(s.length).fill(0))}a.push(Ze(c,0))}const c=a.length,[d,u,h,_]=a[0].dims;let p,m;if(1===c)p=a[0].unsqueeze_(0),m=at([c,d,h,_],!0);else{const e=Math.max(...a.map((e=>e.dims.at(0))));m=at([c,e,h,_],!0);const t=m.data,s=e*h*_;for(let n=0;n<c;++n){const r=a[n].dims[0];if(r<e){a[n]=Ze([a[n],at([e-r,u,h,_],0)],0);const o=n*s+r*h*_,i=(n+1)*s;t.fill(!1,o,i)}}p=Ye(a,0)}return{pixel_values:p,pixel_attention_mask:m,original_sizes:i,reshaped_input_sizes:l,...s?{rows:r,cols:o}:{}}}async split_image(e,{longest_edge:t}){const s=t,n=t,a=[],[r,o]=e.dims.slice(-2);let i=0,l=0;if(r>s||o>n){i=Math.ceil(r/s),l=Math.ceil(o/n);const t=Math.ceil(r/i),c=Math.ceil(o/l);for(let s=0;s<i;++s)for(let n=0;n<l;++n){let d,u,h,_;s===i-1?(u=r-t,_=r):(u=s*t,_=(s+1)*t),n===l-1?(d=o-c,h=o):(d=n*c,h=(n+1)*c);const p=[u,d],m=[_,h],f=await We(e,p,m,[2,3]);a.push(f)}const d=s,u=n;r===d&&o===u||(e=await je(e,{size:[d,u]}))}return a.push(e),{frames:a,num_splits_h:i,num_splits_w:l}}}class Lg extends pg{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map((e=>e*this.rescale_factor))}pad_image(e,t,s,n){return super.pad_image(e,t,s,{constant_values:this.constant_values,center:!0,...n})}}class Bg extends pg{constructor(e){const{resize_mode:t,fill_color:s,interpolation:n,size:a,...r}=e;super({...r,size:"squash"===t?{width:a,height:a}:"shortest"===t?{shortest_edge:a}:{longest_edge:a},resample:"bicubic"===n?3:2,do_center_crop:!0,crop_size:a,do_normalize:!0})}}class Og extends pg{}class $g extends pg{post_process_panoptic_segmentation(...e){return hg(...e)}post_process_instance_segmentation(...e){return _g(...e)}}class Ng extends $g{}class Dg extends $g{}class Vg extends pg{}class jg extends Vg{}class Ug extends pg{}class Rg extends Ug{}class qg extends pg{}class Gg extends qg{}class Wg extends pg{}class Xg extends Wg{}class Hg extends pg{}class Jg extends Hg{}class Kg extends Ag{}class Qg extends pg{post_process_object_detection(...e){return lg(...e)}}class Zg extends Qg{}class Yg extends Qg{}const ew=336,tw=[2,3],{ceil:sw,floor:nw,sqrt:aw}=Math;class rw extends pg{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:s}=this.config;return nw((nw(t/ew)*nw(e/ew)+1)*s+1+(nw(t/ew)+1)*aw(s))}get_resize_output_image_size(e,t){const s=this._num_crops,[n,a]=e.size;let r=n/a,o=1;for(;o*Math.ceil(o/r)<=s;)o+=1;o-=1;const i=Math.floor(336*o);return[i,Math.floor(i/r)]}pad_image(e,t,s,n={}){const[a,r]=t,o=ew*sw(a/ew),i=ew*sw(r/ew),l=[1,1,1].map(((e,t)=>(e-this.image_mean[t])/this.image_std[t]));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??=this.config.num_crops,t<4||aw(t)%1!=0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const s=e.length,n=await Promise.all(e.map((e=>this.preprocess(e)))),a=n.map((e=>e.original_size)),r=n.map((e=>e.reshaped_input_size)),o=[];for(const{pixel_values:e}of n){e.unsqueeze_(0);const[s,n]=e.dims.slice(-2),a=await je(e,{size:[ew,ew],mode:"bicubic"});if(t>0){const r=[],i=aw(t),l=nw(n/i),c=nw(s/i);for(let t=0;t<i;++t)for(let a=0;a<i;++a){let o,d,u,h;t===i-1?(d=s-c,h=s):(d=t*c,h=(t+1)*c),a===i-1?(o=n-l,u=n):(o=a*l,u=(a+1)*l);const _=[d,o],p=[h,u],m=await We(e,_,p,tw);r.push(m)}const d=await je(Ze(r,0),{size:[ew,ew],mode:"bicubic"});o.push(Ze([a,d],0))}else o.push(a)}const i=Ye(o,0),l=r.map((e=>e.map((e=>ew*sw(e/ew)))));return{pixel_values:i,original_sizes:a,reshaped_input_sizes:r,image_sizes:new Ne("int64",l.flat(),[s,2]),num_img_tokens:l.map((([e,t])=>this.calc_num_image_tokens_from_image_size(t,e)))}}}class ow extends pg{}class iw extends pg{async _call(e,...t){const{pixel_values:s,original_sizes:n,reshaped_input_sizes:a}=await super._call(e,...t);let r=s;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;1===r.dims[0]&&(r=Ze(Array.from({length:o},(()=>r)),0));const c=r.dims[0]/o,d=r.dims[1],u=Math.floor(r.dims[2]/l),h=Math.floor(r.dims[3]/l);return{pixel_values:r.view(c,o,d,Math.floor(u/i),i,l,Math.floor(h/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*u*h,d*o*l*l),image_grid_thw:new Ne("int64",[c,u,h],[1,3]),original_sizes:n,reshaped_input_sizes:a}}}class lw extends pg{post_process_object_detection(...e){return lg(...e)}}class cw extends pg{reshape_input_points(e,t,s,n=!1){let a=S(e=structuredClone(e));if(3===a.length)n||(a=[1,...a]),e=[e];else if(4!==a.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let n=0;n<e.length;++n){let a=t[n],r=s[n],o=[r[0]/a[0],r[1]/a[1]];for(let t=0;t<e[n].length;++t)for(let s=0;s<e[n][t].length;++s)for(let a=0;a<e[n][t][s].length;++a)e[n][t][s][a]*=o[a%2]}return new Ne("float32",Float32Array.from(e.flat(1/0)),a)}add_input_labels(e,t){let s=S(e);if(2===s.length)s=[1,...s],e=[e];else if(3!==s.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some(((e,s)=>e!==t.dims[s])))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Ne("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:t=null,input_labels:s=null,input_boxes:n=null}={}){const a=await super._call(e);if(t&&(a.input_points=this.reshape_input_points(t,a.original_sizes,a.reshaped_input_sizes)),s){if(!a.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");a.input_labels=this.add_input_labels(s,a.input_points)}return n&&(a.input_boxes=this.reshape_input_points(n,a.original_sizes,a.reshaped_input_sizes,!0)),a}async post_process_masks(e,t,s,{mask_threshold:n=0,binarize:a=!0,pad_size:r=null}={}){const o=[],i=[(r=r??this.pad_size).height,r.width];for(let r=0;r<t.length;++r){const l=t[r],c=s[r];let d=await je(e[r],{mode:"bilinear",size:i});if(d=d.slice(null,null,[0,c[0]],[0,c[1]]),d=await je(d,{mode:"bilinear",size:l}),a){const e=d.data,t=new Uint8Array(e.length);for(let s=0;s<e.length;++s)e[s]>n&&(t[s]=1);d=new Ne("bool",t,d.dims)}o.push(d)}return o}generate_crop_boxes(e,t,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:a=32,crop_n_points_downscale_factor:r=1}={}){}}class dw extends pg{post_process_semantic_segmentation(...e){return function(e,t=null){const s=e.logits,n=s.dims[0];if(null!==t&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const a=[];for(let e=0;e<n;++e){const n=null!==t?t[e]:null;let r=s[e];null!==n&&(r=Ve(r,n,"bilinear",!1));const[o,i]=n??r.dims.slice(-2),l=new Ne("int32",new Int32Array(o*i),[o,i]),c=r[0].data,d=l.data;for(let e=1;e<r.dims[0];++e){const t=r[e].data;for(let s=0;s<t.length;++s)t[s]>c[s]&&(c[s]=t[s],d[s]=e)}const u=new Array(r.dims[0]);for(let e=0;e<d.length;++e){const t=d[e];u[t]=t}const h=u.filter((e=>void 0!==e));a.push({segmentation:l,labels:h})}return a}(...e)}}class uw extends dw{}class hw extends pg{}class _w extends pg{pad_image(e,t,s,n={}){const[a,r,o]=t;return super.pad_image(e,t,{width:r+(s-r%s)%s,height:a+(s-a%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}}class pw extends pg{}class mw extends pw{}class fw extends pg{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=await Promise.all(e.map((e=>this.preprocess(e)))),n=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))));return{pixel_values:Ye(s.map(((e,t)=>Ze([e.pixel_values,n[t].pixel_values],0))),0),original_sizes:s.map((e=>e.original_size)),reshaped_input_sizes:s.map((e=>e.reshaped_input_size))}}}class gw extends pg{post_process_pose_estimation(e,t,{threshold:s=null}={}){const n=e.tolist(),[a,r,o,i]=e.dims,l=[];for(let e=0;e<a;++e){const a=n[e],r=t[e],c=[];for(let e=0;e<r.length;++e){const t=r[e],n=[],l=[],d=[],u=t.at(-2)/i,h=t.at(-1)/o;for(let e=0;e<a.length;++e){let[t,r]=[0,0],o=0,i=-1/0;const c=a[e];for(let e=0;e<c.length;++e){const s=c[e];for(let n=0;n<s.length;++n){const a=s[n];o+=a,i=Math.max(i,a),t+=(n+.5)*a,r+=e*a}}if(null!=s&&i<s)continue;const _=[u*t/o,h*r/o];n.push(_),d.push(e),l.push(i)}c.push({bbox:t,scores:l,labels:d,keypoints:n})}l.push(c)}return l}}class ww extends pg{post_process_object_detection(...e){return lg(...e)}}class yw extends ww{}class xw{static async from_pretrained(e,t={}){const s=await J(e,Ka,!0,t),n=s.image_processor_type??s.feature_extractor_type;let a=r[n];return a||(void 0!==n&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Ha}.`),a=pg),new a(s)}}class bw extends ag{static tokenizer_class=Na;static image_processor_class=xw;constructor(e,t){super(e,t);const{tasks_answer_post_processing_type:s,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){"string"==typeof e&&(e=[e]);const t=[];for(const s of e)if(this.task_prompts_without_inputs.has(s))t.push(this.task_prompts_without_inputs.get(s));else{for(const[e,n]of this.task_prompts_with_input)if(s.includes(e)){t.push(n.replaceAll("{input}",s).replaceAll(e,""));break}t.length!==e.length&&t.push(s)}return t}post_process_generation(e,t,s){const n=this.tasks_answer_post_processing_type.get(t)??"pure_text";let a;switch(e=e.replaceAll("<s>","").replaceAll("</s>",""),n){case"pure_text":a=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const r="ocr"===n?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[r]),i=[],l=[];for(const[e,t,...n]of o)i.push(t?t.trim():i.at(-1)??""),l.push(n.map(((e,t)=>(Number(e)+.5)/this.size_per_bin*s[t%2])));a={labels:i,[r]:l};break;default:throw new Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:a}}async _call(e,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...await this.image_processor(e,s),...t?this.tokenizer(t,s):{}}}}function kw(e,t){const s=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,s);const a=t.tolist();return n.map(((e,t)=>e?t:null)).filter((e=>null!==e)).map((e=>a[e]))}class vw extends ag{static tokenizer_class=Na;static image_processor_class=xw;async _call(e,t,s={}){const n=e?await this.image_processor(e,s):{};return{...t?this.tokenizer(t,s):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:a=null}={}){const{logits:r,pred_boxes:o}=e,i=r.dims[0];if(null!==a&&a.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=r.dims.at(1),c=r.sigmoid(),d=c.max(-1).tolist(),u=o.tolist().map((e=>e.map((e=>ig(e))))),h=[];for(let e=0;e<i;++e){const r=null!==a?a[e]:null;null!==r&&(u[e]=u[e].map((e=>e.map(((e,t)=>e*r[(t+1)%2])))));const o=d[e],i=[],_=[],p=[];for(let a=0;a<l;++a){const r=o[a];if(r<=s)continue;const l=u[e][a],d=c[e][a];i.push(r),p.push(l);const h=kw(d.gt(n),t[e]);_.push(h)}h.push({scores:i,boxes:p,labels:this.batch_decode(_)})}return h}}function Mw(e,t,s,n,a,r){return 0===e&&0===t?function(e,t,s,n){return`${t}${n}`+s.repeat(e)+`${t}`}(s,n,a,r):function(e,t,s,n,a,r){let o="";for(let r=0;r<t;++r){for(let t=0;t<s;++t)o+=n+`<row_${r+1}_col_${t+1}>`+a.repeat(e);o+="\n"}return o+=`\n${n}${r}`+a.repeat(e)+`${n}`,o}(s,e,t,n,a,r)}class Ew extends ag{static image_processor_class=xw;static tokenizer_class=Na;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,s={}){let n;s.return_row_col_info??=!0,t&&(n=await this.image_processor(t,s)),Array.isArray(e)||(e=[e]);const a=n.rows??[new Array(e.length).fill(0)],r=n.cols??[new Array(e.length).fill(0)],o=this.config.image_seq_len,i=[],l=[];for(let t=0;t<e.length;++t){const s=e[t],n=a[t],c=r[t];i.push($(s,this.image_token));const d=n.map(((e,t)=>Mw(e,c[t],o,this.fake_image_token,this.image_token,this.global_img_token))),u=s.split(this.image_token);if(0===u.length)throw new Error("The image token should be present in the text.");let h=u[0];for(let e=0;e<d.length;++e)h+=d[e]+u[e+1];l.push(h)}return{...this.tokenizer(l),...n}}}class Aw extends ag{static image_processor_class=xw;static tokenizer_class=Na;static uses_processor_config=!0;constructor(e,t){super(e,t),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:t=null,chat_template:s="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter((e=>e.images)).flatMap((e=>e.images)).map((e=>br.read(e))));const n=this.tokenizer,a=e=>n.encode(e,{add_special_tokens:!1}),r=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}).split(this.image_tag),o=r.length-1;if(t.length!==o)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${o})`);const[i,l,c]=n.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let d=a(r[0]),u=new Array(d.length).fill(!1);for(let e=1;e<r.length;++e){const t=new Array(this.num_image_tokens).fill(i),s=a(r[e]);d=P(d,[l],t,[c],s);u=P(u,[!1],new Array(this.num_image_tokens).fill(!0),[!1],new Array(s.length).fill(!1))}const h=[1,d.length],_={input_ids:new Ne("int64",d,h),attention_mask:new Ne("int64",new Array(d.length).fill(1),h),images_seq_mask:new Ne("bool",u,h),images_emb_mask:new Ne("bool",new Array(o*this.num_image_tokens).fill(!0),[1,o,this.num_image_tokens])};if(t&&t.length>0){const e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{..._,...e}}return _}}class Cw extends ag{static tokenizer_class=Na;static image_processor_class=xw;async _call(e=null,t=null,s={}){if(!e&&!t)throw new Error("Either text or images must be provided");return{...e?this.tokenizer(e,s):{},...t?await this.image_processor(t,s):{}}}}const Tw={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class Fw extends ag{static tokenizer_class=Na;static image_processor_class=xw;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!Tw.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[s,n]=Tw[t],a=this[s].bind(this),[r,o]=e.dims,i=[],l=[],c=e.tolist();for(let e=0;e<r;++e){const t=c[e],s=[],a=[];for(let e=1;e<o;++e){const[r,o]=re(Y(t[e]));if(a.push(r),o==n)break;s.push(o)}const r=a.length>0?a.reduce(((e,t)=>e*t),1):0;l.push(s),i.push(r)}return[a(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map((e=>e.replaceAll(" ","")))}batch_decode([e,t,s]){const[n,a]=this._decode_helper(e,"char"),[r,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(s,"wp"),c=[],d=[];for(let e=0;e<n.length;++e){const[t,s]=re([a[e],o[e],l[e]]);c.push([n[e],r[e],i[e]][s]),d.push(t)}return{generated_text:c,scores:d,char_preds:n,bpe_preds:r,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),s=await Na.from_pretrained("Xenova/gpt2"),n=await Na.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:s,wp_tokenizer:n},t}async _call(e,t=null){const s=await this.image_processor(e);return t&&(s.labels=this.tokenizer(t).input_ids),s}}class Sw extends C{constructor(e){super(),this.config=e}static async from_pretrained(e,t){return new this(await J(e,Ja,!0,t))}}function Pw(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}async function zw(e,t){if("undefined"==typeof AudioContext)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const s=await(await G(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const a=await n.decodeAudioData(s);let r;if(2===a.numberOfChannels){const e=Math.sqrt(2),t=a.getChannelData(0),s=a.getChannelData(1);r=new Float32Array(t.length);for(let n=0;n<a.length;++n)r[n]=e*(t[n]+s[n])/2}else r=a.getChannelData(0);return r}function Iw(e,t){if(e<1)return new Float64Array;if(1===e)return new Float64Array([1]);const s=1-t,n=2*Math.PI/(e-1),a=new Float64Array(e);for(let r=0;r<e;++r)a[r]=t-s*Math.cos(r*n);return a}function Lw(e){return Iw(e,.5)}function Bw(e){return Iw(e,.54)}const Ow={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,s=15,n=27/Math.log(6.4))=>e>=t?s+Math.log(e/t)*n:3*e/200};function $w(e,t="htk"){const s=Ow[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}const Nw={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,s=15,n=Math.log(6.4)/27)=>e>=s?t*Math.exp(n*(e-s)):200*e/3};function Dw(e,t,s){const n=(t-e)/(s-1);return Float64Array.from({length:s},((t,s)=>e+n*s))}function Vw(e,t,s,n,a,r=null,o="htk",i=!1){if(null!==r&&"slaney"!==r)throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(s>n)throw new Error(`Require min_frequency: ${s} <= max_frequency: ${n}`);const l=Dw($w(s,o),$w(n,o),t+2);let c,d=function(e,t="htk"){const s=Nw[t];if(!s)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map((e=>s(e)))}(l,o);if(i){const t=a/(2*(e-1));c=$w(Float64Array.from({length:e},((e,s)=>s*t)),o),d=l}else c=Dw(0,Math.floor(a/2),e);const u=function(e,t){const s=Float64Array.from({length:t.length-1},((e,s)=>t[s+1]-t[s])),n=Array.from({length:e.length},(()=>new Array(t.length)));for(let s=0;s<e.length;++s){const a=n[s];for(let n=0;n<t.length;++n)a[n]=t[n]-e[s]}const a=t.length-2,r=Array.from({length:a},(()=>new Array(e.length)));for(let t=0;t<e.length;++t){const e=n[t];for(let n=0;n<a;++n){const a=-e[n]/s[n],o=e[n+2]/s[n+1];r[n][t]=Math.max(0,Math.min(a,o))}}return r}(c,d);if(null!==r&&"slaney"===r)for(let s=0;s<t;++s){const t=u[s],n=2/(d[s+2]-d[s]);for(let s=0;s<e;++s)t[s]*=n}return u}function jw(e,t,s,n,a){if(s<=0)throw new Error("reference must be greater than zero");if(n<=0)throw new Error("min_value must be greater than zero");s=Math.max(n,s);const r=Math.log10(s);for(let s=0;s<e.length;++s)e[s]=t*Math.log10(Math.max(n,e[s])-r);if(null!==a){if(a<=0)throw new Error("db_range must be greater than zero");const t=re(e)[0]-a;for(let s=0;s<e.length;++s)e[s]=Math.max(e[s],t)}return e}async function Uw(e,t,s,n,{fft_length:a=null,power:r=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,mel_filters:d=null,mel_floor:u=1e-10,log_mel:h=null,reference:_=1,min_value:p=1e-10,db_range:m=null,remove_dc_offset:f=null,min_num_frames:g=null,max_num_frames:w=null,do_pad:y=!0,transpose:x=!1}={}){const b=t.length;if(null===a&&(a=s),s>a)throw Error(`frame_length (${s}) may not be larger than fft_length (${a})`);if(b!==s)throw new Error(`Length of the window (${b}) must equal frame_length (${s})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(null===r&&null!==d)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(o){if("reflect"!==i)throw new Error(`pad_mode="${i}" not implemented yet.`);const t=Math.floor((a-1)/2)+1;e=function(e,t,s){const n=new e.constructor(e.length+t+s),a=e.length-1;for(let s=0;s<e.length;++s)n[t+s]=e[s];for(let s=1;s<=t;++s)n[t-s]=e[I(s,a)];for(let r=1;r<=s;++r)n[a+t+r]=e[I(a-r,a)];return n}(e,t,t)}let k=Math.floor(1+Math.floor((e.length-s)/n));null!==g&&k<g&&(k=g);const v=l?Math.floor(a/2)+1:a;let M=k,E=k;null!==w&&(w>k?y&&(E=w):E=M=w);const A=new ce(a),C=new Float64Array(a),T=new Float64Array(A.outputBufferSize),F=new Float32Array(v*E);for(let a=0;a<M;++a){const r=a*n,o=Math.min(e.length-r,s);o!==s&&C.fill(0,0,s);for(let t=0;t<o;++t)C[t]=e[r+t];if(f){let e=0;for(let t=0;t<o;++t)e+=C[t];const t=e/o;for(let e=0;e<o;++e)C[e]-=t}if(null!==c){for(let e=o-1;e>=1;--e)C[e]-=c*C[e-1];C[0]*=1-c}for(let e=0;e<t.length;++e)C[e]*=t[e];A.realTransform(T,C);for(let e=0;e<v;++e){const t=e<<1;F[e*E+a]=T[t]**2+T[t+1]**2}}if(null!==r&&2!==r){const e=2/r;for(let t=0;t<F.length;++t)F[t]**=e}const S=d.length;let P=await Ue(new Ne("float32",d.flat(),[S,v]),new Ne("float32",F,[v,E]));x&&(P=P.transpose(1,0));const z=P.data;for(let e=0;e<z.length;++e)z[e]=Math.max(u,z[e]);if(null!==r&&null!==h){const e=Math.min(z.length,M*S);switch(h){case"log":for(let t=0;t<e;++t)z[t]=Math.log(z[t]);break;case"log10":for(let t=0;t<e;++t)z[t]=Math.log10(z[t]);break;case"dB":if(1===r)!function(e,t=1,s=1e-5,n=null){jw(e,20,t,s,n)}(z,_,p,m);else{if(2!==r)throw new Error(`Cannot use log_mel option '${h}' with power ${r}`);!function(e,t=1,s=1e-10,n=null){jw(e,10,t,s,n)}(z,_,p,m)}break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return P}function Rw(e,t,{periodic:s=!0,frame_length:n=null,center:a=!0}={}){const r=s?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(r).fill(1);break;case"hann":case"hann_window":o=Lw(r);break;case"hamming":o=Bw(r);break;case"povey":o=Lw(r).map((e=>Math.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(s&&(o=o.subarray(0,e)),null===n)return o;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);return o}function qw(e,t,s){for(let n=0;n<s.length;++n)e.setUint8(t+n,s.charCodeAt(n))}class Gw{constructor(e,t){this.audio=e,this.sampling_rate=t}toWav(){return function(e,t){let s=44;const n=new ArrayBuffer(s+4*e.length),a=new DataView(n);qw(a,0,"RIFF"),a.setUint32(4,36+4*e.length,!0),qw(a,8,"WAVE"),qw(a,12,"fmt "),a.setUint32(16,16,!0),a.setUint16(20,3,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,4*t,!0),a.setUint16(32,4,!0),a.setUint16(34,32,!0),qw(a,36,"data"),a.setUint32(40,4*e.length,!0);for(let t=0;t<e.length;++t,s+=4)a.setFloat32(s,e[t],!0);return n}(this.audio,this.sampling_rate)}toBlob(){const e=this.toWav();return new Blob([e],{type:"audio/wav"})}async save(e){let t;if(x.IS_BROWSER_ENV){if(x.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");t=L}else{if(!x.IS_FS_AVAILABLE)throw new Error("Unable to save because filesystem is disabled in this environment.");t=async(e,t)=>{let s=await t.arrayBuffer();N.writeFileSync(e,Buffer.from(s))}}await t(e,this.toBlob())}}class Ww extends Sw{constructor(e){super(e);const t=this.config.sampling_rate,s=Vw(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=Rw(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Uw(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){Pw(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const e=2*this.std,s=t.data;for(let t=0;t<s.length;++t)s[t]=(s[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}}class Xw extends Sw{async _call(e){Pw(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!=0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const s=[1,t,e.length/t];return{input_values:new Ne("float32",e,s)}}}class Hw extends Sw{constructor(e){super(e),this.mel_filters=Vw(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=Vw(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=Rw(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,s,n){let a,r=!1;const o=e.length-t;if(o>0){if("rand_trunc"!==s)throw new Error(`Truncation strategy "${s}" not implemented`);{r=!0;const s=Math.floor(Math.random()*(o+1));e=e.subarray(s,s+t),a=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}}else{if(o<0){let s=new Float64Array(t);if(s.set(e),"repeat"===n)for(let n=e.length;n<t;n+=e.length)s.set(e.subarray(0,Math.min(e.length,t-n)),n);else if("repeatpad"===n)for(let t=e.length;t<-o;t+=e.length)s.set(e,t);e=s}if("fusion"===s)throw new Error(`Truncation strategy "${s}" not implemented`);a=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return a.unsqueeze_(0)}async _extract_fbank_features(e,t,s=null){return Uw(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){Pw(e,"ClapFeatureExtractor");return{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}class Jw extends Xw{}class Kw extends Sw{async _call(e){Pw(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new Ne("float32",e,t)}}}class Qw extends Sw{async _call(e){Pw(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new Ne("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const s=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(const t of e.tolist()){const e=[];let a=-1;for(let s=0;s<t.length;++s){const n=Y(t[s]),[r,o]=re(n),[i,l]=[s,s+1];o!==a?(a=o,e.push({id:o,start:i,end:l,score:r})):(e.at(-1).end=l,e.at(-1).score+=r)}n.push(e.map((({id:e,start:t,end:n,score:a})=>({id:e,start:t*s,end:n*s,confidence:a/(n-t)}))))}return n}}class Zw extends Sw{constructor(e){super(e);const t=this.config.sampling_rate,s=Vw(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=Rw(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return Uw(e=e.map((e=>32768*e)),this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:a=!0}={}){Pw(e,"SeamlessM4TFeatureExtractor");let r,o=await this._extract_fbank_features(e,this.config.max_length);if(n){const[e,t]=o.dims,s=o.data;for(let n=0;n<t;++n){let a=0;for(let r=0;r<e;++r)a+=s[r*t+n];const r=a/e;let o=0;for(let a=0;a<e;++a)o+=(s[a*t+n]-r)**2;o/=e-1;const i=Math.sqrt(o+1e-7);for(let a=0;a<e;++a){const e=a*t+n;s[e]=(s[e]-r)/i}}}if(t){const[e,t]=o.dims,n=o.data,i=e%s;if(i>0){const s=new Float32Array(t*(e+i));s.set(n),s.fill(this.config.padding_value,n.length);const l=e+i;o=new Ne(o.type,s,[l,t]),a&&(r=new Ne("int64",new BigInt64Array(l),[1,l]),r.data.fill(1n,0,e))}}const[i,l]=o.dims,c=this.config.stride;if(0!==i%c)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const d=o.view(1,Math.floor(i/c),l*c),u={input_features:d};if(a){const e=d.dims[1],t=new BigInt64Array(e);if(r){const e=r.data;for(let s=1,n=0;s<i;s+=c,++n)t[n]=e[s]}else t.fill(1n);u.attention_mask=new Ne("int64",t,[1,e])}return u}}class Yw extends Jw{}class ey extends Sw{}class ty extends Sw{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,s=e.reduce(((e,s)=>e+(s-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(s+1e-7)))}async _call(e){Pw(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 s=[1,t.length];return{input_values:new Ne("float32",t,s),attention_mask:new Ne("int64",new BigInt64Array(t.length).fill(1n),s)}}}class sy extends Sw{constructor(e){super(e);const t=this.config.sampling_rate,s=Vw(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=Rw(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return Uw(e=e.map((e=>32768*e)),this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Pw(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){const e=t.mean(1).data,s=t.data,[n,a,r]=t.dims;for(let t=0;t<n;++t){const n=t*a*r,o=t*r;for(let t=0;t<a;++t){const a=n+t*r;for(let t=0;t<r;++t)s[a+t]-=e[o+t]}}}return{input_features:t}}}class ny extends Sw{constructor(e){super(e),this.config.mel_filters??=Vw(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Rw(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await Uw(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=t.data,n=re(s)[0];for(let e=0;e<s.length;++e)s[e]=(Math.max(s[e],n-8)+4)/4;return t}async _call(e,{max_length:t=null}={}){let s;Pw(e,"WhisperFeatureExtractor");const n=t??this.config.n_samples;e.length>n?(e.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e));return{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}}class ay{static async from_pretrained(e,t={}){const s=await J(e,Ja,!0,t),n=s.feature_extractor_type,a=o[n];if(!a)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Ha}.`);return new a(s)}}class ry extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;async _call(e){return await this.feature_extractor(e)}}class oy extends ag{static tokenizer_class=Na;static image_processor_class=xw}const iy="<|image|>",ly=/<\|image_\d+\|>/g;class cy extends ag{static image_processor_class=xw;static tokenizer_class=Na;async _call(e,t=null,{padding:s=!0,truncation:n=!0,num_crops:a=null}={}){let r,o;if(Array.isArray(e)||(e=[e]),t){o=await this.image_processor(t,{num_crops:a});const{num_img_tokens:i}=o,l=e.map(((e,t)=>e.split(ly).join(iy.repeat(i[t]))));r=this.tokenizer(l,{padding:s,truncation:n});const c=this.tokenizer.model.convert_tokens_to_ids([iy])[0];r.input_ids.map_((e=>e==c?-e:e))}else r=this.tokenizer(e);return{...r,...o}}}const dy="<image>";class uy extends ag{static tokenizer_class=Na;static image_processor_class=xw;static uses_processor_config=!1;async _call(e,t=null,s={}){t||(console.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,a=this.image_processor.config.image_seq_length;let r;t.some((e=>e.includes(dy)))?r=t.map((e=>{const t=e.replaceAll(dy,dy.repeat(a)),s=t.lastIndexOf(dy),r=-1===s?0:s+7;return t.slice(0,r)+n+t.slice(r)+"\n"})):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),r=t.map((t=>function(e,t,s,n,a){return`${n.repeat(s*a)}${t}${e}\n`}(t,n,a,dy,e.length))));const o=this.tokenizer(r,s);return{...await this.image_processor(e,s),...o}}}class hy extends ag{static feature_extractor_class=Qw;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}class _y extends ag{static image_processor_class=xw;static tokenizer_class=Na;async _call(e,t=null,...s){let n,a;if(Array.isArray(e)||(e=[e]),t&&(n=await this.image_processor(t),a=n.image_grid_thw),a){let t=this.image_processor.config.merge_size**2,s=0;const n=a.tolist();e=e.map((e=>{for(;e.includes("<|image_pad|>");){const a=Number(n[s++].reduce(((e,t)=>e*t),1n));e=e.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(a/t)))}return e.replaceAll("<|placeholder|>","<|image_pad|>")}))}return{...this.tokenizer(e),...n}}}class py extends ag{static image_processor_class=xw;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)}}class my extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;async _call(e){return await this.feature_extractor(e)}}class fy extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;static uses_processor_config=!0;async _call(e,t=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){const a=t.length,{input_features:r}=await this.feature_extractor(t,{...s,max_length:a}),o=Math.round(a/this.config.encoder_ds_factor+1e-4),i=1+Math.ceil(o/this.config.stack_factor);n.audio_token_len=[i],n.audio_values=r;const l=this.config.audio_placeholder;if(!e.includes(l))throw new Error(`The input text does not contain the image token ${l}.`);e=e.replaceAll(l,l.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}}class gy extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;async _call(e){return await this.feature_extractor(e)}}class wy extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;async _call(e){return await this.feature_extractor(e)}}class yy extends ag{static tokenizer_class=Na;static feature_extractor_class=ay;async _call(e){return await this.feature_extractor(e)}}class xy{static async from_pretrained(e,t={}){const s=await J(e,Ka,!0,t),{image_processor_type:n,feature_extractor_type:a,processor_class:l}=s;if(l&&i[l])return i[l].from_pretrained(e,t);if(!n&&!a)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const c={};if(n){const e=r[n];if(!e)throw new Error(`Unknown image_processor_type: '${n}'.`);c.image_processor=new e(s)}if(a){const e=r[a];if(e)c.image_processor=new e(s);else{const e=o[a];if(!e)throw new Error(`Unknown feature_extractor_type: '${a}'.`);c.feature_extractor=new e(s)}}return new ag({},c)}}async function by(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>br.read(e))))}async function ky(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>"string"==typeof e||e instanceof URL?zw(e,t):e instanceof Float64Array?new Float32Array(e):e)))}function vy(e,t){t&&(e=e.map((e=>0|e)));const[s,n,a,r]=e;return{xmin:s,ymin:n,xmax:a,ymax:r}}class My extends C{constructor({task:e,model:t,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=t,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}}class Ey extends My{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),a="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid():e=>new Ne("float32",Y(e.data),e.dims),r=this.model.config.id2label,o=[];for(const e of n.logits){const s=a(e),n=await qe(s,t),i=n[0].tolist(),l=n[1].tolist().map(((e,t)=>({label:r?r[e]:`LABEL_${e}`,score:i[t]})));1===t?o.push(...l):o.push(l)}return Array.isArray(e)||1===t?o:o[0]}}class Ay extends My{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,r=this.model.config.id2label,o=[];for(let e=0;e<a.dims[0];++e){const s=n.input_ids[e],i=a[e],l=[];for(let e=0;e<i.dims[0];++e){const n=i[e],a=re(n.data)[1],o=r?r[a]:`LABEL_${a}`;if(t.includes(o))continue;const c=this.tokenizer.decode([s[e].item()],{skip_special_tokens:!0});if(""===c)continue;const d=Y(n.data);l.push({entity:o,score:d[a],index:e,word:c})}o.push(l)}return s?o:o[0]}}class Cy extends My{constructor(e){super(e)}async _call(e,t,{top_k:s=1}={}){const n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),{start_logits:a,end_logits:r}=await this.model(n),o=n.input_ids.tolist(),i=n.attention_mask.tolist(),l=this.tokenizer.all_special_ids,c=[];for(let e=0;e<a.dims[0];++e){const t=o[e],n=t.findIndex((e=>e==this.tokenizer.sep_token_id)),d=(i[e].map(((e,s)=>1==e&&(0===s||s>n&&-1===l.findIndex((e=>e==t[s]))))),a[e].tolist()),u=r[e].tolist();for(let s=1;s<d.length;++s)(0==i[e]||s<=n||-1!==l.findIndex((e=>e==t[s])))&&(d[s]=-1/0,u[s]=-1/0);const h=Y(d).map(((e,t)=>[e,t])),_=Y(u).map(((e,t)=>[e,t]));h[0][0]=0,_[0][0]=0;const p=z(h,_).filter((e=>e[0][1]<=e[1][1])).map((e=>[e[0][1],e[1][1],e[0][0]*e[1][0]])).sort(((e,t)=>t[2]-e[2]));for(let e=0;e<Math.min(p.length,s);++e){const[s,n,a]=p[e],r=t.slice(s,n+1),o=this.tokenizer.decode(r,{skip_special_tokens:!0});c.push({answer:o,score:a})}}return 1===s?c[0]:c}}class Ty extends My{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:n}=await this.model(s),a=[],r=s.input_ids.tolist();for(let e=0;e<r.length;++e){const s=r[e],o=s.findIndex((e=>e==this.tokenizer.mask_token_id));if(-1===o)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const i=n[e][o],l=await qe(new Ne("float32",Y(i.data),i.dims),t),c=l[0].tolist(),d=l[1].tolist();a.push(d.map(((e,t)=>{const n=s.slice();return n[o]=e,{score:c[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}})))}return Array.isArray(e)?a:a[0]}}class Fy extends My{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map((e=>this.model.config.prefix+e)));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map((e=>s[this.task].prefix+e)));const n=this.tokenizer,a={padding:!0,truncation:!0};let r;r=this instanceof Py&&"_build_translation_inputs"in n?n._build_translation_inputs(e,a,t):n(e,a);const o=await this.model.generate({...r,...t});return n.batch_decode(o,{skip_special_tokens:!0}).map((e=>({[this._key]:e})))}}class Sy extends Fy{_key="summary_text";constructor(e){super(e)}}class Py extends Fy{_key="translation_text";constructor(e){super(e)}}function zy(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class Iy extends My{constructor(e){super(e)}async _call(e,t={}){let s,n=!1,a=!1;if("string"==typeof e)s=e=[e];else if(Array.isArray(e)&&e.every((e=>"string"==typeof e)))n=!0,s=e;else{if(zy(e))e=[e];else{if(!Array.isArray(e)||!e.every(zy))throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0}a=!0,s=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0})))}const r=t.add_special_tokens??!1,o=!a&&(t.return_full_text??!0);this.tokenizer.padding_side="left";const i=this.tokenizer(s,{add_special_tokens:r,padding:!0,truncation:!0}),l=await this.model.generate({...i,...t}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0});let d;!o&&i.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(i.input_ids,{skip_special_tokens:!0}).map((e=>e.length)));const u=Array.from({length:e.length},(e=>[]));for(let t=0;t<c.length;++t){const s=Math.floor(t/l.dims[0]*e.length);d&&(c[t]=c[t].slice(d[s])),u[s].push({generated_text:a?[...e[s],{role:"assistant",content:c[t]}]:c[t]})}return n||1!==u.length?u:u[0]}}class Ly extends My{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map((([e,t])=>[e.toLowerCase(),t]))),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){const a=Array.isArray(e);a||(e=[e]),Array.isArray(t)||(t=[t]);const r=t.map((e=>s.replace("{}",e))),o=n||1===t.length,i=[];for(const s of e){const e=[];for(const t of r){const n=this.tokenizer(s,{text_pair:t,padding:!0,truncation:!0}),a=await this.model(n);o?e.push([a.logits.data[this.contradiction_id],a.logits.data[this.entailment_id]]):e.push(a.logits.data[this.entailment_id])}const n=(o?e.map((e=>Y(e)[1])):Y(e)).map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));i.push({sequence:s,labels:n.map((e=>t[e[1]])),scores:n.map((e=>e[0]))})}return a?i:i[0]}}class By extends My{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:s=!1,quantize:n=!1,precision:a="binary"}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(r);let i=o.last_hidden_state??o.logits??o.token_embeddings;if("none"===t);else if("mean"===t)i=Xe(i,r.attention_mask);else{if("cls"!==t)throw Error(`Pooling method '${t}' not supported.`);i=i.slice(null,0)}return s&&(i=i.normalize(2,-1)),n&&(i=ut(i,a)),i}}class Oy extends My{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const s=await by(e),{pixel_values:n}=await this.processor(s),a=await this.model({pixel_values:n});let r;if(t){if(!("pooler_output"in a))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");r=a.pooler_output}else r=a.last_hidden_state??a.logits??a.image_embeds;return r}}class $y extends My{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=this.processor.feature_extractor.config.sampling_rate,n=await ky(e,s),a=this.model.config.id2label,r=[];for(const e of n){const s=await this.processor(e),n=(await this.model(s)).logits[0],o=await qe(new Ne("float32",Y(n.data),n.dims),t),i=o[0].tolist(),l=o[1].tolist().map(((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:i[t]})));r.push(l)}return Array.isArray(e)?r:r[0]}}class Ny extends My{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a sound of {}."}={}){const n=!Array.isArray(e);n&&(e=[e]);const a=t.map((e=>s.replace("{}",e))),r=this.tokenizer(a,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await ky(e,o),l=[];for(const e of i){const s=await this.processor(e),n=Y((await this.model({...r,...s})).logits_per_audio.data);l.push([...n].map(((e,s)=>({score:e,label:t[s]}))))}return n?l[0]:l}}class Dy extends My{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const s=!Array.isArray(e);s&&(e=[e]);const n=this.processor.feature_extractor.config.sampling_rate,a=await ky(e,n),r=[];for(const e of a){const t=await this.processor(e),s=(await this.model(t)).logits[0],n=[];for(const e of s)n.push(re(e.data)[1]);const a=this.tokenizer.decode(n);r.push({text:a})}return s?r[0]:r}async _call_whisper(e,t){const s=t.return_timestamps??!1,n=t.chunk_length_s??0,a=t.force_full_sequences??!1;let r=t.stride_length_s??null;const o={...t};"word"===s&&(o.return_token_timestamps=!0,o.return_timestamps=!1);const i=!Array.isArray(e);i&&(e=[e]);const l=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,c=this.processor.feature_extractor.config.hop_length,d=this.processor.feature_extractor.config.sampling_rate,u=await ky(e,d),h=[];for(const e of u){let t=[];if(n>0){if(null===r)r=n/6;else if(n<=r)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const s=d*n,a=d*r,o=s-2*a;let i=0;for(;;){const n=i+s,r=e.subarray(i,n),l=await this.processor(r),c=0===i,d=n>=e.length;if(t.push({stride:[r.length,c?0:a,d?0:a],input_features:l.input_features,is_last:d}),d)break;i+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of t){o.num_frames=Math.floor(e.stride[0]/c);const t=await this.model.generate({inputs:e.input_features,...o});"word"===s?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map((e=>ue(e,2)))):e.tokens=t[0].tolist(),e.stride=e.stride.map((e=>e/d))}const[i,u]=this.tokenizer._decode_asr(t,{time_precision:l,return_timestamps:s,force_full_sequences:a});h.push({text:i,...u})}return i?h[0]:h}async _call_moonshine(e,t){const s=!Array.isArray(e);s&&(e=[e]);const n=this.processor.feature_extractor.config.sampling_rate,a=await ky(e,n),r=[];for(const e of a){const s=await this.processor(e),a=6*Math.floor(e.length/n),o=await this.model.generate({max_new_tokens:a,...t,...s}),i=this.processor.batch_decode(o,{skip_special_tokens:!0})[0];r.push({text:i})}return s?r[0]:r}}class Vy extends My{constructor(e){super(e)}async _call(e,t={}){const s=Array.isArray(e),n=await by(e),{pixel_values:a}=await this.processor(n),r=[];for(const e of a){e.dims=[1,...e.dims];const s=await this.model.generate({inputs:e,...t}),n=this.tokenizer.batch_decode(s,{skip_special_tokens:!0}).map((e=>({generated_text:e.trim()})));r.push(n)}return s?r:r[0]}}class jy extends My{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const s=await by(e),{pixel_values:n}=await this.processor(s),a=await this.model({pixel_values:n}),r=this.model.config.id2label,o=[];for(const e of a.logits){const s=await qe(new Ne("float32",Y(e.data),e.dims),t),n=s[0].tolist(),a=s[1].tolist().map(((e,t)=>({label:r?r[e]:`LABEL_${e}`,score:n[t]})));o.push(a)}return Array.isArray(e)?o:o[0]}}class Uy extends My{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:a=null,target_sizes:r=null,subtask:o=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const i=await by(e),l=i.map((e=>[e.height,e.width])),c=await this.processor(i),{inputNames:d,outputNames:u}=this.model.sessions.model;if(!d.includes("pixel_values")){if(1!==d.length)throw Error(`Expected a single input name, but got ${d.length} inputs: ${d}.`);const e=d[0];if(e in c)throw Error(`Input name ${e} already exists in the inputs.`);c[e]=c.pixel_values}const h=await this.model(c);let _=null;if(null!==o)_=this.subtasks_mapping[o];else if(this.processor.image_processor)for(const[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.image_processor){_=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}const p=this.model.config.id2label,m=[];if(o)if("panoptic"===o||"instance"===o){const e=_(h,t,s,n,a,r??l)[0],o=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(o.data.length);for(let s=0;s<o.data.length;++s)o.data[s]===t.id&&(e[s]=255);const s=new br(e,o.dims[1],o.dims[0],1);m.push({score:t.score,label:p[t.label_id],mask:s})}}else{if("semantic"!==o)throw Error(`Subtask ${o} not supported.`);{const{segmentation:e,labels:t}=_(h,r??l)[0];for(const s of t){const t=new Uint8ClampedArray(e.data.length);for(let n=0;n<e.data.length;++n)e.data[n]===s&&(t[n]=255);const n=new br(t,e.dims[1],e.dims[0],1);m.push({score:null,label:p[s],mask:n})}}}else{const e=1e-5,t=h[u[0]];for(let s=0;s<l.length;++s){const n=l[s],a=t[s];a.data.some((t=>t<-e||t>1+e))&&a.sigmoid_();const r=await br.fromTensor(a.mul_(255).to("uint8")).resize(n[1],n[0]);m.push({label:null,score:null,mask:r})}}return m}}class Ry extends Uy{constructor(e){super(e)}async _call(e,t={}){if(Array.isArray(e)&&1!==e.length)throw Error("Background removal pipeline currently only supports a batch size of 1.");const s=await by(e),n=await super._call(e,t);return s.map(((e,t)=>{const s=e.clone();return s.putAlpha(n[t].mask),s}))}}class qy extends My{constructor(e){super(e)}async _call(e,t,{hypothesis_template:s="This is a photo of {}"}={}){const n=Array.isArray(e),a=await by(e),r=t.map((e=>s.replace("{}",e))),o=this.tokenizer(r,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:i}=await this.processor(a),l=await this.model({...o,pixel_values:i}),c="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>Y(e.data),d=[];for(const e of l.logits_per_image){const s=[...c(e)].map(((e,s)=>({score:e,label:t[s]})));s.sort(((e,t)=>t.score-e.score)),d.push(s)}return n?d:d[0]}}class Gy extends My{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:s=!1}={}){const n=Array.isArray(e);if(n&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const a=await by(e),r=s?null:a.map((e=>[e.height,e.width])),{pixel_values:o,pixel_mask:i}=await this.processor(a),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,r),d=this.model.config.id2label,u=c.map((e=>e.boxes.map(((t,n)=>({score:e.scores[n],label:d[e.classes[n]],box:vy(t,!s)})))));return n?u:u[0]}}class Wy extends My{constructor(e){super(e)}async _call(e,t,{threshold:s=.1,top_k:n=null,percentage:a=!1}={}){const r=Array.isArray(e),o=await by(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];for(let e=0;e<o.length;++e){const r=o[e],d=a?null:[[r.height,r.width]],u=l.pixel_values[e].unsqueeze_(0),h=await this.model({...i,pixel_values:u});let _;if("post_process_grounded_object_detection"in this.processor){const e=this.processor.post_process_grounded_object_detection(h,i.input_ids,{box_threshold:s,text_threshold:s,target_sizes:d})[0];_=e.boxes.map(((t,s)=>({score:e.scores[s],label:e.labels[s],box:vy(t,!a)})))}else{const e=this.processor.image_processor.post_process_object_detection(h,s,d,!0)[0];_=e.boxes.map(((s,n)=>({score:e.scores[n],label:t[e.classes[n]],box:vy(s,!a)})))}_.sort(((e,t)=>t.score-e.score)),null!==n&&(_=_.slice(0,n)),c.push(_)}return r?c:c[0]}}class Xy extends My{constructor(e){super(e)}async _call(e,t,s={}){const n=(await by(e))[0],{pixel_values:a}=await this.processor(n),r=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(r,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,i=await this.model.generate({inputs:a,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...s}),l=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/);let c=null;return l&&l.length>=2&&(c=l[1].trim()),[{answer:c}]}}class Hy extends My{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(t),n=this.model.config.sampling_rate;return new Gw(s.data,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await gf.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new Ne("float32",t,[1,t.length]);else if(!(t instanceof Ne))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model.generate_speech(s,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return new Gw(n.data,a)}}class Jy extends My{constructor(e){super(e)}async _call(e){const t=await by(e),s=await this.processor(t),n=await this.model(s),a=[];for(const e of n.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");a.push(br.fromTensor(t))}return a.length>1?a:a[0]}}class Ky extends My{constructor(e){super(e)}async _call(e){const t=await by(e),s=await this.processor(t),{predicted_depth:n}=await this.model(s),a=[];for(let e=0;e<t.length;++e){const s=n[e],[r,o]=s.dims.slice(-2),[i,l]=t[e].size,c=(await je(s.view(1,1,r,o),{size:[l,i],mode:"bilinear"})).view(l,i),d=c.min().item(),u=c.max().item(),h=c.sub(d).div_(u-d).mul_(255).to("uint8").unsqueeze(0),_=br.fromTensor(h);a.push({predicted_depth:c,depth:_})}return a.length>1?a:a[0]}}const Qy=Object.freeze({"text-classification":{tokenizer:Na,pipeline:Ey,model:wf,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:Na,pipeline:Ay,model:yf,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:Na,pipeline:Cy,model:Af,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:Na,pipeline:Ty,model:Ef,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:Na,pipeline:Sy,model:xf,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:Na,pipeline:Py,model:xf,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:Na,pipeline:Fy,model:xf,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:Na,pipeline:Iy,model:Mf,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:Na,pipeline:Ly,model:wf,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:$y,model:Of,processor:xy,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:Na,pipeline:Ny,model:gf,processor:xy,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:Na,pipeline:Dy,model:[bf,Bf],processor:xy,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:Na,pipeline:Hy,model:[vf,kf],processor:[xy,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:Na,pipeline:Vy,model:Cf,processor:xy,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:jy,model:Tf,processor:xy,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Uy,model:[Ff,Sf,Pf],processor:xy,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Ry,model:[Ff,Sf,Pf],processor:xy,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:Na,pipeline:qy,model:gf,processor:xy,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Gy,model:zf,processor:xy,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:Na,pipeline:Wy,model:If,processor:xy,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:Na,pipeline:Xy,model:Df,processor:xy,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Jy,model:jf,processor:xy,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ky,model:Uf,processor:xy,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:Na,pipeline:By,model:gf,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:xy,pipeline:Oy,model:[Gf,gf],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Zy=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Yy(e,t=null,{progress_callback:s=null,config:n=null,cache_dir:a=null,local_files_only:r=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:u=null,session_options:h={}}={}){e=Zy[e]??e;const _=Qy[e.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(Qy)}]`);t||(t=_.default.model,console.log(`No model specified. Using default model: "${t}".`));const p={progress_callback:s,config:n,cache_dir:a,local_files_only:r,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:u,session_options:h},m=new Map([["tokenizer",_.tokenizer],["model",_.model],["processor",_.processor]]),f=await async function(e,t,s){const n=Object.create(null),a=[];for(const[r,o]of e.entries()){if(!o)continue;let e;e=Array.isArray(o)?new Promise((async(e,n)=>{let a;for(const r of o){if(null===r)return void e(null);try{return void e(await r.from_pretrained(t,s))}catch(e){if(e.message?.includes("Unsupported model type"))a=e;else{if(!e.message?.includes("Could not locate file"))return void n(e);a=e}}}n(a)})):o.from_pretrained(t,s),n[r]=e,a.push(e)}await Promise.all(a);for(const[e,t]of Object.entries(n))n[e]=await t;return n}(m,t,p);f.task=e,T(s,{status:"ready",task:e,model:t});return new(0,_.pipeline)(f)}class ex{constructor(e,t){this.image=e,this.timestamp=t}}class tx{constructor(e,t){e.length>0&&e[0]instanceof br&&(e=e.map(((s,n)=>new ex(s,(n+1)/(e.length+1)*t)))),this.frames=e,this.duration=t}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function sx(e,{num_frames:t=null,fps:s=null}={}){if(!x.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(null==t&&null==s)throw new Error("Either num_frames or fps must be provided.");const n=[],a=document.createElement("video");if(a.crossOrigin="anonymous",a.muted=!0,"string"==typeof e)a.src=e;else if(e instanceof Blob)a.src=URL.createObjectURL(e);else{if(!(e instanceof HTMLVideoElement))throw new Error("Invalid URL or video element provided.");a.src=e.src}if(await new Promise((e=>a.onloadedmetadata=e)),a.seekable.start(0)===a.seekable.end(0)){const e=await fetch(a.src),t=await e.blob();a.src=URL.createObjectURL(t),await new Promise((e=>a.onloadedmetadata=e))}const r=a.duration;let o,i;null!=t?(o=t,i=1===t?0:r/(t-1)):(i=1/s,o=Math.floor(r/i));let l=[];for(let e=0;e<o;++e)l.push(1===t?r/2:e*i);const c=document.createElement("canvas");c.width=a.videoWidth,c.height=a.videoHeight;const d=c.getContext("2d",{willReadFrequently:!0});for(const e of l){a.currentTime=e,await new Promise((e=>{a.onseeked=e})),d.drawImage(a,0,0,c.width,c.height);const t=d.getImageData(0,0,c.width,c.height),s=new br(t.data,c.width,c.height,4),r=new ex(s,e);n.push(r)}return a.remove(),new tx(n,r)}class nx{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const ax=x.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e);class rx extends nx{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:a=!0,decode_kwargs:r={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=s??ax,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:a,...r,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(e){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 s=e[0];this.token_callback_function?.(s),this.token_cache=P(this.token_cache,s);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let a;t||n.endsWith("\n")?(a=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&$s(n.charCodeAt(n.length-1))?(a=n.slice(this.print_len),this.print_len+=a.length):(a=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=a.length),this.on_finalized_text(a,!1)}end(){let e;if(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}else e="";this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===ax&&x.IS_PROCESS_AVAILABLE&&this.callback_function?.("\n")}}class ox extends rx{constructor(e,{skip_prompt:t=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:a=null,on_chunk_end:r=null,on_finalize:o=null,time_precision:i=.02,skip_special_tokens:l=!0,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,skip_special_tokens:l,callback_function:s,token_callback_function:n,decode_kwargs:c}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=a,this.on_chunk_end=r,this.on_finalize=o,this.time_precision=i,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const t=e[0];if(1===t.length){const s=Number(t[0])-this.timestamp_begin;if(s>=0){const t=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(t):this.on_chunk_start?.(t),this.waiting_for_timestamp=!this.waiting_for_timestamp,e=[[]]}}return super.put(e)}end(){super.end(),this.on_finalize?.()}}var ix=a.Bup,lx=a.O0k,cx=a.MRG,dx=a.o57,ux=a.iKv,hx=a.ELH,_x=a.Hi6,px=a.G2X,mx=a.crd,fx=a.UH6,gx=a.ptb,wx=a.EJs,yx=a.CMU,xx=a.fZ7,bx=a.rKH,kx=a.m68,vx=a.Plw,Mx=a.$z$,Ex=a._TZ,Ax=a.W6E,Cx=a.QNG,Tx=a.nuw,Fx=a.JP3,Sx=a.w0O,Px=a.HMe,zx=a.vTA,Ix=a.mvA,Lx=a.FJW,Bx=a.qCM,Ox=a.wju,$x=a.S9w,Nx=a.Yd3,Dx=a.UVV,Vx=a.yGT,jx=a.wrZ,Ux=a.BRf,Rx=a.jQR,qx=a.MOY,Gx=a.ZIt,Wx=a.V9g,Xx=a.TUv,Hx=a.xIA,Jx=a.db0,Kx=a.$TP,Qx=a.gqD,Zx=a.oye,Yx=a.v6I,eb=a.TWC,tb=a.Xh$,sb=a.F05,nb=a.MH$,ab=a.vqx,rb=a.hbt,ob=a.hbT,ib=a.E9I,lb=a.V11,cb=a.foZ,db=a.Dji,ub=a.EKW,hb=a.oaf,_b=a.bmk,pb=a.VoY,mb=a.MRX,fb=a.o2t,gb=a.rSR,wb=a.DIv,yb=a.Ft_,xb=a.bQt,bb=a.tDL,kb=a.JGb,vb=a.Hvf,Mb=a.IrO,Eb=a.wZy,Ab=a.Sm3,Cb=a.eUP,Tb=a.ZiE,Fb=a.P3b,Sb=a.$P2,Pb=a.dg9,zb=a.jld,Ib=a.fv3,Lb=a.GEs,Bb=a.yaC,Ob=a.GEu,$b=a.E_G,Nb=a.tUF,Db=a.FIB,Vb=a.nD4,jb=a.CAk,Ub=a.u2M,Rb=a.CCt,qb=a.N2L,Gb=a.S7g,Wb=a.wc1,Xb=a.h0m,Hb=a.LdY,Jb=a.Aib,Kb=a.S9m,Qb=a.kOS,Zb=a.qtL,Yb=a.mp$,ek=a.SQp,tk=a.XWm,sk=a.lHM,nk=a.PRX,ak=a.$r3,rk=a.qWZ,ok=a.IVZ,ik=a.oZ3,lk=a.ioA,ck=a.hFk,dk=a.riX,uk=a.bOZ,hk=a.F$M,_k=a.gGu,pk=a.uRS,mk=a.q7U,fk=a.wYL,gk=a.qt5,wk=a.z1x,yk=a.Vx0,xk=a.y5s,bk=a.y_I,kk=a.FSH,vk=a.jJ4,Mk=a.fRb,Ek=a.uku,Ak=a.aN4,Ck=a.Llt,Tk=a.lf8,Fk=a.NJd,Sk=a.OBR,Pk=a.nII,zk=a.$o$,Ik=a.Wgp,Lk=a.E7x,Bk=a.MzU,Ok=a.xCN,$k=a.YHO,Nk=a.ALp,Dk=a.c$o,Vk=a.C2_,jk=a.ooI,Uk=a.Ex8,Rk=a.A_V,qk=a.Efq,Gk=a.b5h,Wk=a.EX5,Xk=a.Weu,Hk=a.xUX,Jk=a.XfN,Kk=a.xNh,Qk=a.w4W,Zk=a._yz,Yk=a.L3d,ev=a.Zip,tv=a.pGQ,sv=a.Nmr,nv=a.lr8,av=a.Qs9,rv=a.Ilc,ov=a.pW7,iv=a.vTy,lv=a.$Vt,cv=a.$MY,dv=a.jWB,uv=a.twb,hv=a.Bl1,_v=a.oB7,pv=a.EPI,mv=a.cXP,fv=a.Dki,gv=a.FoX,wv=a.bEM,yv=a.IgO,xv=a.A0R,bv=a.w4p,kv=a.Fbv,vv=a.j9c,Mv=a.fen,Ev=a.ZM0,Av=a.JFO,Cv=a.DDe,Tv=a.HaQ,Fv=a.LlQ,Sv=a.IeB,Pv=a.s8j,zv=a.jzC,Iv=a.gQI,Lv=a.SXK,Bv=a.YVy,Ov=a.uwI,$v=a.NDb,Nv=a.xpG,Dv=a.yuQ,Vv=a.cpF,jv=a.i8h,Uv=a.Oaj,Rv=a.TNE,qv=a.KI$,Gv=a.pHg,Wv=a.fCQ,Xv=a.X6D,Hv=a.KkK,Jv=a.muz,Kv=a.SIh,Qv=a.CF0,Zv=a.gEj,Yv=a.Nyc,eM=a.vh2,tM=a.SzV,sM=a.SPn,nM=a._vb,aM=a.QSM,rM=a.qjJ,oM=a.nDC,iM=a.QGw,lM=a.iGD,cM=a.nD1,dM=a.pSU,uM=a.fzV,hM=a.q9s,_M=a.Uc1,pM=a.cep,mM=a.rGP,fM=a.Hff,gM=a.$ph,wM=a.$Ld,yM=a.nJ5,xM=a.mvc,bM=a.vgU,kM=a.Tk_,vM=a.e1W,MM=a.fQJ,EM=a.YKo,AM=a.syV,CM=a.IUW,TM=a.jIC,FM=a.zMO,SM=a.uB5,PM=a.qJs,zM=a.j2j,IM=a.jt4,LM=a.vdi,BM=a.Cb2,OM=a.FuQ,$M=a.PBg,NM=a.pK1,DM=a.Shx,VM=a.SX4,jM=a.adp,UM=a.Xvs,RM=a.l2J,qM=a.DbD,GM=a.j7p,WM=a.XBq,XM=a.tAq,HM=a.bFh,JM=a.PV9,KM=a.FqW,QM=a.pw$,ZM=a.R0r,YM=a.zJu,eE=a.vlr,tE=a.CIG,sE=a.AhC,nE=a.yyL,aE=a.xJk,rE=a.bKx,oE=a.d56,iE=a.VBL,lE=a.UyU,cE=a.y71,dE=a.UkL,uE=a.uFN,hE=a.okz,_E=a.G$U,pE=a.GLc,mE=a.pSS,fE=a.BQD,gE=a.Vx1,wE=a.O5n,yE=a.kjR,xE=a.UDe,bE=a.Ed4,kE=a.mOb,vE=a.Ynb,ME=a.Kwv,EE=a.EVN,AE=a.bRn,CE=a.xCl,TE=a.qQb,FE=a.vnq,SE=a.gqe,PE=a.oO_,zE=a.OPC,IE=a.Vvo,LE=a.vi3,BE=a.Yiu,OE=a.ePJ,$E=a.q56,NE=a.d7u,DE=a.O0q,VE=a.phI,jE=a.G_t,UE=a.Vkl,RE=a.CfF,qE=a.I07,GE=a.GXe,WE=a.aJl,XE=a.dYU,HE=a.cw6,JE=a.VYv,KE=a.n3o,QE=a.WoL,ZE=a.kn$,YE=a._i4,eA=a.Fex,tA=a.tCA,sA=a.g1K,nA=a.AEy,aA=a.jWM,rA=a.X0l,oA=a.RvM,iA=a.Hiq,lA=a.K5U,cA=a.k5w,dA=a.c$b,uA=a.ehA,hA=a.fim,_A=a.VT2,pA=a.yMg,mA=a.LqK,fA=a.Rcj,gA=a.tm_,wA=a.VT,yA=a.HT0,xA=a.bZR,bA=a.HfH,kA=a.$ow,vA=a.YZs,MA=a.UNt,EA=a.Pgx,AA=a.Mt5,CA=a.YR3,TA=a.cj6,FA=a.QRP,SA=a.OOL,PA=a.xfe,zA=a.zml,IA=a.C_m,LA=a.Mjg,BA=a.IvO,OA=a.kPE,$A=a.KcC,NA=a.wXv,DA=a.FmT,VA=a.W7k,jA=a.U_I,UA=a.OFW,RA=a.Hw7,qA=a.y1Z,GA=a.qph,WA=a.FDZ,XA=a.Hb,HA=a.T1J,JA=a.YqH,KA=a._MQ,QA=a.nj2,ZA=a.$g1,YA=a.BK1,eC=a.nIe,tC=a.hB$,sC=a.mPV,nC=a.b4i,aC=a.S37,rC=a.PWE,oC=a.W0U,iC=a.sG8,lC=a.Oul,cC=a.YCy,dC=a.yZM,uC=a.erL,hC=a.pe4,_C=a.z_R,pC=a.uA4,mC=a.uKS,fC=a.eQ7,gC=a.vZB,wC=a.NlK,yC=a.CBj,xC=a.J_N,bC=a.t8g,kC=a.jTN,vC=a.V7I,MC=a.Jfh,EC=a.Bz$,AC=a.DN9,CC=a.jgy,TC=a.M3c,FC=a.K66,SC=a.mKg,PC=a.k1H,zC=a.Uvp,IC=a.sIn,LC=a.pDc,BC=a.Xxh,OC=a.Bls,$C=a.TCq,NC=a.jeS,DC=a.F6T,VC=a.aJ7,jC=a.Y0u,UC=a.CJY,RC=a.kYJ,qC=a.g4F,GC=a.MHq,WC=a.rz8,XC=a.N5j,HC=a.rbM,JC=a.ZKw,KC=a.yiA,QC=a.qBz,ZC=a.LFe,YC=a.Z9R,eT=a.pBZ,tT=a.IWp,sT=a.F75,nT=a.hNN,aT=a.lX9,rT=a._Bh,oT=a.JE9,iT=a.t68,lT=a.S5F,cT=a.wAB,dT=a.$Tv,uT=a.vZ9,hT=a.s7A,_T=a.mKJ,pT=a.Ck8,mT=a.lmt,fT=a.jZx,gT=a.rZ_,wT=a.zPm,yT=a.vMO,xT=a.Obh,bT=a.XW6,kT=a.jN0,vT=a.TEh,MT=a.lPY,ET=a.ORI,AT=a.SPc,CT=a.Y8J,TT=a.Paj,FT=a.Tc6,ST=a.wfL,PT=a.EVf,zT=a.zEN,IT=a.LGm,LT=a.VD9,BT=a.Xuy,OT=a.Fip,$T=a.FW1,NT=a.FgJ,DT=a.ZVw,VT=a.vqf,jT=a.zgG,UT=a.a86,RT=a.A3P,qT=a.knH,GT=a.GZ7,WT=a.$Mx,XT=a.jCl,HT=a.jlM,JT=a.tU7,KT=a.k1d,QT=a.oKc,ZT=a.Uys,YT=a.MYn,eF=a.WJS,tF=a.lAn,sF=a.ZNn,nF=a._XV,aF=a.$hY,rF=a.e3g,oF=a.git,iF=a.wcw,lF=a.vN5,cF=a.nPB,dF=a.KzV,uF=a.izm,hF=a.Gzn,_F=a.CR8,pF=a.YEl,mF=a.Ghe,fF=a.ZnA,gF=a.VkI,wF=a.L1Z,yF=a.jbx,xF=a.$Un,bF=a.Y2A,kF=a._dY,vF=a.Tyd,MF=a.aLA,EF=a.Jlf,AF=a.pgF,CF=a.A0H,TF=a.U0l,FF=a.guh,SF=a.tjD,PF=a.XyO,zF=a.yD1,IF=a.SJu,LF=a.NXG,BF=a.hf2,OF=a.DK6,$F=a.V2z,NF=a.jZD,DF=a.f7H,VF=a.XNj,jF=a.lyK,UF=a.bHs,RF=a.d52,qF=a.mdL,GF=a.yWo,WF=a.oXw,XF=a.u2I,HF=a.p$Q,JF=a.D9b,KF=a.T2J,QF=a.FS1,ZF=a.xIZ,YF=a.h6w,eS=a.zcr,tS=a.Tl7,sS=a.RZG,nS=a.Vsd,aS=a.Lub,rS=a.lAo,oS=a.t7I,iS=a.REm,lS=a.YOx,cS=a.MNq,dS=a.vts,uS=a.hKP,hS=a.Giz,_S=a.d8n,pS=a.fl$,mS=a.sns,fS=a.eu8,gS=a.Xi0,wS=a.Xsl,yS=a.Ilk,xS=a.Ccq,bS=a.yQp,kS=a.bpB,vS=a.Vnd,MS=a.MgS,ES=a.sbd,AS=a.tKX,CS=a.RIx,TS=a.Bi5,FS=a.FlD,SS=a.G3L,PS=a.fX1,zS=a.Xrw,IS=a.q85,LS=a.DJ0,BS=a.DVM,OS=a.rQe,$S=a.rgj,NS=a.RBo,DS=a.HLV,VS=a.dBN,jS=a.YjU,US=a.SsB,RS=a.U14,qS=a.g$7,GS=a.dt5,WS=a.AVh,XS=a.iAJ,HS=a.gJd,JS=a.UX7,KS=a.Z83,QS=a.wRc,ZS=a.cR9,YS=a.MNc,eP=a.gbg,tP=a.zPu,sP=a.NIO,nP=a.XN3,aP=a.OJc,rP=a.Z40,oP=a.v3L,iP=a.QiY,lP=a.Pqo,cP=a.fqH,dP=a.oJL,uP=a.FEt,hP=a.LN6,_P=a.GqW,pP=a.LvX,mP=a.D$4,fP=a.z45,gP=a.qvY,wP=a.rb,yP=a.RWH,xP=a.T$2,bP=a.UaF,kP=a.E6D,vP=a.I04,MP=a.fjb,EP=a.diq,AP=a.nR6,CP=a.oZv,TP=a.EpU,FP=a.Dlv,SP=a.vn6,PP=a.sCu,zP=a.S3$,IP=a.Kul,LP=a.O_r,BP=a.c93,OP=a.qcZ,$P=a.crA,NP=a.TzE,DP=a.TrS,VP=a.VG4,jP=a.dAU,UP=a.j_7,RP=a.j6y,qP=a.fGD,GP=a.vf1,WP=a.Fzc,XP=a.b9b,HP=a.xbg,JP=a._0v,KP=a.qYS,QP=a.H6X,ZP=a.EbS,YP=a.AOe,ez=a.T1P,tz=a.psK,sz=a.iaN,nz=a.sKA,az=a.hTz,rz=a.COx,oz=a.HBQ,iz=a.A4X,lz=a.SNK,cz=a.OP6,dz=a.LsV,uz=a.n_R,hz=a.cU1,_z=a.GNt,pz=a.dp7,mz=a.IzE,fz=a.ct5,gz=a.bGU,wz=a.WIq,yz=a.xI8,xz=a.W5i,bz=a.UqB,kz=a.$gq,vz=a.VeZ,Mz=a.wY7,Ez=a.gxi,Az=a.D_,Cz=a.WFR,Tz=a.w2j,Fz=a.IMK,Sz=a.bg1,Pz=a.xrW,zz=a.h_s,Iz=a.LJl,Lz=a.qLW,Bz=a.ZGD,Oz=a.eJU,$z=a.m1H,Nz=a.GPY,Dz=a.Y_v,Vz=a.uzq,jz=a.KJ,Uz=a.PyP,Rz=a.Ct0,qz=a.Kt3,Gz=a.P_g,Wz=a.cl7,Xz=a.x5Z,Hz=a.fGl,Jz=a.OQ0,Kz=a.bAw,Qz=a.ltw,Zz=a.aGV,Yz=a.dMI,eI=a.i3J,tI=a.YyD,sI=a.RT2,nI=a.K_R,aI=a.AyL,rI=a.Xyp,oI=a.Eh_,iI=a.ag_,lI=a.Pyv,cI=a.zys,dI=a.e25,uI=a.eU0,hI=a.iYt,_I=a.VFU,pI=a.EAC,mI=a.aHU,fI=a.gSt,gI=a.Vf$,wI=a.pgB,yI=a.Fg4,xI=a.I_U,bI=a.d7$,kI=a._Dc,vI=a.cD,MI=a.v11,EI=a.Pzh,AI=a.QJ0,CI=a.czX,TI=a.vGK,FI=a.pJ8,SI=a.OK_,PI=a.klo,zI=a.gN,II=a.jN2,LI=a.GXK,BI=a.Z0G,OI=a.nWJ,$I=a.ajg,NI=a.WLR,DI=a.mjH,VI=a.URg,jI=a.CbL,UI=a.vHC,RI=a.$3d,qI=a.KPo,GI=a.ZUB,WI=a.gEG,XI=a.$qk,HI=a.gJr,JI=a.Omf,KI=a.TyF,QI=a._K2,ZI=a.a2Z,YI=a.ck6,eL=a.dOS,tL=a.kvc,sL=a.s_v,nL=a.GWP,aL=a.vZh,rL=a.vdP,oL=a.WFC,iL=a.l8C,lL=a.vaw,cL=a.BW4,dL=a.CMs,uL=a.VOO,hL=a.DDf,_L=a.T9B,pL=a.i2o,mL=a.X7P,fL=a.jV8,gL=a.Brl,wL=a.jkA,yL=a.SaS,xL=a.oCF,bL=a.Ny6,kL=a.SXi,vL=a.TkF,ML=a.Jaq,EL=a._9M,AL=a._2u,CL=a.z8$,TL=a.LIG,FL=a.dik,SL=a.Vs9,PL=a.OjR,zL=a.t$z,IL=a.cQR,LL=a.rfw,BL=a.E,OL=a.Ul9,$L=a.aFj;export{ix as ASTFeatureExtractor,lx as ASTForAudioClassification,cx as ASTModel,dx as ASTPreTrainedModel,ux as AlbertForMaskedLM,hx as AlbertForQuestionAnswering,_x as AlbertForSequenceClassification,px as AlbertModel,mx as AlbertPreTrainedModel,fx as AlbertTokenizer,gx as AudioClassificationPipeline,wx as AutoConfig,yx as AutoFeatureExtractor,xx as AutoImageProcessor,bx as AutoModel,kx as AutoModelForAudioClassification,vx as AutoModelForAudioFrameClassification,Mx as AutoModelForAudioTextToText,Ex as AutoModelForCTC,Ax as AutoModelForCausalLM,Cx as AutoModelForDepthEstimation,Tx as AutoModelForDocumentQuestionAnswering,Fx as AutoModelForImageClassification,Sx as AutoModelForImageFeatureExtraction,Px as AutoModelForImageMatting,zx as AutoModelForImageSegmentation,Ix as AutoModelForImageTextToText,Lx as AutoModelForImageToImage,Bx as AutoModelForMaskGeneration,Ox as AutoModelForMaskedLM,$x as AutoModelForNormalEstimation,Nx as AutoModelForObjectDetection,Dx as AutoModelForPoseEstimation,Vx as AutoModelForQuestionAnswering,jx as AutoModelForSemanticSegmentation,Ux as AutoModelForSeq2SeqLM,Rx as AutoModelForSequenceClassification,qx as AutoModelForSpeechSeq2Seq,Gx as AutoModelForTextToSpectrogram,Wx as AutoModelForTextToWaveform,Xx as AutoModelForTokenClassification,Hx as AutoModelForUniversalSegmentation,Jx as AutoModelForVision2Seq,Kx as AutoModelForXVector,Qx as AutoModelForZeroShotObjectDetection,Zx as AutoProcessor,Yx as AutoTokenizer,eb as AutomaticSpeechRecognitionPipeline,tb as BackgroundRemovalPipeline,sb as BartForConditionalGeneration,nb as BartForSequenceClassification,ab as BartModel,rb as BartPretrainedModel,ob as BartTokenizer,ib as BaseModelOutput,lb as BaseStreamer,cb as BeitFeatureExtractor,db as BeitForImageClassification,ub as BeitModel,hb as BeitPreTrainedModel,_b as BertForMaskedLM,pb as BertForQuestionAnswering,mb as BertForSequenceClassification,fb as BertForTokenClassification,gb as BertModel,wb as BertPreTrainedModel,yb as BertTokenizer,xb as BitImageProcessor,bb as BlenderbotForConditionalGeneration,kb as BlenderbotModel,vb as BlenderbotPreTrainedModel,Mb as BlenderbotSmallForConditionalGeneration,Eb as BlenderbotSmallModel,Ab as BlenderbotSmallPreTrainedModel,Cb as BlenderbotSmallTokenizer,Tb as BlenderbotTokenizer,Fb as BloomForCausalLM,Sb as BloomModel,Pb as BloomPreTrainedModel,zb as BloomTokenizer,Ib as CLIPFeatureExtractor,Lb as CLIPImageProcessor,Bb as CLIPModel,Ob as CLIPPreTrainedModel,$b as CLIPSegForImageSegmentation,Nb as CLIPSegModel,Db as CLIPSegPreTrainedModel,Vb as CLIPTextModel,jb as CLIPTextModelWithProjection,Ub as CLIPTokenizer,Rb as CLIPVisionModel,qb as CLIPVisionModelWithProjection,Gb as CamembertForMaskedLM,Wb as CamembertForQuestionAnswering,Xb as CamembertForSequenceClassification,Hb as CamembertForTokenClassification,Jb as CamembertModel,Kb as CamembertPreTrainedModel,Qb as CamembertTokenizer,Zb as CausalLMOutput,Yb as CausalLMOutputWithPast,ek as ChineseCLIPFeatureExtractor,tk as ChineseCLIPModel,sk as ChineseCLIPPreTrainedModel,nk as ClapAudioModelWithProjection,ak as ClapFeatureExtractor,rk as ClapModel,ok as ClapPreTrainedModel,ik as ClapTextModelWithProjection,lk as ClassifierFreeGuidanceLogitsProcessor,ck as CodeGenForCausalLM,dk as CodeGenModel,uk as CodeGenPreTrainedModel,hk as CodeGenTokenizer,_k as CodeLlamaTokenizer,pk as CohereForCausalLM,mk as CohereModel,fk as CoherePreTrainedModel,gk as CohereTokenizer,wk as ConvBertForMaskedLM,yk as ConvBertForQuestionAnswering,xk as ConvBertForSequenceClassification,bk as ConvBertForTokenClassification,kk as ConvBertModel,vk as ConvBertPreTrainedModel,Mk as ConvBertTokenizer,Ek as ConvNextFeatureExtractor,Ak as ConvNextForImageClassification,Ck as ConvNextImageProcessor,Tk as ConvNextModel,Fk as ConvNextPreTrainedModel,Sk as ConvNextV2ForImageClassification,Pk as ConvNextV2Model,zk as ConvNextV2PreTrainedModel,Ik as DFineForObjectDetection,Lk as DFineModel,Bk as DFinePreTrainedModel,Ok as DPTFeatureExtractor,$k as DPTForDepthEstimation,Nk as DPTImageProcessor,Dk as DPTModel,Vk as DPTPreTrainedModel,jk as DacDecoderModel,Uk as DacDecoderOutput,Rk as DacEncoderModel,qk as DacEncoderOutput,Gk as DacFeatureExtractor,Wk as DacModel,Xk as DacPreTrainedModel,Hk as DataTypeMap,Jk as DebertaForMaskedLM,Kk as DebertaForQuestionAnswering,Qk as DebertaForSequenceClassification,Zk as DebertaForTokenClassification,Yk as DebertaModel,ev as DebertaPreTrainedModel,tv as DebertaTokenizer,sv as DebertaV2ForMaskedLM,nv as DebertaV2ForQuestionAnswering,av as DebertaV2ForSequenceClassification,rv as DebertaV2ForTokenClassification,ov as DebertaV2Model,iv as DebertaV2PreTrainedModel,lv as DebertaV2Tokenizer,cv as DecisionTransformerModel,dv as DecisionTransformerPreTrainedModel,uv as DeiTFeatureExtractor,hv as DeiTForImageClassification,_v as DeiTImageProcessor,pv as DeiTModel,mv as DeiTPreTrainedModel,fv as DepthAnythingForDepthEstimation,gv as DepthAnythingPreTrainedModel,wv as DepthEstimationPipeline,yv as DepthProForDepthEstimation,xv as DepthProPreTrainedModel,bv as DetrFeatureExtractor,kv as DetrForObjectDetection,vv as DetrForSegmentation,Mv as DetrImageProcessor,Ev as DetrModel,Av as DetrObjectDetectionOutput,Cv as DetrPreTrainedModel,Tv as DetrSegmentationOutput,Fv as Dinov2ForImageClassification,Sv as Dinov2Model,Pv as Dinov2PreTrainedModel,zv as Dinov2WithRegistersForImageClassification,Iv as Dinov2WithRegistersModel,Lv as Dinov2WithRegistersPreTrainedModel,Bv as DistilBertForMaskedLM,Ov as DistilBertForQuestionAnswering,$v as DistilBertForSequenceClassification,Nv as DistilBertForTokenClassification,Dv as DistilBertModel,Vv as DistilBertPreTrainedModel,jv as DistilBertTokenizer,Uv as DocumentQuestionAnsweringPipeline,Rv as DonutFeatureExtractor,qv as DonutImageProcessor,Gv as DonutSwinModel,Wv as DonutSwinPreTrainedModel,Xv as EfficientNetForImageClassification,Hv as EfficientNetImageProcessor,Jv as EfficientNetModel,Kv as EfficientNetPreTrainedModel,Qv as ElectraForMaskedLM,Zv as ElectraForQuestionAnswering,Yv as ElectraForSequenceClassification,eM as ElectraForTokenClassification,tM as ElectraModel,sM as ElectraPreTrainedModel,nM as ElectraTokenizer,aM as EncodecFeatureExtractor,rM as EosTokenCriteria,oM as EsmForMaskedLM,iM as EsmForSequenceClassification,lM as EsmForTokenClassification,cM as EsmModel,dM as EsmPreTrainedModel,uM as EsmTokenizer,hM as ExaoneForCausalLM,_M as ExaoneModel,pM as ExaonePreTrainedModel,mM as FFT,fM as FalconForCausalLM,gM as FalconModel,wM as FalconPreTrainedModel,yM as FalconTokenizer,xM as FastViTForImageClassification,bM as FastViTModel,kM as FastViTPreTrainedModel,vM as FeatureExtractionPipeline,MM as FeatureExtractor,EM as FillMaskPipeline,AM as Florence2ForConditionalGeneration,CM as Florence2PreTrainedModel,TM as Florence2Processor,FM as ForcedBOSTokenLogitsProcessor,SM as ForcedEOSTokenLogitsProcessor,PM as GLPNFeatureExtractor,zM as GLPNForDepthEstimation,IM as GLPNModel,LM as GLPNPreTrainedModel,BM as GPT2LMHeadModel,OM as GPT2Model,$M as GPT2PreTrainedModel,NM as GPT2Tokenizer,DM as GPTBigCodeForCausalLM,VM as GPTBigCodeModel,jM as GPTBigCodePreTrainedModel,UM as GPTJForCausalLM,RM as GPTJModel,qM as GPTJPreTrainedModel,GM as GPTNeoForCausalLM,WM as GPTNeoModel,XM as GPTNeoPreTrainedModel,HM as GPTNeoXForCausalLM,JM as GPTNeoXModel,KM as GPTNeoXPreTrainedModel,QM as GPTNeoXTokenizer,ZM as Gemma2ForCausalLM,YM as Gemma2Model,eE as Gemma2PreTrainedModel,tE as Gemma3ForCausalLM,sE as Gemma3Model,nE as Gemma3PreTrainedModel,aE as GemmaForCausalLM,rE as GemmaModel,oE as GemmaPreTrainedModel,iE as GemmaTokenizer,lE as GlmForCausalLM,cE as GlmModel,dE as GlmPreTrainedModel,uE as GraniteForCausalLM,hE as GraniteModel,_E as GranitePreTrainedModel,pE as Grok1Tokenizer,mE as GroundingDinoForObjectDetection,fE as GroundingDinoImageProcessor,gE as GroundingDinoPreTrainedModel,wE as GroundingDinoProcessor,yE as GroupViTModel,xE as GroupViTPreTrainedModel,bE as HeliumForCausalLM,kE as HeliumModel,vE as HeliumPreTrainedModel,ME as HerbertTokenizer,EE as HieraForImageClassification,AE as HieraModel,CE as HieraPreTrainedModel,TE as HubertForCTC,FE as HubertForSequenceClassification,SE as HubertModel,PE as HubertPreTrainedModel,zE as IJepaForImageClassification,IE as IJepaModel,LE as IJepaPreTrainedModel,BE as Idefics3ForConditionalGeneration,OE as Idefics3ImageProcessor,$E as Idefics3PreTrainedModel,NE as Idefics3Processor,DE as ImageClassificationPipeline,VE as ImageFeatureExtractionPipeline,jE as ImageFeatureExtractor,UE as ImageMattingOutput,RE as ImageProcessor,qE as ImageSegmentationPipeline,GE as ImageToImagePipeline,WE as ImageToTextPipeline,XE as InterruptableStoppingCriteria,HE as JAISLMHeadModel,JE as JAISModel,KE as JAISPreTrainedModel,QE as JinaCLIPImageProcessor,ZE as JinaCLIPModel,YE as JinaCLIPPreTrainedModel,eA as JinaCLIPProcessor,tA as JinaCLIPTextModel,sA as JinaCLIPVisionModel,nA as LiteWhisperForConditionalGeneration,aA as LlamaForCausalLM,rA as LlamaModel,oA as LlamaPreTrainedModel,iA as LlamaTokenizer,lA as LlavaForConditionalGeneration,cA as LlavaOnevisionForConditionalGeneration,dA as LlavaOnevisionImageProcessor,uA as LlavaPreTrainedModel,hA as LogitsProcessor,_A as LogitsProcessorList,pA as LogitsWarper,mA as LongT5ForConditionalGeneration,fA as LongT5Model,gA as LongT5PreTrainedModel,wA as M2M100ForConditionalGeneration,yA as M2M100Model,xA as M2M100PreTrainedModel,bA as M2M100Tokenizer,kA as MBart50Tokenizer,vA as MBartForCausalLM,MA as MBartForConditionalGeneration,EA as MBartForSequenceClassification,AA as MBartModel,CA as MBartPreTrainedModel,TA as MBartTokenizer,FA as MPNetForMaskedLM,SA as MPNetForQuestionAnswering,PA as MPNetForSequenceClassification,zA as MPNetForTokenClassification,IA as MPNetModel,LA as MPNetPreTrainedModel,BA as MPNetTokenizer,OA as MT5ForConditionalGeneration,$A as MT5Model,NA as MT5PreTrainedModel,DA as MarianMTModel,VA as MarianModel,jA as MarianPreTrainedModel,UA as MarianTokenizer,RA as Mask2FormerImageProcessor,qA as MaskFormerFeatureExtractor,GA as MaskFormerForInstanceSegmentation,WA as MaskFormerImageProcessor,XA as MaskFormerModel,HA as MaskFormerPreTrainedModel,JA as MaskedLMOutput,KA as MaxLengthCriteria,QA as Metric3DForDepthEstimation,ZA as Metric3DPreTrainedModel,YA as Metric3Dv2ForDepthEstimation,eC as Metric3Dv2PreTrainedModel,tC as MgpstrForSceneTextRecognition,sC as MgpstrModelOutput,nC as MgpstrPreTrainedModel,aC as MgpstrProcessor,rC as MgpstrTokenizer,oC as MimiDecoderModel,iC as MimiDecoderOutput,lC as MimiEncoderModel,cC as MimiEncoderOutput,dC as MimiModel,uC as MimiPreTrainedModel,hC as MinLengthLogitsProcessor,_C as MinNewTokensLengthLogitsProcessor,pC as MistralForCausalLM,mC as MistralModel,fC as MistralPreTrainedModel,gC as MobileBertForMaskedLM,wC as MobileBertForQuestionAnswering,yC as MobileBertForSequenceClassification,xC as MobileBertModel,bC as MobileBertPreTrainedModel,kC as MobileBertTokenizer,vC as MobileLLMForCausalLM,MC as MobileLLMModel,EC as MobileLLMPreTrainedModel,AC as MobileNetV1FeatureExtractor,CC as MobileNetV1ForImageClassification,TC as MobileNetV1ForSemanticSegmentation,FC as MobileNetV1ImageProcessor,SC as MobileNetV1Model,PC as MobileNetV1PreTrainedModel,zC as MobileNetV2FeatureExtractor,IC as MobileNetV2ForImageClassification,LC as MobileNetV2ForSemanticSegmentation,BC as MobileNetV2ImageProcessor,OC as MobileNetV2Model,$C as MobileNetV2PreTrainedModel,NC as MobileNetV3FeatureExtractor,DC as MobileNetV3ForImageClassification,VC as MobileNetV3ForSemanticSegmentation,jC as MobileNetV3ImageProcessor,UC as MobileNetV3Model,RC as MobileNetV3PreTrainedModel,qC as MobileNetV4FeatureExtractor,GC as MobileNetV4ForImageClassification,WC as MobileNetV4ForSemanticSegmentation,XC as MobileNetV4ImageProcessor,HC as MobileNetV4Model,JC as MobileNetV4PreTrainedModel,KC as MobileViTFeatureExtractor,QC as MobileViTForImageClassification,ZC as MobileViTImageProcessor,YC as MobileViTModel,eT as MobileViTPreTrainedModel,tT as MobileViTV2ForImageClassification,sT as MobileViTV2Model,nT as MobileViTV2PreTrainedModel,aT as ModelOutput,rT as ModernBertForMaskedLM,oT as ModernBertForSequenceClassification,iT as ModernBertForTokenClassification,lT as ModernBertModel,cT as ModernBertPreTrainedModel,dT as Moondream1ForConditionalGeneration,uT as MoonshineFeatureExtractor,hT as MoonshineForConditionalGeneration,_T as MoonshineModel,pT as MoonshinePreTrainedModel,mT as MoonshineProcessor,fT as MptForCausalLM,gT as MptModel,wT as MptPreTrainedModel,yT as MultiModalityCausalLM,xT as MultiModalityPreTrainedModel,bT as MusicgenForCausalLM,kT as MusicgenForConditionalGeneration,vT as MusicgenModel,MT as MusicgenPreTrainedModel,ET as NllbTokenizer,AT as NoBadWordsLogitsProcessor,CT as NoRepeatNGramLogitsProcessor,TT as NomicBertModel,FT as NomicBertPreTrainedModel,ST as NougatImageProcessor,PT as NougatTokenizer,zT as OPTForCausalLM,IT as OPTModel,LT as OPTPreTrainedModel,BT as ObjectDetectionPipeline,OT as Olmo2ForCausalLM,$T as Olmo2Model,NT as Olmo2PreTrainedModel,DT as OlmoForCausalLM,VT as OlmoModel,jT as OlmoPreTrainedModel,UT as OpenELMForCausalLM,RT as OpenELMModel,qT as OpenELMPreTrainedModel,GT as OwlViTFeatureExtractor,WT as OwlViTForObjectDetection,XT as OwlViTImageProcessor,HT as OwlViTModel,JT as OwlViTPreTrainedModel,KT as OwlViTProcessor,QT as Owlv2ForObjectDetection,ZT as Owlv2ImageProcessor,YT as Owlv2Model,eF as Owlv2PreTrainedModel,tF as PaliGemmaForConditionalGeneration,sF as PaliGemmaPreTrainedModel,nF as PaliGemmaProcessor,aF as PatchTSMixerForPrediction,rF as PatchTSMixerModel,oF as PatchTSMixerPreTrainedModel,iF as PatchTSTForPrediction,lF as PatchTSTModel,cF as PatchTSTPreTrainedModel,dF as Phi3ForCausalLM,uF as Phi3Model,hF as Phi3PreTrainedModel,_F as Phi3VForCausalLM,pF as Phi3VImageProcessor,mF as Phi3VPreTrainedModel,fF as Phi3VProcessor,gF as PhiForCausalLM,wF as PhiModel,yF as PhiPreTrainedModel,xF as Pipeline,bF as PreTrainedModel,kF as PreTrainedTokenizer,vF as PretrainedConfig,MF as PretrainedMixin,EF as Processor,AF as PvtForImageClassification,CF as PvtImageProcessor,TF as PvtModel,FF as PvtPreTrainedModel,SF as PyAnnoteFeatureExtractor,PF as PyAnnoteForAudioFrameClassification,zF as PyAnnoteModel,IF as PyAnnotePreTrainedModel,LF as PyAnnoteProcessor,BF as QuestionAnsweringModelOutput,OF as QuestionAnsweringPipeline,$F as Qwen2ForCausalLM,NF as Qwen2Model,DF as Qwen2PreTrainedModel,VF as Qwen2Tokenizer,jF as Qwen2VLForConditionalGeneration,UF as Qwen2VLImageProcessor,RF as Qwen2VLPreTrainedModel,qF as Qwen2VLProcessor,GF as Qwen3ForCausalLM,WF as Qwen3Model,XF as Qwen3PreTrainedModel,HF as RFDetrForObjectDetection,JF as RFDetrModel,KF as RFDetrObjectDetectionOutput,QF as RFDetrPreTrainedModel,ZF as RTDetrForObjectDetection,YF as RTDetrImageProcessor,eS as RTDetrModel,tS as RTDetrObjectDetectionOutput,sS as RTDetrPreTrainedModel,nS as RTDetrV2ForObjectDetection,aS as RTDetrV2Model,rS as RTDetrV2ObjectDetectionOutput,oS as RTDetrV2PreTrainedModel,iS as RawAudio,lS as RawImage,cS as RawVideo,dS as RawVideoFrame,uS as RepetitionPenaltyLogitsProcessor,hS as ResNetForImageClassification,_S as ResNetModel,pS as ResNetPreTrainedModel,mS as RoFormerForMaskedLM,fS as RoFormerForQuestionAnswering,gS as RoFormerForSequenceClassification,wS as RoFormerForTokenClassification,yS as RoFormerModel,xS as RoFormerPreTrainedModel,bS as RoFormerTokenizer,kS as RobertaForMaskedLM,vS as RobertaForQuestionAnswering,MS as RobertaForSequenceClassification,ES as RobertaForTokenClassification,AS as RobertaModel,CS as RobertaPreTrainedModel,TS as RobertaTokenizer,FS as SamImageProcessor,SS as SamImageSegmentationOutput,PS as SamModel,zS as SamPreTrainedModel,IS as SamProcessor,LS as SapiensForDepthEstimation,BS as SapiensForNormalEstimation,OS as SapiensForSemanticSegmentation,$S as SapiensPreTrainedModel,NS as SeamlessM4TFeatureExtractor,DS as SegformerFeatureExtractor,VS as SegformerForImageClassification,jS as SegformerForSemanticSegmentation,US as SegformerImageProcessor,RS as SegformerModel,qS as SegformerPreTrainedModel,GS as Seq2SeqLMOutput,WS as SequenceClassifierOutput,XS as SiglipImageProcessor,HS as SiglipModel,JS as SiglipPreTrainedModel,KS as SiglipTextModel,QS as SiglipTokenizer,ZS as SiglipVisionModel,YS as SmolVLMForConditionalGeneration,eP as SmolVLMImageProcessor,tP as SmolVLMProcessor,sP as SnacDecoderModel,nP as SnacEncoderModel,aP as SnacFeatureExtractor,rP as SnacModel,oP as SnacPreTrainedModel,iP as SpeechT5FeatureExtractor,lP as SpeechT5ForSpeechToText,cP as SpeechT5ForTextToSpeech,dP as SpeechT5HifiGan,uP as SpeechT5Model,hP as SpeechT5PreTrainedModel,_P as SpeechT5Processor,pP as SpeechT5Tokenizer,mP as SqueezeBertForMaskedLM,fP as SqueezeBertForQuestionAnswering,gP as SqueezeBertForSequenceClassification,wP as SqueezeBertModel,yP as SqueezeBertPreTrainedModel,xP as SqueezeBertTokenizer,bP as StableLmForCausalLM,kP as StableLmModel,vP as StableLmPreTrainedModel,MP as Starcoder2ForCausalLM,EP as Starcoder2Model,AP as Starcoder2PreTrainedModel,CP as StoppingCriteria,TP as StoppingCriteriaList,FP as StyleTextToSpeech2Model,SP as StyleTextToSpeech2PreTrainedModel,PP as SummarizationPipeline,zP as SuppressTokensAtBeginLogitsProcessor,IP as Swin2SRForImageSuperResolution,LP as Swin2SRImageProcessor,BP as Swin2SRModel,OP as Swin2SRPreTrainedModel,$P as SwinForImageClassification,NP as SwinForSemanticSegmentation,DP as SwinModel,VP as SwinPreTrainedModel,jP as T5ForConditionalGeneration,UP as T5Model,RP as T5PreTrainedModel,qP as T5Tokenizer,GP as TableTransformerForObjectDetection,WP as TableTransformerModel,XP as TableTransformerObjectDetectionOutput,HP as TableTransformerPreTrainedModel,JP as TemperatureLogitsWarper,KP as Tensor,QP as Text2TextGenerationPipeline,ZP as TextClassificationPipeline,YP as TextGenerationPipeline,ez as TextStreamer,tz as TextToAudioPipeline,sz as TokenClassificationPipeline,nz as TokenClassifierOutput,az as TokenizerModel,rz as TopKLogitsWarper,oz as TopPLogitsWarper,iz as TrOCRForCausalLM,lz as TrOCRPreTrainedModel,cz as TranslationPipeline,dz as UltravoxModel,uz as UltravoxPreTrainedModel,hz as UltravoxProcessor,_z as UniSpeechForCTC,pz as UniSpeechForSequenceClassification,mz as UniSpeechModel,fz as UniSpeechPreTrainedModel,gz as UniSpeechSatForAudioFrameClassification,wz as UniSpeechSatForCTC,yz as UniSpeechSatForSequenceClassification,xz as UniSpeechSatModel,bz as UniSpeechSatPreTrainedModel,kz as VLChatProcessor,vz as VLMImageProcessor,Mz as ViTFeatureExtractor,Ez as ViTForImageClassification,Az as ViTImageProcessor,Cz as ViTMAEModel,Tz as ViTMAEPreTrainedModel,Fz as ViTMSNForImageClassification,Sz as ViTMSNModel,Pz as ViTMSNPreTrainedModel,zz as ViTModel,Iz as ViTPreTrainedModel,Lz as VisionEncoderDecoderModel,Bz as VitMatteForImageMatting,Oz as VitMatteImageProcessor,$z as VitMattePreTrainedModel,Nz as VitPoseForPoseEstimation,Dz as VitPoseImageProcessor,Vz as VitPosePreTrainedModel,jz as VitsModel,Uz as VitsModelOutput,Rz as VitsPreTrainedModel,qz as VitsTokenizer,Gz as Wav2Vec2BertForCTC,Wz as Wav2Vec2BertForSequenceClassification,Xz as Wav2Vec2BertModel,Hz as Wav2Vec2BertPreTrainedModel,Jz as Wav2Vec2CTCTokenizer,Kz as Wav2Vec2FeatureExtractor,Qz as Wav2Vec2ForAudioFrameClassification,Zz as Wav2Vec2ForCTC,Yz as Wav2Vec2ForSequenceClassification,eI as Wav2Vec2Model,tI as Wav2Vec2PreTrainedModel,sI as Wav2Vec2Processor,nI as Wav2Vec2ProcessorWithLM,aI as WavLMForAudioFrameClassification,rI as WavLMForCTC,oI as WavLMForSequenceClassification,iI as WavLMForXVector,lI as WavLMModel,cI as WavLMPreTrainedModel,dI as WeSpeakerFeatureExtractor,uI as WeSpeakerResNetModel,hI as WeSpeakerResNetPreTrainedModel,_I as WhisperFeatureExtractor,pI as WhisperForConditionalGeneration,mI as WhisperModel,fI as WhisperPreTrainedModel,gI as WhisperProcessor,wI as WhisperTextStreamer,yI as WhisperTimeStampLogitsProcessor,xI as WhisperTokenizer,bI as XLMForQuestionAnswering,kI as XLMForSequenceClassification,vI as XLMForTokenClassification,MI as XLMModel,EI as XLMPreTrainedModel,AI as XLMRobertaForMaskedLM,CI as XLMRobertaForQuestionAnswering,TI as XLMRobertaForSequenceClassification,FI as XLMRobertaForTokenClassification,SI as XLMRobertaModel,PI as XLMRobertaPreTrainedModel,zI as XLMRobertaTokenizer,II as XLMTokenizer,LI as XLMWithLMHeadModel,BI as XVectorOutput,OI as YolosFeatureExtractor,$I as YolosForObjectDetection,NI as YolosImageProcessor,DI as YolosModel,VI as YolosObjectDetectionOutput,jI as YolosPreTrainedModel,UI as ZeroShotAudioClassificationPipeline,RI as ZeroShotClassificationPipeline,qI as ZeroShotImageClassificationPipeline,GI as ZeroShotObjectDetectionPipeline,WI as bankers_round,XI as cat,HI as cos_sim,JI as dot,KI as dynamic_time_warping,QI as env,ZI as full,YI as full_like,eL as getKeyValueShapes,tL as hamming,sL as hanning,nL as interpolate,aL as interpolate_4d,rL as interpolate_data,oL as is_chinese_char,iL as layer_norm,lL as load_image,cL as load_video,dL as log_softmax,uL as magnitude,hL as matmul,_L as max,pL as mean,mL as mean_pooling,fL as medianFilter,gL as mel_filter_bank,wL as min,yL as ones,xL as ones_like,bL as permute,kL as permute_data,vL as pipeline,ML as quantize_embeddings,EL as rand,AL as read_audio,CL as rfft,TL as round,FL as slice,SL as softmax,PL as spectrogram,zL as stack,IL as std_mean,LL as topk,BL as window_function,OL as zeros,$L as zeros_like};